DO NOT EDIT! This file was generated automatically by 'qcbuild --makedoc' tool.
| Title: | LibCGI |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki <sw143@wp.pl> |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Set up environment for CGI/C++ program. |
| Description: | It handles _GET[], _POST[] and _COOKIE[] arrays like PHP. |
| Dependences: | LibSSMap LibStr LibFile LibDebug |
| Used by: |
string CgiUrlDecode
(
string SRC
);
Decode URL string.
SRC - URL encoded string (IN).
RETURNS: Decoded string.
string CgiUrlEncode
(
string str
);
Encode arbitral string to URL.
str - string to encode (IN).
RETURNS: URL encoded string.
int CgiDecodeUserVars
(
SSMap &ssmap,
char * userData,
const char delim
);
Decode QUERY string to {lvalue |-> rvalue} map.
ssmap - {lvalue |-> rvalue} map with decoded variables (OUT)
userData - raw url encoded query get string (IN).
delim - what is delim char to use (default '&') (IN/OPT).
RETURNS: 0 if OK.
string CgiEncodeUserVars
(
SSMap &ssmap
);
Create QUERY string from string |-> string map.
int CgiInit
(
);
Init CGI library.
MUST be called one time before first use.
RETURNS: 0 if OK.
const char * CgiGet
(
const char * lvalue
);
Retrieve value of given GET variable.
lvalue - name of variable to found (IN).
RETURNS: Pointer to variable value or NULL if not found.
void CgiHashAdd
(
string &hash,
const string &str
);
void CgiHashAdd
(
string &hash,
int value
);
Don't be sucker! Describe your function in source code.
void CgiHashArgs
(
string &hash
);
Default hash function.
Works always, but may be ineficient in general case.
Should be reimplemented in derived to fit case sensitive,
local characters, arguments order etc.
RETURNS: none.
| Title: | LibNet |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | General mid-level and high-level network functions. |
| Description: | - |
| Dependences: | LibDebug LibThread LibMath |
| Used by: | Tegenaria-net LibSftp LibSftp-example01-sftp-client LibSecure-example01-callbacks LibSecure-example02-socket LibSecure-example04-hp-server LibNet-example01-thread-server LibNet-example02-single LibNet-example05-HP-server libnet-example07-echo-server libnet-example08-echo-client libnet-example09-smtp-client libnet-example10-statistics LibIO-example02-network-mixer |
- Hide NetStatistics implementation.
NetConnection::NetConnection
(
const void * ctx,
const char * protocol,
int socket,
NetHandleConnProto handler,
ThreadHandle_t * thread
);
Constructor.
ctx - caller specified context (IN).
protocol - artbitrary protocol name e.g. "TCP/IP" (IN).
socket - asociatet socket number, can be -1 if not needed (IN/OPT).
handler - callback to handle incoming connections (IN/OPT).
thread - asociated thread handle (IN/OPT).
NetConnection::~NetConnection
(
);
Desctructor. Shutdown connection to force flush.
int NetConnection::write
(
const void * buf,
int count,
int timeout
);
Send <count> bytes stored in <buf>.
buf - source buffer where data to write stored (IN).
count - number of bytes to send (IN).
timeout - timeout in miliseconds (IN).
RETURNS: Number of bytes written or
-1 if error.
int NetConnection::read
(
void * buf,
int count,
int timeout
);
Reveive up to <count> bytes and store them in <buf>.
buf - destination buffer where to store readed data (OUT).
count - expecting number of bytes to be readed (IN).
timeout - timeout in miliseconds (IN).
RETURNS: Number of bytes readed or
-1 if error.
void NetConnection::cancel
(
);
Cancel all pending I/O associated with connection (if any).
int NetConnection::shutdown
(
int how
);
Shutdown connection.
int NetConnection::join
(
);
Wait until connection finished work.
int NetConnection::readCallback
(
void * buf,
int count,
int timeout,
void * ctx
);
Static wrappers for read/write methods to be compatible with pure C code.
Ctx means this pointer (NetConnection object).
Used to pass read/write callback to IOMixer without adding dependency
on LibNet.
To pass read/write method to another C code we need to pass 2 values:
- this pointer ('this')
- pointer to NetConnection::readCallback ('callback')
After that third C code can use it by calling:
callback(buf, count, timeout, this)
int NetConnection::writeCallback
(
void * buf,
int count,
int timeout,
void * ctx
);
Don't be sucker! Describe your function in source code.
void NetConnection::cancelCallback
(
void * ctx
);
Don't be sucker! Describe your function in source code.
int NetConnection::request
(
int * serverCode,
char * serverMsg,
int serverMsgSize,
int timeout,
const char * fmt
);
- Send single, printf like formatted request to server
- read answer in format 'XYZ > message'
- split answer to <XYZ> code and <message> parts.
Example usage:
request(&serverCode, serverMsg, sizeof(serverMsg),
"share --alias %s --path %s", alias, path);
TIP: If only exit code is needed <answer> can be set to NULL.
serverCode - exit code returned by server (OUT).
serverMsg - ASCIZ message returned by server (OUT/OPT).
serverMsgSize - size of answer buffer in bytes (IN).
timeout - timeout in ms, defaulted to infinite if -1 (IN/OPT).
fmt - printf like parameters to format command to send (IN).
RETURNS: 0 if request sucessfuly sent and asnwer from server received.
-1 otherwise.
WARNING!: Request could still failed on server side.
To get server's side exit code use 'answerCode' parameter.
const void * NetConnection::getContext
(
);
Get back caller context passed to constructor if any.
const char * NetConnection::getProtocol
(
);
Get back protocol passed to constructor if any.
int NetConnection::getSocket
(
);
Get back socket passed to constructor if any.
NetHandleConnProto NetConnection::getHandler
(
);
Get back handler function passed to constructor if any.
const char * NetConnection::getClientInfo
(
);
Get string with information about remote client.
void NetConnection::addRef
(
);
Increase refference counter.
WARNING! Every call to addRef() MUSTS be followed by one release() call.
TIP #1: Object will not be destroyed until refference counter is greater
than 0.
TIP #2: Don't call destructor directly, use release() instead. If
refference counter achieve 0, object will be destroyed
automatically.
void NetConnection::release
(
);
Decrease refference counter increased by addRef() before.
int NetConnection::setState
(
int state
);
Set connection state. See NET_STATE_XXX defines in LibNet.h for
possible states.
state - one of NET_STATE_XXX state defined in LibNet.h (IN).
RETURNS: 0 if OK.
int NetConnection::getState
(
);
Get back current connection state set by setState() before.
int NetConnection::waitForState
(
int state,
int timeout
);
Wait until connection reach given state or timeout.
state - target state, which should be set (IN).
timeout - timeout limit in ms. Defaulted to infinite if -1. (IN/OPT).
RETURNS: 0 if target status reached,
-1 otherwise.
void NetConnection::setNoDelay
(
int value
);
Disable nagle algorithm on given connection if possible.
value - 1 to disable algo, 0 to enable it back (IN).
void NetConnection::setKeepAlive
(
int interval
);
Enable SO_KEEPALIVE flag, it keeps connections active by
enabling the periodic transmission of messages.
interval - -1 to disable SO_KEEPALIVE, above 0 will set time
in seconds between individual keepalive probes.
ThreadHandle_t * NetConnection::getThread
(
);
Get back thread handle set in costructor or by setThread() later.
void NetConnection::setThread
(
ThreadHandle_t * thread
);
Set thread handle associated with object.
thread - thread handle created by threadCreate() before (IN).
int NetConnection::authorize
(
const void * authData,
int authDataSize
);
Authroize connection if needed.
RETURNS: 0 if OK.
int NetConnection::getAuthData
(
void * authData,
int authDataSize
);
Get authorization data needed to be passed to another side if needed.
RETURNS: 0 if OK.
int NetConnection::disableInherit
(
);
Disable inherit to child process (exec).
RETURNS: 0 if OK.
int NetConnection::isPointerCorrect
(
NetConnection * ptr
);
Check is given this pointer points to correct NetConnection *object.
ptr - this pointer to check (IN).
RETURNS: 1 if given pointer points to correct net connection object,
0 otherwise.
void NetConnection::setQuietMode
(
int value
);
Set quiet mode to avoid printing error message longer.
int NetParseAddress
(
char * ip1,
char * ip2,
int * port,
const char * address
);
Split network address string into ip and port parts.
WARNING: ip1, ip2 buffers MUST have at least 16 bytes length
if specified.
ip1 - buffer, where to store recognized ip (eg. "1.2.3.4").
Can be NULL. (OUT/OPT).
ip2 - buffer where to store second ip if UPNP scheme detected.
Set to empty string if UPNP not detected. Can be NULL. (OUT/OPT).
port - recognized port number. Can be NULL. (OUT/OPT).
address - input address to parse e.g. "127.0.0.1:80" (IN).
RETURNS: 0 if OK,
-1 if string not recognized as net address.
const string NetGetPortState
(
int port,
const char * protocol
);
Run underlying netstat command and return state string of
given network port.
port - port number check e.g. 80 (IN).
protocol - protocol string, defaulted to TCP (IN/OPT).
RETURNS: Status string e.g. TIME_WAIT or
"-" if port not opened or error.
int NetIsPortOpen
(
int port,
const char * protocol
);
Check is given port opened in any state.
port - port number to check e.g. 80 (IN).
protocol - protocol string, defaulted to TCP (IN/OPT).
RETURNS: 1 if port opened,
0 if port NOT opened or error.
int NetGetFreePort
(
const char * protocol
);
Find random unused port.
protocol - protocol string, defaulted to "TCP" if skipped (IN/OPT).
RETURNS: First found unused port or
-1 if error.
int NetIsPortClosed
(
int port,
const char * protocol
);
Check is given port closed in any state.
port - port number to check e.g. 80 (IN).
protocol - protocol string, defaulted to TCP (IN/OPT).
RETURNS: 1 if port opened,
0 if port NOT opened or error.
int NetSetFDsLimit
(
int limit
);
Set limit of maximum opened FD for current user.
limit - new limit to set (IN).
RETURNS: 0 if OK.
int NetGetCpuNumber
(
);
Return number of CPU cores installed on system.
int NetGetLocalIp
(
char * ip,
int ipSize
);
Retrieve IP of current running machine e.g. 10.0.0.14.
ip - buffer, where to store retrieved ip of local machine (OUT).
ipSize - size of ip[] buffer in bytes (IN).
RETURNS: 0 if OK.
int NetSetNonBlockMode
(
int sock
);
Switch socket to non-block mode.
RETURNS: 0 if OK.
int NetSetBlockMode
(
int sock
);
Switch socket to block mode.
RETURNS: 0 if OK.
int NetResolveIp
(
vector<string> &ips,
const char * host
);
Resolve ip adresses for given host name.
ips - list of found IP addresses (OUT).
host - host name to resolve e.g. "google.pl" (IN).
RETURNS: 0 if OK,
-1 otherwise.
string NetBase64
(
const char * data,
int size
);
Encode data to base64 string.
data - binary data to encode (IN).
size - size of data[] buffer in bytes (IN).
RETURNS: base64 string.
int NetServerLoop
(
NetConnection * nc
);
Don't be sucker! Describe your function in source code.
NetConnection * NetServerCreate
(
int port,
NetHandleConnProto handler,
void * custom
);
Start up TCP server in background thread.
handler - callback routine to handle incoming connections (IN).
custom - custom, caller specified data passed to handler directly
inside NetConnection struct as 'ctx' (IN/OPT).
port - listening port (IN).
RETURNS: Pointer to server side connection,
or NULL if error.
NetConnection * NetAccept
(
int port,
int timeout
);
Create listening TCP/IP4 socket and wait for one client.
After connection negociated, listening socket is shutted down.
WARNING: Caller MUST release received net connection object by
calling nc -> release() method on it.
port - listening port (IN).
timeout - maximum listening time in miliseconds. Defaulted to infinite if -1 (IN/OPT).
RETURNS: Pointer to server side connection,
or NULL if error.
int NetTryBind
(
int port
);
Try create listening socket on given port.
port - listening port (IN).
RETURNS: 0 if socket can be created (port free)
-1 otherwise.
int NetCreateListenSocket
(
int port,
int maxConnections,
int nonBlock
);
Create listening socket on given port.
queue.
port - port number, where to start litsening (IN).
maxConnections - maximum allowed number of incoming connections (IN).
nonBlock - create non-blocking socket if set to 1 (IN).
RETURNS: Listening socket
or -1 if error.
NetConnection * NetConnect
(
const char * host,
int port,
int timeout
);
Open connection to server.
host - server's ip address or hostname eg. "google.pl" (IN).
port - port, on which server is listening (IN).
timeout - timeout in miliseconds (IN/OPT).
RETURNS: Pointer to new allocated NetConnection or
NULL if error.
WARNING: Caller MUST delete returned NetConnection object.
TIP: Use read/write method fro NetConnection to communicate with
remote host.
int NetRequest
(
int fd[2],
int * serverCode,
char * serverMsg,
int serverMsgSize,
const char * fmt
);
Don't be sucker! Describe your function in source code.
int NetHpServerLoop
(
int port,
NetHpOpenProto openHandler,
NetHpCloseProto closeHandler,
NetHpDataProto dataHandler
);
Create TCP server based on IO Completion Ports (WIndows)
or epoll (Linux).
port - listening port (IN).
openHandler - handler called when new connection arrived (IN/OPT).
closeHandler - handler called when existing connection closed (IN/OPT).
dataHandler - handler called when something to read on one of existing
connection (IN).
TIP #1: Use NetHpWrite() to write data inside data handler. Don't
use write() or send() directly.
RETURNS: 0 if terminated correctly by NetIocpServerKill(),
-1 if error.
int NetHpWrite
(
NetHpContext * ctx,
int fd,
void * buf,
int len
);
Write <len> bytes to FD received inside NetHpData handler called
from NetHpServerLoop().
TIP #1: Caller should use this function to write data
to client inside data handler specified to
NetIocpServerLoop(). Don't use write() or send() directly.
ctx - context received in data handler parameters (IN).
fd - related FD where to write data (IN).
buf - buffer with data to write (IN).
len - how many bytes to write (IN).
RETURNS: Number of bytes written or
-1 if error.
int NetSmtpReadServerAnswer
(
int * smtpCode,
char * msg,
int msgSize,
NetConnection * nc
);
Read SMTP server response in 'XXX message' format.
smtpCode - SMTP response code (OUT).
msg - buffer, where to put server message (OUT).
msgSize - size of msg[] buffer in bytes (IN).
nc - pointer NetConnection object connected to SMTP server (IN).
RETURNS: 0 if OK.
int NetSmtpSendMail
(
const char * smtpHost,
int smtpPort,
const char * from,
const char * fromFull,
const char * subject,
vector<string> receivers,
const char * message,
const char * login,
const char * password
);
Send email using existing SMTP server.
smtpHost - hostname of smtp server to use e.g. "smtp.wp.pl" (IN).
smtpPort - port, where smtp server listening. Default is 25. (IN).
from - from field in email e.g. login@wp.pl (IN).
subject - subject field in email (IN).
receivers - list of destination email addresses (IN).
message - message field in email (IN).
login - login to authenticate on smtp server (IN).
password - password to authenticate on smtp server (IN).
RETURNS: 0 if OK,
-1 otherwise.
int NetFirewallRuleAdd
(
const char * name,
const char * group,
const char * desc,
const char * appPath,
int protocol
);
Add firewall rule.
WARNING: Function needs admin privileges.
name - name of rule (IN).
group - name of rule's group (IN).
desc - rule's description (IN).
appPath - full path to target application (IN).
RETURNS: 0 if OK.
int NetFirewallRuleDel
(
const char * name
);
Remove firewall rule.
WARNING: Function needs admin privileges.
name - name of rule to remove (IN).
RETURNS: 0 if OK.
| Title: | LibNetEx |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | High-level network functions depending on third part libraries. |
| Description: | - |
| Dependences: | libevent LibDebug LibLock LibThread LibSecure |
| Used by: | LibNetEx-example01-hp-server LibNetEx-example02-tls-server |
int NetExHpServerWorkerLoop
(
NetExHpContext * ctx
);
Internal use only. Thread function falling into main libevent loop.
We create one libevent loop for every CPU core inside NetExHpServerLoop().
ctx - HP context created inside NetExHpServerLoop() (IN).
int NetExHpSecureServerLoop
(
int port,
NetExHpOpenProto openHandler,
NetExHpCloseProto closeHandler,
NetExHpDataProto dataHandler,
const char * secureCert,
const char * securePrivKey,
const char * securePrivKeyPass
);
Create TCP server based on libevent library. Traffic is encrypted
basing on TLS protocol.
port - listening port (IN).
openHandler - handler called when new connection arrived (IN/OPT).
closeHandler - handler called when existing connection closed (IN/OPT).
dataHandler - handler called when something to read on one of existing
connection (IN).
secureCert - filename, where server certificate is stored (IN).
securePrivKey - filename, where server private key is stored (server side
only) (IN/OPT).
securePrivKeyPass - passphrase to decode private key. Readed from keyboard
if skipped (IN/OPT).
TIP #1: Use NetExHpWrite() to write data inside data handler. Don't
use write() or send() directly.
RETURNS: never reached in correct work,
-1 if error.
int NetExHpServerLoop
(
int port,
NetExHpOpenProto openHandler,
NetExHpCloseProto closeHandler,
NetExHpDataProto dataHandler
);
Create TCP server based on libevent library.
port - listening port (IN).
openHandler - handler called when new connection arrived (IN/OPT).
closeHandler - handler called when existing connection closed (IN/OPT).
dataHandler - handler called when something to read on one of existing
connection (IN).
TIP #1: Use NetExHpWrite() to write data inside data handler. Don't
use write() or send() directly.
TIP #2: Use NetExHpSecureServerLoop() to create TLS encrypted server.
RETURNS: never reached in correct work,
-1 if error.
int NetExHpWrite
(
NetExHpContext * ctx,
void * buf,
int len
);
Write <len> bytes remote client related with given NetExHpContext.
TIP #1: Caller should use this function to write data
to remote client inside data handler specified to
NetExServerLoop(). Don't use write() or send() directly.
ctx - context received in data handler parameters (IN).
buf - buffer with data to write (IN).
len - how many bytes to write (IN).
RETURNS: Number of bytes written or
-1 if error.
static void NetExHpOpenCallback
(
evutil_socket_t fd,
short ev,
void * data
);
Callback called when new connection arrived.
static void NetExHpReadCallback
(
struct bufferevent * bev,
void * data
);
Callback called when new data arrived.
static void NetExHpEventCallback
(
struct bufferevent * bev,
short events,
void * data
);
Callback called when connection closed.
static void NetExHpExitCallback
(
evutil_socket_t sig,
short events,
void * data
);
Callback called when SIGINT handled.
int NetExGetCpuNumber
(
);
Return number of CPU cores installed on system.
| Title: | LibSecure |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Wrap unsecure connection into secure one, generate cryptografically strong random numbers, encrypt/decrypt raw buffers. |
| Description: | - |
| Dependences: | OpenSSL LibDebug LibLock |
| Used by: | Tegenaria-core LibNetEx LibSecure-example01-callbacks LibSecure-example02-socket LibSecure-example03-random LibSecure-example04-hp-server LibSecure-example05-encrypt LibSecure-example06-hash LibSecure-example07-read-pass LibSecure-example08-acl libnet-example09-smtp-client |
-------------------------------------------------------------------------------
Secure connection
-------------------------------------------------------------------------------
1. Init
-------
1. To wrap existing non-encrypted connection into encrypted one (TLS) use
one of SecureConnectionCreate() functions family.
Input non-encrypted connection can be defined as:
- FD pair
- socket
- {read, write} callbacks
2. To start TLS session:
------------------------
Server needs:
- certificate file (cert parameter)
- private key file (privKey paramter)
Client needs:
- nothing (cert and privKey parameters should be NULL)
3. Server skeleton code:
------------------------
sc = SecureConnectionCreate(SECURE_INTENT_SERVER, ..., cert, privateKey);
sc -> read(...);
sc -> write(...);
sc -> release();
4. Client skeleton code:
------------------------
sc = SecureConnectionCreate(SECURE_INTENT_CLIENT, ..., NULL, NULL);
sc -> write(...);
sc -> read(...);
sc -> release();
static int Win64NotImportedError
(
);
Don't be sucker! Describe your function in source code.
int SecureConnection::writeRaw
(
const void * buf,
int len,
int timeout
);
Write <len> bytes directly to underlying IO skipping SSL object beetwen.
Used internally only.
buf - source buffer with data, which we want to write (IN).
len - number of bytes to write (IN).
timeout - timeout in ms, set to -1 for infinite (IN).
RETURNS: Number of bytes written or
-1 if error.
int SecureConnection::readRaw
(
void * buf,
int len,
int timeout
);
Read data directly from underlying IO (without parsing it via SSL
object).
Used internally only.
buf - destination buffer, where to write readed data (OUT).
len - number of bytes to read (IN).
timeout - timeout in ms, set -1 to infinity (IN).
RETURNS: Number of bytes readed or
-1 if error.
int SecureConnection::encrypt
(
void * encrypted,
int encryptedSize,
const void * buffer,
int bufferSize
);
Encrypt message.
encrypted - buffer, where to store encrypted message (OUT).
encryptedSize - size of encrypted[] buffer in bytes (IN).
buffer - source buffer with data to encrypt (IN).
bufferSize - number of bytes to be encrypted (IN).
RETURNS: Length of encrypted data written to encrypted[] in bytes or
-1 if error.
int SecureConnection::decrypt
(
void * decrypted,
int decryptedSize,
const void * buffer,
int bufferSize
);
Decrypt message.
decrypted - buffer, where to store decrypted message (OUT).
decryptedSize - size of decrypted[] buffer in bytes (IN).
buffer - source buffer with data to be decrypt (IN).
bufferSize - number of bytes to be decrypted (IN).
RETURNS: Length of decrypted data written to decrypted[] in bytes or
-1 if error.
int SecureConnection::write
(
const void * buf,
int len,
int timeout
);
Write <len> bytes throught secure connection.
buf - source buffer with data, which we want to write (IN).
len - number of bytes to write (IN).
timeout - timeout in ms, set to -1 for infinite (IN).
RETURNS: Number of bytes written or
-1 if error.
int SecureConnection::read
(
void * buf,
int len,
int timeout
);
Read data from secure connection.
buf - destination buffer, where to write readed data (OUT).
len - number of bytes to read (IN).
timeout - timeout in ms, set -1 to infinite (IN)
RETURNS: Number of bytes readed or
-1 if error.
int SecureConnection::request
(
int * serverCode,
char * serverMsg,
int serverMsgSize,
int timeout,
const char * fmt
);
- Send single, printf like formatted request to server
- read answer in format 'XYZ > message'
- split answer to <XYZ> code and <message> parts.
Example usage:
request(&serverCode, serverMsg, sizeof(serverMsg),
"share --alias %s --path %s", alias, path);
TIP: If only exit code is needed <answer> can be set to NULL.
sc - pointer to SecureConnection object connected to server (IN).
serverCode - exit code returned by server (OUT).
serverMsg - ASCIZ message returned by server (OUT/OPT).
serverMsgSize - size of answer buffer in bytes (IN).
timeout - timeout in ms, defaulted to infinite if -1 (IN/OPT).
fmt - printf like parameters to format command to send (IN).
RETURNS: 0 if request sucessfuly sent and asnwer from server received.
-1 otherwise.
WARNING!: Request could still failed on server side.
To get server's side exit code use 'answerCode' parameter.
SecureConnection::~SecureConnection
(
);
Desctroy secure connection created by SecureConnectionCreate() before.
int SecureConnection::handshakeStep
(
void * customBuffer,
int * customSize
);
Perform underlying SSL handshake to init encrypted secure connection.
Internal use only.
TIP#1: For custom connection use 5-parameter SecureHandshakeStep.
TIP#2: For non-custom connections (underlying IO is set to callbacks,
socket or FDs pair} handshake is performed automatically in
SecureConnectionCreate. No manually work needed.
WARNING! Handshake must be performed before any data would be send
via SecureWrite() or read via SecureRead() functions.
Parameters:
customBuffer - on input data treated as readed from underlying IO if IOMODE
set to NONE. On output data needed to be written to
underlying IO. (IN/OUT/OPT).
customSize - on input size of customBuffer[] in bytes if IOMODE set to
NONE. On output number of bytes returned in customBuffer[]
and needed to be written back to underlying IO (IN/OUT/OPT).
RETURNS: 0 if OK.
int SecureConnection::handshakeStep
(
void * outputBuffer,
int * outputSize,
void * inputBuffer,
int inputSize
);
Handshake step for custom connection (iomode set to none).
TIP#1: This function should be used to perform manually handshake when
underlying IO is set to NONE (i.e. custom secure connection).
TIP#2: Before call, caller should read data from underlying IO manually
and pass it in {inputBuffer, inputSize} parameters.
TIP#3: After call, caller should write data returned in
{outputBuffer, outputSize} to underlying IO manually.
Caller algorithm to do handshake manually:
while(sc -> state != SECURE_STATE_ESTABLISHED)
{
Read data from underlying IO to inputBuffer[].
Call SecureHandshakeStep(inputBuffer, ..., outputBuffer, ...)
Write data from outputBuffer[] to underlying IO.
}
sc - secure connection object returned from SecureConnectionCreate() (IN).
outputBuffer - data needed to be written to underlying IO by caller (OUT).
outputSize - on input size of outputBuffer[] in bytes, on output number
of bytes written to outputBuffer[] (IN/OUT).
inputBuffer - data readed from underlying IO (IN).
inputSize - size of inputBuffer[] in bytes (IN).
RETURNS: 0 if OK.
SecureConnection::SecureConnection
(
);
Create empty secure connection object.
Used internally only.
TIP#1: Don't create SecureConnection object directly.
Use one of SecureConnectionCreate() function instead.
int SecureConnection::initSSL
(
int intent,
const char * cert,
const char * privKey,
const char * privKeyPass
);
Initialize SSL DTLS connection inside secure connection object.
Internal use only by SecureConnectionCreate().
RETURNS: 0 if OK.
void SecureConnection::addRef
(
);
Increase refference counter.
WARNING! Every call to addRef() MUSTS be followed by one release() call.
TIP #1: Object will not be destroyed until refference counter is greater
than 0.
TIP #2: Don't call destructor directly, use release() instead. If
refference counter achieve 0, object will be destroyed
automatically.
void SecureConnection::release
(
);
Decrease refference counter increased by addRef() before and
desroy object when it's refference counter reach 0.
int SecureConnection::getState
(
);
Don't be sucker! Describe your function in source code.
SecureConnection * SecureConnectionCreate
(
int intent,
SecureReadProto readCallback,
SecureWriteProto writeCallback,
void * ioCtx,
const char * cert,
const char * privKey,
const char * privKeyPass
);
Wrap abstract read/write callbacks into secure connection.
intent - set to SECURE_INTENT_CLIENT or SECURE_INTENT_SERVER (IN).
readCallback - callback used to read from underlying unsecure IO (IN).
writeCallback - callback used to write to underlying unsecure IO (IN).
cancelCallback - callback used to cancel pending read on underlying IO (IN).
ioCtx - caller specified context passed to IO callbacks directly (IN).
cert - filename, where server certificate is stored (IN/OPT).
privKey - filename, where server private key is stored (server side
only) (IN/OPT).
privKeyPass - passphrase to decode private key. Readed from keyboard
if skipped (IN/OPT).
WARNING! Returned pointer MUSTS be freed by SecureConnectionDestroy() if not
needed longer.
TIP#1: Use SecureHandshake() to init encrypted SSL connection before
attemp to read or write via created connection.
TIP#2: Use SecureWrite to send data via secure connection.
TIP#3: Use SecureRead to read data from secure connection.
RETURNS: Pointer to new allocated SecureConnectionCreate object
or NULL if error.
SecureConnection * SecureConnectionCreate
(
int intent,
int fdin,
int fdout,
const char * cert,
const char * privKey,
const char * privKeyPass
);
Wrap FD pair into secure connection.
intent - set to SECURE_INTENT_CLIENT or SECURE_INTENT_SERVER (IN).
fdin - FD used to read data from underlying unsecure IO (IN).
fdout - FD used to write data into underlying unsecure IO (IN).
cert - filename, where server certificate is stored (IN/OPT).
privKey - filename, where server private key is stored (server side
only) (IN/OPT).
privKeyPass - passphrase to decode private key, readed from keyboard if
skipped (IN/OPT).
WARNING! Returned pointer MUSTS be released release() method when not
needed longer.
TIP#1: Use SecureHandshake() to init encrypted SSL connection before
attemp to read or write via created connection.
TIP#2: Use SecureWrite to send data via secure connection.
TIP#3: Use SecureRead to read data from secure connection.
RETURNS: Pointer to new allocated SecureConnectionCreate object
or NULL if error.
SecureConnection * SecureConnectionCreate
(
int intent,
int sock,
const char * cert,
const char * privKey,
const char * privKeyPass
);
Wrap socket into secure connection.
intent - set to SECURE_INTENT_CLIENT or SECURE_INTENT_SERVER (IN).
sock - socket connected to remote machine (IN)
cert - filename, where server certificate is stored (IN/OPT).
privKey - filename, where server private key is stored (server
side only) (IN/OPT).
privKeyPass - passphrase to decode private key, readed from keyboard if
skipped (IN/OPT).
WARNING! Returned pointer MUSTS be released release() method when not
needed longer.
TIP#1: Use SecureHandshake() to init encrypted SSL connection before
attemp to read or write via created connection.
TIP#2: Use SecureWrite to send data via secure connection.
TIP#3: Use SecureRead to read data from secure connection.
RETURNS: Pointer to new allocated SecureConnectionCreate object
or NULL if error.
SecureConnection * SecureConnectionCreate
(
int intent,
const char * cert,
const char * privKey,
const char * privKeyPass
);
Custom secure connection.
intent - set to SECURE_INTENT_CLIENT or SECURE_INTENT_SERVER (IN).
cert - filename, where server certificate is stored (IN/OPT).
privKey - filename, where server private key is stored (server
side only) (IN/OPT).
privKeyPass - passphrase to decode private key, readed from keyboard if
skipped (IN/OPT).
WARNING! Returned pointer MUSTS be released release() method when not
needed longer.
TIP#1: Use SecureHandshake() to init encrypted SSL connection before
attemp to read or write via created connection.
TIP#2: Use SecureWrite to send data via secure connection.
TIP#3: Use SecureRead to read data from secure connection.
RETURNS: Pointer to new allocated SecureConnectionCreate object
or NULL if error.
SecureAcl::SecureAcl
(
);
Create empty, NULL access list.
int SecureAcl::initFromString
(
const char * acl
);
Init access list from raw string.
String format is: "user1:rights1;user2:rights2...*:otherRights"
Example lists are:
"jan:R;jozek:F;*:D" - jan can read, jozek can read and write, others have no access
"jan:F;*:R" - jan can read and write, others can read only
"*:F" - all can read and write
"*:D" - nobody have access
"" - invalid data, * terminator missing.
R = read only
F = full access
D = access denied
* = others users not included in list explicite. SHOULD be the
last entry on the access list.
Parameters:
acl - string containing correct access list in format describet above (IN).
RETURNS: 0 if OK,
-1 otherwise.
int SecureAcl::setRights
(
const char * user,
int rights
);
Set user rights to given value.
WARNING#1: If user has already some rights granted function will OVERWRITE
them with new one.
TIP#1: To read back rights granted to user use getRights() method.
user - username, which we want grant rights to (IN).
rights - rights, which we want to grant in binary representation i.e.
combination of SECURE_ACL_XXX flags defined in Secure.h (IN).
RETURNS: 0 if OK.
int SecureAcl::setRights
(
const char * user,
const char * rights
);
Set user rights to given value.
WARNING#1: If user has already some rights granted function will OVERWRITE
them with new one.
TIP#1: To read back rights granted to user use getRights() method.
user - username, which we want grant rights to (IN).
rights - rights, which we want to grant as human readable string i.e.
combination of SECURE_ACL_SYMBOL_XXX chars defined in Secure.h.
Example string is "D" (deny) or "F" (Full access) (IN).
RETURNS: 0 if OK.
int SecureAcl::setOthersRights
(
int rights
);
Set rights granted to others users to given value. Others means all users
not mentioned in ACL explicite.
WARNING#1: If others has already some rights granted function will OVERWRITE
them with new one.
rights - rights, which we want to grant in binary representation i.e.
combination of SECURE_ACL_XXX flags defined in Secure.h (IN).
RETURNS: 0 if OK.
int SecureAcl::setOthersRights
(
const char * rights
);
Set rights granted to others users to given value. Others means all users
not mentioned in ACL explicite.
WARNING#1: If others has already some rights granted function will OVERWRITE
them with new one.
rights - rights, which we want to grant as human readable string i.e.
combination of SECURE_ACL_SYMBOL_XXX chars defined in Secure.h.
Example string is "D" (deny) or "F" (Full access) (IN).
RETURNS: 0 if OK.
int SecureAcl::revokeAll
(
const char * user
);
Remove user from accesslist. After that user has no any rights granted.
user - user, which we want revoke rights for (IN).
RETURNS: 0 if OK.
int SecureAcl::getRights
(
const char * user
);
Gather rights for given users.
user - name of user, which we want rights for (IN).
RETURNS: Rights granted to given user.
string SecureAcl::getRightsString
(
const char * user
);
Gather rights for given users.
user - name of user, which we want rights for (IN).
RETURNS: Rights granted to given user as human readable string.
string SecureAcl::toString
(
);
Convert access list stored inside object into ACL string.
void SecureAcl::clear
(
);
Revoke all grant from all users stored accesslist.
int SecureAcl::encodeRights
(
const char * str
);
Encode rights string into its binary representation.
Rights in binary representation is combination of SECURE_ACL_XXX flags
defined in Secure.h file.
WARNING#1: If input rights string is incorrect function assign SECURE_ACL_DENY
rights value.
rights - human readable string representing rights to encode, for list of
allowed chars see SECURE_ACL_SYMBOL_XXX defines in Secure.h (IN).
RETURNS: Binary representation of rights.
string SecureAcl::decodeRights
(
int rights
);
Decode rights value into string.
String contains chars representing single rights eg. "RW" means READ+WRITE.
Full list of allowed rights chars is defined at SECURE_ACL_SYMBOL_XXX defines
in Secure.h file
WARNING#1: If input rights value is incorrect function assign "D" (access denied)
rights.
rights - binary encoded rights i.e. combination of SECURE_ACL_XXX flags
defined in Secure.h (IN).
RETURNS: Human readable string representing rights.
static int Win64NotImportedError
(
);
Don't be sucker! Describe your function in source code.
int SecureRandom
(
void * buf,
int len
);
Generate random buffer.
buf - buffer, where to store generated data (OUT).
len - number of butes to generate (IN).
RETURNS: 0 if OK.
uint32_t SecureRandomInt32
(
);
Generate random 32-bit integer.
uint64_t SecureRandomInt64
(
);
Generate random 64-bit integer.
uint8_t SecureRandomByte
(
);
Generate random byte.
int SecureRandomText
(
char * buf,
int len
);
Generate random text.
Example: K1aCK1bC0=38]8GM9ggk5=K836@yee5M
buf - buffer, where to store generated text (OUT).
len - size of buf[] buffer in bytes (IN).
RETURNS: 0 if OK.
int SecureRandomHexText
(
char * buf,
int len
);
Generate random hex asciz text.
Example: 23c02a8b7c7
buf - buffer, where to store generated hex text (OUT).
len - size of buf[] buffer in bytes (IN).
RETURNS: 0 if OK.
static int Win64NotImportedError
(
);
Don't be sucker! Describe your function in source code.
void SecureEncrypt
(
SecureCipher * ctx,
void * buffer,
int size
);
Encrypt data.
ctx - secure context containing cipher state created by
SecureCipherCreate before (IN/OUT).
buffer - buffer to encrypt (IN/OUT).
size - size of buffer[] in bytes (IN).
void SecureDecrypt
(
SecureCipher * ctx,
void * buffer,
int size
);
Decrypt data.
ctx - secure context containing cipher state created by
SecureCipherCreate before (IN/OUT).
buffer - buffer to decrypt (IN/OUT).
size - size of buffer[] in bytes (IN).
SecureCipher * SecureCipherCreate
(
int cipher,
int cipherMode,
const char * key,
int keySize,
const char * iv,
int ivSize
);
Create secure context object to track state of encrypt/decrypt process.
TIP#1: Use SecureEncrypt to encrypt data using created context.
TIP#2: Use SecureDecrypt to decrypt data using created context.
cipher - cipher to use, see SECURE_CIPHER_XXX defines in Secure.h (IN).
cipherMode - the way how encrpted blocks are joined into stream,
see SECURE_CIPHER_MODE_XXX defines in Secure.h (IN).
key - symmetric key to use (IN).
keySize - size of key[] buffer in bytes (IN).
iv - init vector, can be treated as second part of key (IN).
ivSize - size of iv[] buffer in bytes (IN).
void SecureCipherDestroy
(
SecureCipher * ctx
);
Free secure context created by SecureCipherCreate() before.
int SecureDisableEcho
(
);
Disable echo on stdin.
RETURNS: 0 if OK.
int SecureEnableEcho
(
);
Enable echo on stdin.
RETURNS: 0 if OK.
int SecureReadPassword
(
char * pass,
int passSize,
const char * prompt
);
Disable echo and read password from stdin.
pass - buffer, where to store readed password (OUT).
passSize - size of pass[] buffer in bytes (IN).
prompt - optional prompt to show before ask for pass (IN/OPT).
RETURNS: 0 if OK.
int SecurePassAuthorize
(
const char * expectedHash,
const char * password,
const char * salt
);
Verify password stored as SHA256(pass + salt).
Function compute SHA256(pass + salt) by own and compare result with
expectedHash parameter.
expectedHash - expected SHA256(pass + salt) hash computed in register time (IN).
password - plain text password (IN).
salt - salt generated in register time (IN).
RETURNS: 0 if SHA256(pass + salt) matches expectedHash (authorization ok),
1 if hashes does not matches (authorization failed)
-1 if unexpected error occures.
static int Win64NotImportedError
(
);
Don't be sucker! Describe your function in source code.
int SecureHashSha256
(
char * hash,
int hashSize,
const char * data,
int dataSize,
const char * salt,
int saltSize
);
Compute sha256 hash. Function compute hash = SHA256(data + salt).
Salt is optional, set to NULL if not needed.
WARNING! Hash[] buffer MUST have at least 65 bytes length.
hash - buffer, where to store computed hash (OUT).
hashSize - size of hash[] buffer in bytes (IN).
data - data to hash (IN).
dataSize - size of data[] buffer in bytes (IN).
salt - optional salt data to add. Can be NULL (IN/OPT).
saltSize - size of salt[] buffer in bytes. Can be 0. (IN/OPT).
RETURNS: 0 if OK.
| Title: | LibSftp |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | SSHFS client library. |
| Description: | - |
| Dependences: | LibDebug LibStr LibThread LibLock LibMath LibNet |
| Used by: | Tegenaria-net LibSftp-example01-sftp-client |
1. Init
-------
To wrap existing FDs pair or socket connected to SFTP server
create new SftpClient object.
SftpClient *sftp = new SftpClient(fdin, fdout);
sftp -> connect();
... some work here ...
delete sftp;
2. Synchronous requests (low-level API)
---------------------------------------
Below methods maps to related basic SFTP requests:
SSH2_FXP_OPEN |-> sftp -> open()
SSH2_FXP_CLOSE |-> sftp -> close()
SSH2_FXP_READ |-> sftp -> read()
SSH2_FXP_WRITE |-> sftp -> write()
SSH2_FXP_OPENDIR |-> sftp -> opendir()
SSH2_FXP_READDIR |-> sftp -> readiir()
SSH2_FXP_REMOVE |-> sftp -> remove()
SSH2_FXP_MKDIR |-> sftp -> mkdir()
SSH2_FXP_RMDIR |-> sftp -> rmdir()
SSH2_FXP_STAT |-> sftp -> stat()
SSH2_FXP_RENAME |-> sftp -> rename()
3. Asynchronous requests (high-level API)
-----------------------------------------
There high-level API on top of basic SFTP requests from [2] to run SFTP job
asynchronous in background threads.
A. Download job: sftp -> downloadFile(..., callback)
B. Upload job: sftp -> uploadFile(..., callback)
C. List job: sftp -> listFiles(..., callback)
Callback function is called when:
- job changed its states (e.g. job finished or error occured)
- new transfer statistics arrived (upload/download jobs)
- new portion of file list arrived (list job)
To cancel pending job use job -> cancel() method.
WARNING: All SftpJob objects MUSTS be freed by job -> release() when no
needed longer.
- Where are ThreadJoin / ThreadWait ?
SftpClient::SftpClient
(
int fdin,
int fdout,
int timeout,
int fdType
);
Create SFTP client over given CRT FD pair.
TIP: To initiate session with server on other side
use connect() method.
fdin - FD for input data (IN).
fdout - FD for output data (IN).
timeout - I/O timeout in ms, -1 means infinite (IN).
fdType - set SFTP_CLIENT_FD if fdin/fdout are CRT FDs and
SFTP_CLIENT_SOCKET if fdin/fdout are sockets.
Defaulted to SFTP_CLIENT_FD if skipped (IN/OPT).
SftpClient::~SftpClient
(
);
Shutdown connection if any.
int SftpClient::connect
(
);
Establish connection with sftp-server.
Sends : SSH2_FXP_INIT packet.
Expects : SSH2_VERSION packet.
RETURNS: 0 if OK.
void SftpClient::disconnect
(
);
Disconnect existing connection with sftp server.
int SftpClient::reconnect
(
);
Close existing connection with server and reinit it once again
from begin.
int64_t SftpClient::open
(
const char * path,
int mode,
int isDir
);
Open remote file or directory.
Sends : SSH2_FXP_OPEN or SSH2_FXP_OPENDIR packet.
Expect : SSH2_FXP_HANDLE or SSSH2_FXP_STATUS packet.
path - path to remote file or directory (IN).
mode - sftp access mode (IN).
isDir - set to 1 for directory, 0 otherwise (IN).
RETURNS: handle assigned by sftp-server
or -1 if error.
int64_t SftpClient::opendir
(
const char * path
);
Open remote directory.
Works as open with isDir set to 1.
See SftpClient::open().
int SftpClient::close
(
int64_t handle
);
Close remote handle on server.
Sends : SSH2_FXP_CLOSE packet.
Expect : SSH2_FXP_STATUS packet.
handle - handle value retrieved from open() before (IN).
RETURNS: 0 if OK.
int SftpClient::multiclose
(
vector<int64_t> &handles
);
Close many remote handles in one request.
Sends : SSH2_FXP_DIRLIGO_MULTICLOSE packet.
Expect : SSH2_FXP_STATUS packet.
handle - list of handles value retrieved from open() before (IN).
RETURNS: 0 if OK.
int SftpClient::resetdir
(
int64_t handle
);
Reset directory handle. If readdir() finished with EOF on given handle
resetdir() request will reopen directory on server to make the same handle
possible to reuse in another readdir() request.
Sends : SSH2_FXP_DIRLIGO_RESETDIR packet.
Expect : SSH2_FXP_STATUS packet.
handle - handle value retrieved from opendir() before (IN).
RETURNS: 0 if OK.
int SftpClient::read
(
int64_t handle,
char * buffer,
uint64_t offset,
int bytesToRead
);
Read data from remote file.
Sends : many SSH2_FXP_READ.
Expect : many SSH2_FXP_DATA and one SSH2_FXP_STATUS for EOF signal.
handle - handle retrieved from open() before (IN).
buffer - buffer, where to store readed data (OUT).
offset - file position of first byte to read (IN).
bytesToRead - number of bytes to read (IN).
RETURNS: Number of bytes readed,
or -1 if error.
int SftpClient::write
(
int64_t handle,
char * buffer,
uint64_t offset,
int bytesToWrite
);
Write data to remote file.
Sends : many SSH2_FXP_WRITE packets.
Expect : many SSH2_FXP_STATUS packets.
handle - handle retrieved from open() before (IN).
buffer - buffer with data, which we want to write (IN).
offset - file position, where to start writing (IN).
bytesToWrite - number of bytes to write (IN).
RETURNS: Number of bytes written,
or -1 if error.
int SftpClient::append
(
int64_t handle,
char * buffer,
int bytesToWrite
);
Append data to remote file.
Sends : many SSH2_FXP_DIRLIGO_APPEND packets.
Expect : many SSH2_FXP_STATUS packets.
handle - handle retrieved from open() before (IN).
buffer - buffer with data, which we want to write (IN).
bytesToWrite - number of bytes to write (IN).
RETURNS: Number of bytes written,
or -1 if error.
int SftpClient::stat
(
const char * path,
BY_HANDLE_FILE_INFORMATION * info
);
Windows implementation of stat() command.
Check is file exists and optionally retrieve file attributes.
Sends : SSH2_FXP_STAT_VERSION_0 packet.
Expects : SSH2_FXP_ATTR or SSH2_FXP_STATUS.
path - full remote path on server (IN).
info - info about remote file. (OUT).
RETURNS: 0 if OK.
int SftpClient::readdir
(
vector<WIN32_FIND_DATAW> &data,
int64_t handle
);
Windows implementation of readdir().
List content of remote directory.
Sends : many SSH2_FXP_DIRLIGO_READDIR_SHORT packets.
Expects : many SSH2_FXP_NAME and one SSH2_FXP_STATUS for EOF.
data - list of files/dirs living inside selected directory (OUT).
handle - value retrieved from open() function before (IN).
RETURNS: 0 if OK.
int SftpClient::stat
(
const char * path,
SftpFileAttr * attr
);
Generic implementation of stat() command.
Check is file exists and optionally retrieve file attributes.
Sends : SSH2_FXP_STAT_VERSION_0 packet.
Expects : SSH2_FXP_ATTR or SSH2_FXP_STATUS.
path - full remote path on server (IN).
attr - info about remote file. (OUT).
RETURNS: 0 if OK.
int SftpClient::readdir
(
vector<SftpFileInfo> &files,
int64_t handle
);
Generic implementation of readdir().
List content of remote directory.
Sends : many SSH2_FXP_DIRLIGO_READDIR_SHORT packets.
Expects : many SSH2_FXP_NAME and one SSH2_FXP_STATUS for EOF.
files - list of files/dirs living inside selected directory (OUT).
handle - value retrieved from open() function before (IN).
RETURNS: 0 if OK.
int SftpClient::statvfs
(
Statvfs_t * stvfs,
const char * path
);
Retrieve info about remote disk.
WARNING: Server MUST support "statvfs@openssh.com" extension.
stvfs - buffer to store info about disk (see Sftp.h) (OUT)
path - remote path to check (IN)
RETURNS: 0 if OK.
int SftpClient::mkdir
(
const char * path
);
Create new directory on server.
Sends : SSH2_FXP_MKDIR packet.
Expects : SSH2_FXP_STATUS packet.
path - path to craete (IN).
RETURNS: 0 if OK.
int SftpClient::remove
(
const char * path
);
Remove file on server.
Sends : SSH2_FXP_REMOVE packet.
Expects : SSH2_FXP_STATUS packet.
path - path to craete (IN).
RETURNS: 0 if OK.
int SftpClient::rmdir
(
const char * path
);
Remove empty directory on server.
Sends : SSH2_FXP_RMDIR packet.
Expects : SSH2_FXP_STATUS packet.
path - path to craete (IN).
RETURNS: 0 if OK.
int SftpClient::rename
(
const char * path1,
const char * path2
);
Rename remote file or directory.
Sends : SSH2_FXP_RENAME packet.
Expects: SSH2_FXP_STATUS packet.
path1 - existing, old path to rename (IN).
path2 - new name to set (IN).
RETURNS: 0 if OK.
int64_t SftpClient::createfile
(
const char * path,
uint32_t access,
uint32_t shared,
uint32_t create,
uint32_t flags,
int * isDir
);
Open remote file using {access, shared, create, flags} masks
used with CreateFile() on Windows.
Sends : SSH2_FXP_DIRLIGO_CREATEFILE packet.
Expects : SSH2_FXP_HANDLE packet.
path - path to remote file (IN).
accesMode - the same as dwSharedAccess in CreateFile (IN).
sharedMode - the same as dwShareShared in CreateFile (IN).
create - the same as dwCreateDisposition in CreateFile (IN).
flags - the same as dwFlags in CreateFile (IN).
isDIr - on output set to 1 if opened file is a directory (OUT/OPT).
RETURNS: remote file handle,
or -winapi error if error (e.g. -ERROR_FILE_NOT_FOUND).
int64_t SftpClient::open
(
const wchar_t * path16,
int mode,
int isDir
);
Widechar wrapper for open().
See utf8 version of SftpClient::open().
int64_t SftpClient::opendir
(
const wchar_t * path16
);
Widechar wrapper for opendir().
See utf8 version of SftpClient::opendir().
int SftpClient::stat
(
const wchar_t * path16,
BY_HANDLE_FILE_INFORMATION * info
);
Widechar wrapper for stat().
See utf8 version of SftpClient::stat().
int SftpClient::mkdir
(
const wchar_t * path16
);
Widechar wrapper for mkdir().
See utf8 version of SftpClient::mkdir().
int SftpClient::remove
(
const wchar_t * path16
);
Widechar wrapper for remove().
See utf8 version of SftpClient::remove().
int SftpClient::rmdir
(
const wchar_t * path16
);
Widechar wrapper for rmdir().
See utf8 version of SftpClient::rmdir().
int SftpClient::rename
(
const wchar_t * path1_16,
const wchar_t * path2_16
);
Widechar wrapper for rename().
See utf8 version of SftpClient::rename().
int64_t SftpClient::createfile
(
const wchar_t * path16,
uint32_t access,
uint32_t shared,
uint32_t create,
uint32_t flags,
int * isDir
);
Widechar wrapper for createfile().
See utf8 version of SftpClient::createfile().
int SftpClient::statvfs
(
Statvfs_t * stvfs,
const wchar_t * path16
);
Widechar wrapper for statvfs().
See utf8 version of SftpClient::statvfs().
int SftpClient::popAttribs
(
BY_HANDLE_FILE_INFORMATION * info,
string &packet
);
Don't be sucker! Describe your function in source code.
int SftpClient::popAttribs
(
SftpFileAttr * info,
string &packet
);
Decode attributes sent by SFTP server.
info - struct, where to write decoded atributes (OUT).
packet - raw packet received from SFTP server (IN).
int SftpClient::processPacketSimple
(
string &answer,
string &packet
);
Send <packet> to server and receive <answer> packet.
TIP: You can use the same buffers for answer and packet to send.
answer - buffer, where to store received answer paceket (OUT).
packet - buffer with packet to send (IN).
RETURNS: 0 if OK.
int SftpClient::processPacket
(
string &answer,
string &packet
);
Send <packet> to server and receive <answer> packet.
TIP: You can use the same buffers for answer and packet to send.
answer - buffer, where to store received answer paceket (OUT).
packet - buffer with packet to send (IN).
RETURNS: 0 if OK.
int SftpClient::readLoop
(
void * data
);
Thread reading incoming packets.
data - pointer to related SftpClient object (this pointer) (IN)
uint32_t SftpClient::popStatusPacket
(
string &packet,
uint32_t id
);
Pop and decode SSH2_FXP_STATUS packet from buffer.
packet - buffer, where status packet is stored (IN/OUT).
id - expected packet's id. Status packet is a server's response
for one of packet sent by client. Id for send and received
packet must be the same (IN).
RETURNS: Decoded serverStatus code.
void SftpClient::setSectorSize
(
int size
);
Change used sector size.
size - sector size in bytes (IN).
int SftpClient::packetComplete
(
string &packet,
int realSize
);
Check is given SFTP packet completem.
Needed to handle partial read.
packet - SFTP packet data to check (IN).
realSize - real packet size i.e. number of useful bytes in packet[] buffer (IN).
RETURNS: 1 if given packet is a full, complete SFTP packet,
0 otherwise (partial packet).
int SftpClient::decodePacketHead
(
uint32_t * size,
uint32_t * id,
uint8_t * type,
string &packet,
int realSize
);
Decode packet {size, type, ID} head from packet buffer without
destroying it.
size - decoded packet size (OUT).
id - decoded packet ID (OUT).
type - decoded packet type (OUT).
packet - SFTP packet data to check (IN).
realSize - real packet size i.e. number of useful bytes in packet[] buffer (IN).
RETURNS: 0 if OK.
int SftpClient::DownloadFileWorker
(
void * data
);
Download file from sftp server in background thread.
Internal use only. See downloadFile() method.
data - pointer to related SftpJob object (this pointer) (IN/OUT).
SftpJob * SftpClient::downloadFile
(
const char * localPath,
const char * remotePath,
SftpJobNotifyCallbackProto notifyCallback
);
notifyCallback - function to be called when new transfer statistics arrives
or job's state changed. Optional, can be NULL (IN/OPT).
RETURNS: Pointer to new allocated SftpJob object,
or NULL if error.
int SftpClient::UploadFileWorker
(
void * data
);
Upload file to sftp server in background thread.
Internal use only. See uploadFile() method.
data - pointer to related SftpJob object (this pointer) (IN/OUT).
SftpJob * SftpClient::uploadFile
(
const char * remotePath,
const char * localPath,
SftpJobNotifyCallbackProto notifyCallback
);
Upload file to sftp server.
WARNING: Returned SftpJob object MUST be free by calling job -> release()
method.
TIP#1 : Use job -> wait() method to wait until job finished.
TIP#2 : Use job -> stop() method to stop job before finished.
remotePath - full remote path on server side, where to put file
(containing file name too) (IN).
localPath - local path, with file to upload (IN).
notifyCallback - function to be called when new transfer statistics arrives
or job's state changed. Optional, can be NULL (IN/OPT).
RETURNS: 0 if OK.
int SftpClient::ListFilesWorker
(
void * data
);
List content of remote directory in background thread.
Internal use only. See listFiles() method.
data - pointer to related SftpJob object (this pointer) (IN/OUT).
SftpJob * SftpClient::listFiles
(
const char * remotePath,
SftpJobNotifyCallbackProto notifyCallback
);
Asynchronous list content of remote directory.
WARNING: Returned SftpJob object MUST be free by calling job -> release()
method.
TIP#1 : Use job -> wait() method to wait until job finished.
TIP#2 : Use job -> stop() method to stop job before finished.
TIP#3 : Use job -> getFiles() method inside notifyCallback to receive next
part of files, wchich was listed.
Parameters:
remotePath - full remote directory to list e.g. "/home" (IN).
notifyCallback - function to be called when new part of file list arrived
from network (IN).
RETURNS: 0 if OK.
void SftpClient::setNetStatTick
(
int tick
);
Change interval telling how often network statistics are computed.
tick - statistics tick in number of processed packets (IN).
void SftpClient::registerNetStatCallback
(
SftpNetStatCallbackProto callback,
void * ctx
);
Register callback function called when number of packets touch
net statistics tick set by setNetStatTick() function.
callback - function to be called when new statistics arrived (IN).
ctx - caller context passed to callback function directly (IN/OPT).
void SftpClient::setPartialThreshold
(
int readThreshold,
int writeThreshold
);
Set timeout in seconds after, which read/write operation is stopped
and only partial result is returned (e.g. readed 1024 bytes, when
caller wanted 2048).
readThreshold - read threshold in seconds (IN).
writeThreshold - write threshold in seconds (IN).
void SftpClient::registerConnectionDroppedCallback
(
SftpConnectionDroppedProto callback,
void * ctx
);
Set callback function called when underlying connection dead.
void SftpClient::shutdown
(
);
Don't be sucker! Describe your function in source code.
SftpJob::SftpJob
(
int type,
SftpClient * sftp,
const char * localName,
const char * remoteName,
SftpJobNotifyCallbackProto notifyCallback
);
SftpJob constructor.
type - job's type, see SFTP_JOB_TYPE_XXX defines in SftpJob.h (IN).
sftp - related SFTP Client object (IN).
localName - related local path, e.g. source local file in upload job (IN).
remoteName - related remote path e.g. destination remote path in upload job (IN).
notifyCallback - function to be called when new transfer statistics arrives
or job's state changed. Optional, can be NULL (IN/OPT).
SftpJob::~SftpJob
(
);
SftpJob destructor.
double SftpJob::getTimeMs
(
);
Get current time in ms.
void SftpJob::addRef
(
);
Increase refference counter.
WARNING! Every call to addRef() MUSTS be followed by one release() call.
TIP #1: Object will not be destroyed until refference counter is greater
than 0.
TIP #2: Don't call destructor directly, use release() instead. If
refference counter achieve 0, object will be destroyed
automatically.
void SftpJob::release
(
);
Decrease refference counter increased by addRef() before.
void SftpJob::setState
(
int state
);
Change current state. See SFTP_STATE_XXX defines in SftpJob.h.
state - new state to set (IN).
void SftpJob::setThread
(
ThreadHandle_t * thread
);
Set thread handle related with job.
thread - thread handle to set (IN).
int SftpJob::getState
(
);
Get current state code. See SFTP_JOB_STATE_XXX defines in SftpJob.h.
RETURNS: Current state code.
const char * SftpJob::getStateString
(
);
Get current state as human readable string.
RETURNS: Name of current job's state.
int SftpJob::wait
(
int timeout
);
Wait until job finished or stopped with error.
timeout - maximum time to wait in ms. Set to -1 for infinite (IN).
RETURNS: 0 if OK (job finished/stopped on exit),
-1 otherwise (job still active on exit).
void SftpJob::cancel
(
);
Send stop signal for pending SFTP job.
After that related thread should stop working and state
should change to SFTP_JOB_STATE_STOPPED.
WARNING#1: SFTP job object MUSTS be still released with release() method.
TIP#1: To stop and release resources related with SFTP job use below code:
job -> cancel();
job -> release();
SftpClient * SftpJob::getSftpClient
(
);
Retrieve SftpClient object related with job.
const char * SftpJob::getRemoteName
(
);
Retrieve remote name related with job.
const char * SftpJob::getLocalName
(
);
Retrieve local name related with job.
void SftpJob::updateStatistics
(
double processedBytes,
double totalBytes
);
Update transfer statistics for job.
Internal use only.
processedBytes - number of bytes already processed (IN).
totalBytes - number of total bytes to process (IN).
int SftpJob::getType
(
);
Retrieve job type. See SFTP_JOB_TYPE_XXX defines in SftpJob.h.
double SftpJob::getAvgRate
(
);
Get averange job's rate in bytes per seconds.
int64_t SftpJob::getTotalBytes
(
);
Get total bytes needed to be processed to finish job e.g. total size
of file to download in bytes.
int64_t SftpJob::getProcessedBytes
(
);
Get number of bytes already processed by job.
double SftpJob::getPercentCompleted
(
);
Get completion status in percentes (0-100%).
void SftpJob::clearFiles
(
);
Clear list of files stored inside job object.
Used internally only.
void SftpJob::addFile
(
SftpFileInfo &file
);
Add file to files list stored inside job object.
Used internally only.
vector<SftpFileInfo> & SftpJob::getFiles
(
);
Retrieve list of files stored inside job object.
TIP#1: Use this function to retrieve next part of files while performing
SFTP_JOB_TYPE_LIST job. This function should be called inside
notify callback passed to SftpClient::listFiles() function.
RETURNS: Refference to files list currently stored inside job object.
void SftpJob::triggerNotifyCallback
(
int code
);
Tell sftp job object to call underlying notify callback set in constructor.
Used internally only.
code - one of SFTP_JOB_NOTIFY_XXX code passed to callback notify (IN).
int GenerateUniqueId
(
);
Generate thread-safe, unique number.
Used internally to generate handles and session IDs.
RETURNS: Number unique inside process.
int GetSftpFlagFromWinapi
(
DWORD access,
DWORD shared,
DWORD create,
DWORD flags
);
Translate {access, create, flags} masks passed to CreateFile()
into SFTP access mask.
access - dwDesiredAccess mask passed used with CreateFile (IN).
share - dwShareMode mask passed used with CreateFile (IN).
create - dwCreationDisposition parameter used with CreateFile (IN).
flags - dwFlagsAndAttributes parameter used with CreateFile (IN).
RETURNS: SFTP access mask.
const char * TranslateSftpStatus
(
int code
);
Translate SSH2_FX_XXX code into human readable string.
code - one of SSH2_FX_XXX code defined in Sftp.h (IN).
RETURNS: Error string related to given code,
or "Unknown" if code not recognized.
double GetTimeMs
(
);
Get current time in ms.
| Title: | LibArgs |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Parse command line arguments. |
| Description: | - |
| Dependences: | LibDebug LibStr |
| Used by: | Tegenaria-core qcbuild LibArgs-example LibArgs-example-shell |
int ArgsParse
(
ArgsObj * ao,
int argc,
char ** argv
);
Process arguments.
int ArgsParse
(
ArgsObj * ao,
const char * cmd
);
Wrapper for ArgsParse() working with one continous
string on input.
RETURNS: 0 if OK.
int ArgsAlloc
(
int * argc,
char *** argv,
const char * cmd
);
Allocate argv[] table from continous string.
WARNING: Output argv[] MUST be free by caller via ArgsFree().
argc - number of elements in argv[] (OUT).
argv - table with tokenized arguments (OUT).
argStr - command line string to tokenize (IN).
RETURNS: 0 if OK.
void ArgsFree
(
int argc,
char ** argv
);
Free argv[] table allocated by ArgsAlloc().
| Title: | LibDebug |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Write logs to file/stderr and ships common macros to catch errors. |
| Description: | - |
| Dependences: | |
| Used by: | Tegenaria-core qcbuild LibCGI LibNet LibNetEx LibSecure LibSftp LibSecure-example01-callbacks LibSecure-example02-socket LibSecure-example03-random LibSecure-example04-hp-server LibSecure-example05-encrypt LibSecure-example06-hash LibSecure-example07-read-pass LibSecure-example08-acl LibNet-example01-thread-server LibNet-example02-single LibNet-example05-HP-server libnet-example07-echo-server libnet-example08-echo-client libnet-example09-smtp-client ZLib-example libevent-example-server LibArgs LibFile LibIO LibIpc LibJob LibLock LibMath LibObject LibProcess LibReg LibService LibSSMap LibStr LibSystem LibThread LibVariant LibStr-example01-binary-packet LibStr-example02-verify LibStr-example03-date LibReg-example01-simple LibReg-example02-list-subkeys LibLock-example01-mutex LibLock-example02-semaphore liblock-example03-requestpool LibIO-example01-file-mixer LibIO-example02-network-mixer LibIO-example03-timeout-read LibDebug-example-simple LibDebug-example02-monitor LibDebug-example-level LibDebug-example-io LibArgs-example LibArgs-example-shell |
I. Init
=======
Call DBG_INIT or DBG_INIT_EX at startup.
If not called:
- Log fd defaulted to stderr
- Log level defaulted to DBG_LEVEL_DEFAULT (see Debug.h)
TIP#1: You can adjust extra features by setting flags parameter
to DBG_INIT_EX. See Debug.h for possible values.
Examples:
DBG_INIT("dirligo.log")
DBG_INIT_EX(NULL, "debug3", -1)
DBG_INIT_EX("dirligo.log", DBG_LEVEL_INFO, DBG_STATE_ENABLE)
II. System error codes
======================
GetLastError() can be used:
- Returns native GetLastError() on Windows.
- Returns errno value on Linux.
No #ifdef needed.
III. Tracing code
=================
Use DBG_ENTER or DBG_ENTER_EX to mark begin of function calls.
Use DBG_LEAVE to mark end of function calls.
TIP#1: DBG_ENTER2, DBG_ENTER3 etc. are enabled under DEBUG2, DEBUG3 levels
only. Use them to avoid flooding log with a lot of enter/leaves
messages if one of function is called very often.
IV. Log levels
==============
Defined in Debug.h.
To set log level at init use DBG_INIT_EX at startup.
To set log level after init use DBG_SET_LEVEL or DBG_INIT_EX with
DBG_REINIT flag.
Level name | Enabled macros
=================+===================================================
DBG_LEVEL_NONE | Fatal quits without message
-----------------+---------------------------------------------------
DBG_LEVEL_ERROR | Error, Fatal
-----------------+---------------------------------------------------
DBG_LEVEL_INFO | DBG_INFO, DBG_HEAD
-----------------+---------------------------------------------------
DBG_LEVEL_DEBUG1 | DEBUG1, DBG_MSG, DBG_MSG1, DBG_HEAD1, DBG_ENTER,
| DBG_ENTER1, DBG_LEAVE, DBG_LEAVE1
-----------------+---------------------------------------------------
DBG_LEVEL_DEBUG2 | DEBUG2, DBG_MSG2, DBG_HEAD2, DBG_ENTER2, DBG_LEAVE2
-----------------+---------------------------------------------------
DBG_LEVEL_DEBUG3 | DEBUG3, DBG_MSG3, DBG_HEAD3 DBG_ENTER3, DBG_LEAVE3
-----------------+---------------------------------------------------
DBG_LEVEL_DEBUG4 | DEBUG4, DBG_MSG4, DBG_HEAD4 DBG_ENTER4, DBG_LEAVE4
-----------------+---------------------------------------------------
DBG_LEVEL_DEBUG5 | DEBUG5, DBG_MSG5, DBG_HEAD5 DBG_ENTER5, DBG_LEAVE5
| DBG_DUMP
V. Monitoring process resources
===============================
1. To enable state monitor init log using DBG_INIT_EX with
DBG_STATE_ENABLE flag.
2. To add/delete resources to monitor use DBG_SET_XXX marcos.
DBG_SET_ADD - add object to monitor
DBG_SET_DEL - remove object from monitor
DBG_SET_MOVE - move object from one set to another (e.g. move
mutex from locking to locked).
Example: See example02-monitor.
TIP#1: You can assign arbitar names to object ID to debug code easier.
To do it see at:
DBG_SET_ADD_EX - Add named object to monitor
DBG_SET_RENAME - Rename anonymous object or change existing one
VI. Monitoring I/O activity
===========================
1. To enable I/O logs use DBG_IO_ENABLE flag in DBG_INIT_EX.
2. I/O log is written to *.io.<pid>.log file.
3. To monitor I/O use DBG_IO_XXX macros:
DBG_IO_WRITE_BEGIN(TYPE, ID, BUF, COUNT)
DBG_IO_WRITE_END(TYPE, ID, BUF, COUNT)
DBG_IO_READ_BEGIN(TYPE, ID, BUF, COUNT)
DBG_IO_READ_END(TYPE, ID, BUF, COUNT)
DBG_IO_CLOSE_BEGIN(TYPE, ID)
DBG_IO_CLOSE_END(TYPE, ID)
where TYPE is arbirtar string e.g. "socket".
4. Examples:
//
// Write some data to FD.
//
DBG_IO_WRITE_BEGIN("fd", fd, buf, count);
written = write(fd, buf, count);
DBG_IO_WRITE_END("fd", fd, buf, written);
//
// Read some data from socket.
//
DBG_IO_READ_BEGIN("socket", sock, buf, count);
readed = recv(sock, buf, count, 0);
DBG_IO_READ_END("fd", fd, buf, readed);
//
// Close stdio file.
//
DBG_IO_CLOSE_BEGIN("FILE*", f);
fclose(f);
DBG_IO_CLOSE_END("FILE*", f);
See example04-io for full working code.
VII. Catching errors
====================
You can use *FAIL* family macros:
FAIL(X) - if X true jump to fail
FAILEX(X, ...) - if X true write formatted messages at DBG_LEVEL_ERROR
and jump to fail
TIP#1: FAIL and FAILEX does NOT affect OS error code.
You can catch it just after fail label.
Example:
{
int exitCode = -1;
...
FAIL(write(fd, buf, count) < 0);
FAILEX(ptr == NULL, "ERROR: Ptr cannot be NULL.");
...
//
// Error handler.
//
exitCode = 0;
fail:
if (exitCode)
{
//
// We fall here if function fail in middle.
//
Error("Fail with code : %d.\n", GetLastError());
}
...
}
void DbgInit
(
const char * fname,
int logLevel,
int flags
);
Initialize:
- main log file
- state.<pid> file.
- state-history.<pid> file.
- save pid of current process.
fname - file path, where to store main log file.
Defaulted to stderr if NULL or file cannot be created (IN/OPT).
level - one of DBG_LEVEL_XXX (see Debug.h) level to set.
Defaulted to DBG_LEVEL_DEFAULT if -1. (IN/OPT).
flags - combination of DBG_XXX flags degined in Debug.h.
Defaulted to DBG_FLAGS_DEFAULT if -1. (IN/OPT).
void DbgInit
(
const char * fname,
const char * levelName,
int flags
);
Wrapper for DbgInit() working with human readable string
as log level name.
See DbgInit() and TranslateLogName() for more.
void DbgGetPrefix
(
char * prefix,
int prefixSize,
int level
);
Generate '[pid][threadID] time' prefix.
prefix - buffer, where to store created prefix (OUT).
prefixSize - size of buffer[] in bytes (IN).
level - log level to generate prefix if DBG_LOGLEVEL_PREFIX
flag set (IN).
void DbgMsg
(
int level,
const char * fmt
);
Put formatted message into main log.
TIP#1: Default log file is stderr. To redirect it to file,
use DBG_INIT(logfile).
TIP#2: To change log level in current process use
DBG_INIT_EX(logfile, level, flags) instead of DBG_INIT.
level - requested log level, if less than log level for current
process nothing happen. See DBG_LEVEL_XXX in Debug.h (IN).
fmt, ... - printf like arguments to format message (IN).
void DbgIoMsg
(
int level,
const char * fmt
);
Put formatted message into I/O log.
TIP#1: Disabled as default, use DBG_IO_ENABLE flag in DBG_INIT_EX.
TIP#2: IO log is written to io.<pid> file.
TIP#3: Use DBG_IO_XXX() macros.
level - requested log level, if less than log level for current
process nothing happen. See DBG_LEVEL_XXX in Debug.h (IN).
fmt, ... - printf like arguments to format message (IN).
void DbgHead
(
int level,
const char * fmt
);
Put formatted header into log file in form:
------------------------------------------------
- some printf like formatted message here -
------------------------------------------------
level - requested log level, if current level is less nothing happen (IN).
fmt - printf like args to fomat message (IN).
void DbgDump
(
void * buf,
int size
);
Dump raw buffer to log as hex values.
buf - buffer to dump (IN).
size - size of buffer in bytes (IN).
void DbgEnterEx
(
int level,
const char * fname,
const char * fmt
);
int DbgSetLevel
(
int level
);
Change log level for current running process.
level - one of DBG_LEVEL_XXX values from Debug.h. (IN).
RETURNS: 0 if OK.
int DbgTranslateLevelName
(
const char * levelName
);
Translate human readable log level value.
levelName - Name of log level to set. Supported values are:
none, error, info, debug1, debug2 or debug3 or
number. Names are case insensitve - INFO and info are
the same (IN).
Examples:
DbgTranslateLevelName("info") gives 2
DbgTranslateLevelName("2") gives 2
DbgTranslateLevelName("bla") gives -1
RETURNS: One of DBG_LEVEL_XXX values from Debug.h,
or -1 if unknown level name.
int DbgSetLevel
(
const char * levelName
);
Wrapper for DbgSetLevel(int) working with human readable names.
It can be used with name readed from text config file directly.
levelName - Name of log level to set. Supported values are:
none, error, info, debug1, debug2 or debug3.
Names are case insensitve - INFO and info are the same (IN).
RETURNS: 0 if OK.
void DbgIoDumpOperation
(
int level,
int operationCode,
const char * fdType,
uint64_t fdId64,
const void * buf,
int count,
const char * sourceFile,
int sourceLine
);
Dump read/write operation into IO log.
level - requested log level, if less than log level for current
process nothing happen. See DBG_LEVEL_XXX in Debug.h (IN).
operation - one of DBG_IO_OPERATION_XXX code defined in Debug.h (IN)
fdType - type of underlying IO object eg. "FD", "Socket" (IN).
fdId64 - 64-bit ID of related IO object eg. socket number or pointer
to NetConnection object (IN).
buf - buffer related with operation (IN).
count - size of operation in bytes (IN).
sourceFile - source file name, where operation is called (IN).
sourceLine - number of code line in source file (IN).
inline int GetCurrentThreadId
(
);
Don't be sucker! Describe your function in source code.
void DbgSetDump
(
);
Dump state of all monitored objects to state.<pid> file.
void DbgSetAdd
(
const char * setName,
uint64_t id,
const char * fmtName
);
Add object with given ID to objects set.
setName - name of target set, eg. 'socket' (IN).
id - object id (IN).
fmtName - optional, human readable name e.g. NETAPI#2/Mutex,
or printf like list to format name in runtime (IN/OPT).
Examples:
DbgSetAdd("socket", 1234);
DbgSetAdd("mutex", 0x1000, "LogFile");
DbgSetAdd("session", this, "NETAPI #%d/%d, id, ownerId);
void DbgSetAdd
(
const char * setName,
void * ptr,
const char * fmt
);
Don't be sucker! Describe your function in source code.
void DbgSetDel
(
const char * setName,
uint64_t id
);
Remove object with given ID from objects set.
setName - name of target set, eg. 'socket' (IN).
id - object id (IN).
Examples:
DbgSetDel("socket", 1234);
DbgSetDel("session", this);
void DbgSetMove
(
const char * dstSet,
const char * srcSet,
uint64_t id
);
Move object with given ID from source set to destination set.
dstSet - name of destination set (IN).
srcSet - name of source set (IN).
id - object id (IN).
void DbgSetRename
(
const char * setName,
uint64_t id,
const char * fmtName
);
Assign human readable string to object.
setName - name of object set used in DbgSetAdd() before (IN).
id - object id (IN).
fmtName - new object's name to assign e.g. 'Session ID#5' or
printf like list to format new name. See DbgSetAdd()
for examples (IN).
void DbgSetRename
(
const char * setName,
void * ptr,
const char * fmt
);
Don't be sucker! Describe your function in source code.
| Title: | LibError |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki (sw143@wp.pl) |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Unify error codes, translate error codes to human readable strings. |
| Description: | - |
| Dependences: | |
| Used by: | Tegenaria-core LibLock LibStr LibError-example01-system-codes |
const char * ErrGetString
(
int code
);
Translate ERR_XXX codes into human readable
string.
code - one of ERR_XXX codes defined in LibServer.h (IN).
RETURNS: Human readable message or empty string if
unknown code.
int ErrGetSystemError
(
);
Get last saved system error code.
It calls internally:
- GetLastError() on Windows
- errno() on Linux
RETURNS: System error code saved from last system function.
const string ErrGetSystemErrorString
(
);
Get last saved system error as human readable string.
It calls internally:
- GetLastError() on Windows
- errno on Linux
RETURNS: System error code saved from last system function converted
to human readable string (eg. "access denied").
| Title: | LibFile |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Process files and pathes. Ships transacted I/O. |
| Description: | - |
| Dependences: | LibDebug |
| Used by: | Tegenaria-core qcbuild LibCGI |
= Change tfwrite() like macros into pure functions to hide implementation.
char * FileLoad
(
const char * fname,
int * readed
);
Load file to new allocate buffer.
fname - name of file to load (IN).
readed - number of bytes allocated and readed (OUT/OPT).
RETURNS: New allocated buffer or NULL if fail.
int ListFiles
(
string path,
string mask,
vector<string>& files,
bool recursive,
unsigned int flags
);
Make file list in given directory.
path - directory where to search (IN)
mask - file mask (e.g. '*.dat') (IN)
files - output file list (OUT)
recursive - search also in subdirs, if set to true (IN)
flags - combination of FILE_XXX flags defined in File.h (IN/OPT).
RETURNS: 0 if OK
int ListDirs
(
string path,
string mask,
vector<string>& dirs,
bool recursive,
unsigned int flags
);
Make directories list in given directory.
path - directory where to search (IN)
mask - file mask (IN)
files - output file list (OUT)
recursive - list subdirs if true (IN)
flags - combination of FILE_XXX flags defined in File.h (IN/OPT).
RETURNS: 0 if OK
int FileCompare
(
int &stat,
const string &fname1,
const string &fname2
);
Compare two files.
stat - result of comparison (1 if equal, 0 if not) (OUT).
fname1 - first file to compare (IN).
fname2 - second file to compare (IN).
RETURNS: 0 if OK.
int FileExists
(
const string &path
);
Check does file or directory exists on disk.
path - path to check (IN).
RETURNS: 1 if file exists.
int FileWait
(
const char * fname,
int timeout
);
Wait until given file exists on disk.
fname - file name to wait (IN).
timeout - maximum allowed wait time in ms. Defaulted to
infinite if skipped (IN/OPT).
RETURNS: 0 if file found within timeout,
-1 if timeout reached.
int FileDelete
(
const char * fname
);
Remove file from disk.
fname - path to file which we want to delete (IN).
RETURNS: 0 if OK.
int FileCreateRecursiveDir
(
const string &target
);
Create directory recursively at one call.
target - path to create (e.g. 'A/B/C/D') (IN).
RETURNS: 0 if OK.
int FileCreateDir
(
const string &path,
int quiet
);
Create single directory.
TIP#1: Use FileCreateRecursiveDir() to create whole path recursively.
path - target path to create (IN).
quiet - do not write error message if set to 1 (IN).
RETURNS: 0 if OK.
int FileSave
(
const char * fname,
const char * buf,
int size
);
Save buffer to file. If file already exists will be overwritten.
fname - path to output file (IN).
buf - buffer to dump (IN).
size - size of buf[] buffer in bytes (IN).
RETURNS: 0 if OK.
int FileGetDir
(
char * path,
int pathSize
);
Get current working directory.
path - buffer where to store retrieved directory (OUT).
pathSize - size of path[] buffer in bytes (IN).
RETURNS: 0 if OK.
int FileSetDir
(
const char * path
);
Change current working directory.
path - new working directory to set (e.g. 'c:/tmp') (IN).
RETURN: 0 if OK.
string FileGetRootName
(
const string &path
);
Get root filename from path, eg. it retrieve
'file' from 'c:/tmp/file.dat'.
path - path to split (IN).
RETURNS: Root filename part or empty string if error.
string FileCreateTempName
(
const char * baseDir,
const char * prefix
);
Genearete temporary filename (WITHOUT creating the file).
Ouput path has format : '<BaseDir>/<prefix>XXX.YYY',
where XXX.YYY are generated unique name and extension.
baseDir - directory, where to store file. System temp will be
used if skipped (IN/OPT).
prefix - prefix to add before filename (IN/OPT).
RETURNS: Abosolute path to temporary file or
empty string if error.
int CanonizePath
(
string &path
);
Don't be sucker! Describe your function in source code.
int FileSize
(
const char * fname
);
Retrieve size of given file.
fname - path to check (e.g. 'c:/tmp/test.dat') (IN).
RETURNS: Size of file in bytes or -1 if error.
void FileNormalizeSlash
(
char * path,
char slash
);
Normalize slashes in path to '/' or '\\'.
path - path to normalize (IN/OUT).
slash - new slash character to use ('/' or '\\') (IN).
void FileNormalizeSlash
(
wchar_t * path,
wchar_t slash
);
Normalize slashes in widechar path to L'/' or L'\\'.
path - path to normalize (IN/OUT).
slash - new slash character to use (L'/' or L'\\') (IN).
const char FileGetFirstFreeLetter
(
);
Retrieve first free drive letter.
RETURNS: First available letter (e.g. 'J'),
or 0 if error.
int FileWriteString
(
FILE * f,
const string &str
);
Dump C++ string to binary file.
It writes to file xx xx xx xx ss ss ss ss ss ....
where:
xx - little endian dword (4 bytes) length of string without 0
ss - variable string data
f - C stream, where to write data (IN).
str - C++ string to dump (IN).
RETURNS: 0 if OK.
int FileReadString
(
FILE * f,
string &str
);
Load C++ string from binary file, stored by FileWriteString() before.
f - C stream, where to read data from (IN).
str - C++ string where to load data (IN).
RETURNS: 0 if OK.
const string FileGetTempDir
(
);
Return system TEMP directory.
int FileReadInt16
(
FILE * f,
int16_t * rv
);
int FileReadInt32
(
FILE * f,
int32_t * rv
);
Don't be sucker! Describe your function in source code.
int FileReadInt64
(
FILE * f,
int64_t * rv
);
Don't be sucker! Describe your function in source code.
int FileReadFloat
(
FILE * f,
float * rv
);
Don't be sucker! Describe your function in source code.
int FileSkipBytes
(
FILE * f,
int numberOfBytesToSkip
);
Don't be sucker! Describe your function in source code.
int FileReadDouble
(
FILE * f,
double * rv
);
Don't be sucker! Describe your function in source code.
char * FileGetLine
(
char * buf,
int bufSize,
FILE * f,
int * readed,
int trim
);
Read line from C stream WITHOUT end of line character.
buf - destination buffer, where to put readed data (OUT).
bufSize - buf[] size in bytes (IN).
f - C stream retrievead from fopen before (IN).
readed - number of bytes readed (without end of line) (OUT/OPT).
trim - remove white space from left and right side if set to 1 (IN/OPT).
RETURNS: pointer to first byte of line
or NULL if error.
string FilePathGetTopDir
(
const string &path
);
Get root directory from path.
Example input : "Lib/LibFile"
Example output : "Lib"
string FilePathGetDirAtDeep
(
const string &path,
int deep
);
Get directory name at given deep level inside path.
Example path : "Source/Lib/LibFile"
Example deep : 1
Example returns : Lib
int FileGetLastModificationTimestamp
(
const char * path
);
Returns UNIX timestamp of last file modification or -1 if error.
TFILE * tfopen
(
const char * fname,
const char * mode
);
Open file in transacted mode.
fname - file path to open (IN).
mode - C style open mode (see fopen) (IN).
RETURNS: File handle or NULL if error.
void tfclose
(
TFILE * f
);
Close transacted file.
f - handle retrieved from tfopen function (IN).
int FileRecoverFailedIO
(
const char * directory
);
Recover corrupted I/O operations in given directory.
directory - path, where scan for corrupted operations (IN).
RETURNS: 0 if OK.
| Title: | LibIO |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Ships common patterns to perform I/O tasks. |
| Description: | - |
| Dependences: | LibDebug LibLock LibThread ZLib |
| Used by: | Tegenaria-core LibIO-example01-file-mixer LibIO-example02-network-mixer LibIO-example03-timeout-read |
-------------------------------------------------------------------------------
- -
- IOFifo class -
- -
-------------------------------------------------------------------------------
I. Cyclic buffer to storing I/O data.
Incoming data is appended to the end of buffer.
Outcoming data is popped from the begin of buffer.
(First in first out order).
xx xx xx xx xx xx xx ... yy yy yy yy yy
^^^ ^^^
Read position. Write position.
Pop data from here. Push data here.
(Begin of buffer) (End of buffer).
II. Read/write
==============
To add data to FIFO use push().
To pop data from FIFO use pop().
To eat data (pop, but don't write anywhere) use eat().
III. Multithread
================
IOFifo is NOT thread safe itself.
Use lock() and unlock() to synchronize access from many threads.
-------------------------------------------------------------------------------
- -
- IOMixer class -
- -
-------------------------------------------------------------------------------
IOMixer to multiplex one master connection into many slave channels.
I. Master thread:
=================
One IOMixer = one master thread = one IOMixer::masterLoop().
/ [slave1/IN] - ...
[Master] - [slave2/IN] - ...
\ [slave3/IN] - ...
Master loop does:
-----------------
1. Read <id><len><data> packet from master.
2. Send <len> bytes of <data> to slave with ID <id>.
<data1> -> slave1/IN
/
master/OUT -> <1><len1><data1><2><len2><data2> ... -> <data2> -> slave2/IN
\
...
Master loop is created in IOMixer::start().
Master loop is deleted in IOMixer::stop().
II. Slave threads:
==================
One IOMixer = many slaves threads = many IOMixer::slaveLoop().
... -> [slave1/OUT] \
... -> [slave2/OUT] -> [Master/IN] ->
... -> [slave3/OUT] /
Slave loop does:
----------------
1. Read <data> from slave with given <id>.
2. Write <id><len><data> to master.
Slave1/OUT -> <data1>
\
Slave2/OUT -> <data2> -> <1><len1><data1> <2><len2><data2> ... -> master/IN
/
...
Slave thread is created in IOMixer::addSlave(...)
Slave thread is deleted in IOMixer::removeSlave(..)
III. Slave IDs:
===============
Slave 0 : Reserved for internal IOMixer usage.
Slave 1, 2, ... : Created by caller in IOMixer::addSlave().
IV. EOF packets:
================
Used internally by IOMixer only.
Zero length data means EOF, i.e. packet <id><0>.
If slave loop received EOF it means slave with given <id> is dead
and should be shutted down.
EOF on slave ID#0 is reserved for master EOF.
It signal to shutdown whole connection.
VI. Shutdown protocol:
======================
1. Send EOF for every slaves, i.e. <id><0>.
2. Send master EOF, i.e. <0><0>.
3. Wait for master EOF from remote or connection broken.
Implemented in IOMixer::shutdown().
Called internally from destructor.
- Review performance when TCP_NO_DELAY enabled.
int IOMixer::addSlave
(
int callerFds[2],
int slaveId
);
Create new slave fd pair.
All <data> written to 'slaveOut' will be wrapped to <slaveId> <len> <data>
inside slave thread. One slave = one 'slave thread'.
-> <data1> -> [Slave1] \
-> <1><len1><data1> <2><len2><data2> -> [master] ->
-> <data3> -> [Slave3] /
All <slaveId> <len> <data> readed from 'masterIn' will be dispatched
into 'slaveIn' with given ID inside 'master thread'.
One master thread is common to all slaves.
<data1> ->
/
<1><len1><data1><2><len2><data2> -> [Master]
\
<data2> ->
callerFds[] - input/output CRT fds valid in caller context (OUT).
slaveId - ID for new slave. Optional, if skipped new unique ID
will be generated (IN/OPT).
RETURNS: ID assigned to slave or -1 if error.
IOMixer::IOMixer
(
int masterOut,
int masterIn,
int masterOutType,
int masterInType
);
Constructor using socket/FDs pair.
IOMixer::IOMixer
(
IOReadProto readCallback,
IOWriteProto writeCallback,
void * readCtx,
void * writeCtx,
IOCancelProto ioCancelCallback
);
Constructor using two caller specified read/write functions.
readCallback - function used to read data from master (IN).
writeCallback - function used to write data to master (IN).
readCtx - caller defined data passed to readCallback() (IN/OPT).
writeCtx - caller defined data passed to writeCallback() (IN/OPT).
ioCancelCallback - function used to cancel pending IO on master (IN/OPT)
IOMixerSlave * IOMixer::getSlave
(
int id
);
Retrieve pointer to slave object with given ID,
added by addSlave() before.
RETURNS: Pointer to slave object or NULL if wrong ID.
int IOMixer::removeSlave
(
int id
);
Remove slave with given ID.
id - ID of slave to remove, retrieved from addSlave() before (IN).
RETURNS: 0 if OK.
int IOMixer::start
(
);
Start up master thread, which reading from <master>
and dispatching readed data to slaves.
WARNING: If master thread will be started BEFORE registering
needed slaves via addSlave(), all incoming data
will be ignored with "ERROR: Unknown slave ID.".
RETURNS: 0 if OK.
int IOMixer::stop
(
);
Stop master thread started before by start() method.
RETURNS: 0 if OK.
int IOMixer::slaveLoop
(
IOMixerSlave * slave
);
Thread routine to mix many <slave-outputs> into one <master-input>.
Used internally only.
One slave = one slave loop = one slave thread.
-> slave1 \
-> slave2 -> master
-> slave3 /
slave - pointer to related I/O slave (IN/OUT).
RETURNS: 0 if OK.
int IOMixer::masterLoop
(
IOMixer * this_
);
Thread routine to split one <master-input> into many <slave-outputs>.
Used internally only.
/ slave1
-> master - slave2
\ slave3
this_ - pointer to related IOMixer object (IN/OUT).
RETURNS: 0 if OK.
int IOMixer::join
(
);
Wait until 'master thread' and every 'slave threads' finished works.
RETURNS: 0 if OK.
IOMixer::~IOMixer
(
);
Desctructor.
Kill master thread and all slaves.
int IOMixer::masterEncode
(
int id,
void * buf,
int size,
uint8_t flags
);
Encode <data> into <id><flags><size><data> and write it into master OUT.
TIP: If <size> is <= 0, then <data> part will be skipped.
It's equal to sending EOF/error to other side, where remote
read() will return -1/0.
id - channel id where to send data (IN).
buf - buffer to send (IN).
size - size of buf[] buffer in bytes (IN).
flags - combination of IOMIXER_FLAG_XXX flags (IN).
RETURNS: 0 if OK.
int IOMixer::masterDecode
(
int * id,
int * size,
void * data,
int dataSize
);
Pop <id><flags><size><data> packet from master IN.
id - buffer where to store decoded <id> (OUT).
size - buffer where to store decoded <size> (OUT).
data - buffer where to store decoded <data> (OUT).
dataSize - size of data[] buffer in bytes (IN).
RETURNS: Number of decoded <data> bytes of -1 if error.
int IOMixer::masterWrite
(
void * buf,
int bytesToWrite
);
Atomic write <size> bytes from <buf> to master OUT.
Wrapper to system write() to hide difference beetwen socket
and CRT FD on windows.
buf - buffer with data to write (IN).
bytesToWrite - number of bytes to be written (IN).
RETURNS: 0 if all data written
-1 if otherwise.
int IOMixer::masterRead
(
void * buf,
int bytesToRead
);
Atomic read <size> bytes from master IN to <buf>.
Wrapper to system read() to hide difference beetwen socket
and CRT FD on windows.
buf - buffer with data to write (IN).
bytesToRead - number of bytes to be readed (IN).
RETURNS: 0 if all data readed
-1 if otherwise.
int IOMixer::slaveWrite
(
int id,
void * buf,
int size
);
Write <size> bytes from <buf> to slave with id <id>.
id - id of target slave (IN).
buf - source buffer to write (IN).
size - number of bytes to be written (IN).
RETURNS: 0 if all data written,
-1 otherwise.
int IOMixer::shutdown
(
);
Shutdown master FD. It sends EOF for ID #0,
where ID #0 is reserved for master.
int IOMixer::flush
(
);
Wait until all slave threads finished work.
void IOMixer::setSlaveDeadCallback
(
IOSlaveDeadProto callback,
void * ctx
);
Register callback to inform caller when slave with given ID dead.
callback - pointer to function, which will be called if one
of slave dead (IN).
ctx - custom, caller specified data passed directly
into callback (IN/OPT).
RETURNS: none.
void IOMixer::setQuietMode
(
int value
);
Enable/disble quiet mode to avoid printint error messages longer.
int IOMixer::isPointerCorrect
(
IOMixer * ptr
);
Check is given this pointer points to correct IOMixer *object.
ptr - this pointer to check (IN).
RETURNS: 1 if given pointer points to correct IOMixer object,
0 otherwise.
int IOMixer::setSlaveCompression
(
int id,
int enabled
);
Enable or disable IOMIXER_FLAG_COMPRESSION_ON flag on selected
channel. After that outcoming data on this channel will be
compressed/uncompressed.
id - slave ID to change (IN).
enabled - set to 1 to enable compression, 0 to disable (IN).
RETURNS: 0 if OK.
int IOMixer::initZLib
(
);
Initialize ZLib library.
Called internally only.
RETURNS: 0 if OK.
const char * IOMixer::objectName
(
);
Get object name generated in constructor.
void IOMixer::addRef
(
);
Increase refference counter.
WARNING! Every call to addRef() MUSTS be followed by one release() call.
TIP #1: Object will not be destroyed until refference counter is greater
than 0.
TIP #2: Don't call destructor directly, use release() instead. If
refference counter achieve 0, object will be destroyed
automatically.
void IOMixer::release
(
);
Decrease refference counter increased by addRef() before.
IOFifo::IOFifo
(
unsigned int capacity
);
Create new IOFifo with given capacity.
capacity - size of fifo in bytes (IN).
IOFifo::~IOFifo
(
);
Free buffers allocated in constructor.
int IOFifo::push
(
void * source,
int len
);
Add data to the end of FIFO.
Buffer before: xx xx xx xx xx
Buffer after : xx xx xx xx xx yy yy yy yy ...
source - source buffer with data to append (IN).
len - number of bytes to append (IN).
RETURNS: 0 if all bytes appended,
-1 otherwise.
int IOFifo::pop
(
void * dest,
int len,
int peekOnly
);
Pop data from the begin of FIFO.
Buffer before: xx xx xx xx yy yy yy yy ...
Buffer after : yy yy yy yy ...
TIP#1: If dest buffer is NULL, data are popped from FIFO,
but don't written anywhere.
TIP#2: Skip len parameter or set to -1 if you want to pop up
all data stored in queue.
TIP#3: Use peekOnly flag to get data WITHOUT removing it from FIFO.
dest - buffer where to write popped data (OUT/OPT).
len - number of bytes to pop, if set to -1 all available data
will be popped (IN/OPT).
peekOnly - set to 1 if you want copy data to dest buffer WITHOUT
remove it from buffer (IN/OPT).
RETURNS: 0 if all bytes popped,
-1 otherwise..
int IOFifo::eat
(
int len
);
Eat data from the begin of FIFO.
Buffer before: xx xx xx xx yy yy yy yy ...
Buffer after : yy yy yy yy ...
Works as pop() method with destination set to NULL.
len - number of bytes to eat (IN).
RETURNS: 0 if all bytes eated,
-1 otherwise..
int IOFifo::peek
(
void * dest,
int len
);
Copy <len> bytes from begin of FIFO to <dest>, but
do NOT remove them from FIFO.
Works as pop() with peekOnly flag set to 1.
dest - buffer where to store readed data (OUT).
len - number of bytes to read. If set to -1 all
available data will be copied (IN/OPT).
RETURNS: 0 if all bytes copied,
-1 otherwise.
uint64_t IOFifo::peekQword
(
int endian
);
Peek QWORD from fifo begin, but do NOT remove it from buffer.
WARNING: If there is less than 8 bytes in buffer, return value
is always zero.
endian - set to IO_BIG_ENDIAN or IO_LITTLE_ENDIAN (IN).
RETURNS: First QWORD in queue.
uint32_t IOFifo::peekDword
(
int endian
);
Peek DWORD from fifo begin, but do NOT remove it from buffer.
WARNING: If there is less than 4 bytes in buffer, return value
is always zero.
endian - set to IO_BIG_ENDIAN or IO_LITTLE_ENDIAN (IN).
RETURNS: First DWORD in queue.
uint8_t IOFifo::peekByte
(
);
Peek byte from fifo begin, but do NOT remove it from buffer.
WARNING: If there is less than 1 bytes in buffer, return value
is always zero.
RETURNS: First byte in queue.
void IOFifo::lock
(
);
Lock access to fifo.
void IOFifo::unlock
(
);
Unlock access to fifo blocked by lock() before.
unsigned int IOFifo::bytesLeft
(
);
Return number of free bytes, which can be append to fifo.
unsigned int IOFifo::size
(
);
Return number of bytes already stored inside fifo.
unsigned int IOFifo::capacity
(
);
Return total fifo capacity in bytes.
int CreatePipeEx
(
int pipe[2],
SECURITY_ATTRIBUTES sa[2],
int bufSize,
DWORD readMode,
DWORD writeMode,
int timeout
);
Create fake anonymous pipe pair ready for asynchronous read.
pipe - buffer to store read and write instances of pipe (OUT).
sa - security attributes to set (IN).
bufSize - buffer size in bytes (IN).
readMode - flags for read pipe (IN).
writeMode - flags for write pipe (IN).
RETURNS: 0 if OK.
int IOLoop
(
int count,
int * fd,
int * direct,
IOFifo * queue,
IOCompletedProto callback
);
Template routine for main I/O loop.
count - number of FDs to read/write. MUST much with number of
elements in fd[], direct[] and queue[] tables (IN).
fd - table with FDs to read or write (IN).
direct - 0 at index i menns fd[i] is input device,
1 at index i means fd[i] is output device (IN).
queue - table with IOFifo objects related with related fd.
Used to collect data incoming from fd (direct=0),
or as data source written to fd (direct=1) (IN/OUT).
callback - routine called when portion of data received or send.
Can be NULL if not needed. (IN/OPT).
RETURNS: 0 if loop finished in usual way,
-1 if abnormal exit.
int IOTimeoutRead
(
int fd,
void * buf,
int size,
int timeout
);
Works like standard CRT read(), but with timeout functionality.
fd - CRT file descriptor (received from open()) (IN)
buf - buffer where to store readed data (OUT)
size - number of bytes to read (IN)
timeout - timeout in ms or -1 for infinite (IN)
RETURNS: number of bytes readed or
-1 if error.
| Title: | LibIpc |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Inter-process comunication. |
| Description: | - |
| Dependences: | LibDebug LibThread LibLock |
| Used by: | Tegenaria-core LibIpc-example LibIpc-example2 |
- Handle timeout - Move processing connection into another thread
int IpcServerLoop
(
const char * nameIn,
IpcWorkerProto callback,
void * ctx,
int * ready
);
Main loop for named pipe server.
Can be used to set up blocking server loop in user app.
TIP #1: To create server loop in another thread ('non-blocking') use
IpcServerCreate() instead.
TIP #2: Use IpcServerKill to close server.
name - pipe name to create (IN).
callback - handler function to process incoming connections (IN).
timeout - maximum allow time to process one connection in ms (IN).
ctx - caller context passed to callback function (IN/OPT).
ready - set to 1 when server loop initialized (OUT/OPT).
RETURNS: 0 if OK.
int IpcServerThreadLoop
(
IpcJob * job
);
Wrapper to pass IpcServerLoop() to threadCreate.
Used internally only by IpcServerCreate.
int IpcServerCreate
(
const char * name,
IpcWorkerProto callback,
void * ctx
);
Create IPC server in another thread. Works as non-blocking IpcServerLoop().
name - pipe name to create (IN).
callback - handler function to process incoming connections (IN).
ctx - caller context passed to callback function directly (IN/OPT).
TIP #1: Use IpcServerKill to close server.
RETURNS: 0 if OK.
int IpcServerKill
(
const char * name
);
Close server loop started by IpcServerLoop() or IpcServerCreate() before.
WARNING! Do not use this function inside IPC request handler (passed
to IpcServerCreate as callback). It can causes deadlock.
TIP#1: To finish server inside IPC request handler use IpcServerFinish()
instead.
name - name passed to IpcServerXXX function before (IN).
RETURNS: 0 if OK.
int IpcServerMarkLastRequest
(
const char * name
);
Mark pipe loop started by IpcServerLoop() or IpcServerCreate() as
finished. After exit from last pending IPC request server should exit
from server loop.
WARNING! This function should be called from IPC Request handler (passed
to IpcServerCreate as callback). It means that current IPC
request is last request in loop.
TIP#1: If you want to finish IPC loop outside IPC request handler use
IpcServerKill() instead.
name - name passed to IpcServerXXX function before (IN).
RETURNS: 0 if OK.
HANDLE IpcOpenHandle
(
const char * name,
int timeout = IPC_DEFAULT_TIMEOUT
);
Open connection to existing named pipe server.
name - pipe name passed to IpcServer() in server process (IN).
timeout - maximum allow wait time in ms (IN/OPT).
RETURNS: Pipe HANDLE use with WriteFile/ReadFile functions,
or INVALID_HANDLE_VALUE if error.
int IpcOpen
(
const char * name,
int timeout
);
Open connection to existing pipe server.
name - pipe name passed to IpcServer() in server process (IN).
timeout - maximum allow wait time in ms (IN/OPT).
RETURNS: CRT descriptor (fd) ready to use with write/read funcions,
or -1 if error.
int IpcRequest
(
const char * pipeName,
int * serverCode,
char * serverMsg,
int serverMsgSize,
const char * fmt
);
- Send single request to pipe server
- read answer in format 'XYZ > message'
- split answer to <XYZ> code and <message> parts.
Example usage:
IpcRequest(PIPENAME, &code, answer, sizeof(answer),
"share --alias %s --path %s", alias, path);
TIP: If only exit code is needed <answer> can be set to NULL.
pipeName - pipe name, where to send command (IN).
serverCode - exit code returned by server (OUT/OPT).
serverMsg - ASCIZ message returned by server (OUT/OPT).
serverMsgSize - size of answer buffer in bytes (IN/OPT).
fmt - printf like parameters to format command to send (IN).
RETURNS: 0 if request sucessfuly sent and asnwer from server received.
-1 otherwise.
WARNING!: Request could still failed on server side.
To get server's side exit code use 'answerCode' parameter.
int IpcSendAnswer
(
int fd,
int code,
const char * msg
);
Format 'XYZ> message' string and send it to given CRT FD.
fd - CRT FD, where to send answer (IN).
code - 3 digit answer code (e.g. 100) (IN).
msg - Optional, ASCIZ message to send, can be NULL (IN/OPT).
RETURNS: 0 if OK.
int TimeoutReadSelect
(
int fd,
void * buf,
int len,
int timeout
);
Work like system read(), but with timeout functionality.
fd - CRT file descriptor where to read from (IN).
buf - destination buffer (OUT).
len - number of bytes to read (IN).
timeout - timeout in seconds (IN).
RETURNS: Number of bytes readed or
-1 if error.
int TimeoutReadFileOv
(
HANDLE handle,
void * buf,
int len,
int * readed,
int timeout
);
Work like system ReadFile(), but with timeout functionality.
WARNING: Handle MUST be opened in overlapped mode.
handle - native HANDLE to input device e.g. named pipe or socket (IN).
buf - destination buffer (OUT).
len - number of bytes to read (IN).
readed - number of bytes readed (OUT).
timeout - timeout in miliseconds (IN).
RETURNS: 1 if success and still something to read,
0 otherwise.
int SetUpSecurityAttributesEverybody
(
SECURITY_ATTRIBUTES * sa
);
Allocating security attributes giving READ+WRITE rights to
everybody, and maximum allowed rights to administartors.
WARNING: Output struct need to be uninitialized by
FreeSecurityAttributes() function!
sa - security attributes struct to fill (OUT).
RETURNS: 0 if OK.
void FreeSecurityAttributes
(
SECURITY_ATTRIBUTES * sa
);
Free Security Attributes struct allocated by
SetUpSecurityAttributes() function.
| Title: | LibJob |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Template to performing asynchronous jobs like downloading file from network or compressing data. |
| Description: | - |
| Dependences: | LibDebug LibThread LibLock |
| Used by: | Tegenaria-core libjob-example01-simple |
Job::Job
(
const char * title,
JobNotifyCallbackProto notifyCallback,
void * notifyCallbackCtx,
JobWorkerCallbackProto workerCallback,
void * workerCallbackCtx
);
Create job object.
title - job's title (IN/OPT).
notifyCallback - callback called when job changed state or progress meter (IN/OPT).
notifyCallbackCtx - caller context passed to notifyCallback() directly (IN/OPT).
workerCallback - callback function performing real job work (IN).
workerCallbackCtx - caller context passed to workerCallback() directly (IN/OPT).
void Job::triggerNotifyCallback
(
int code
);
Call underlying notify callback set in constructor.
code - one of JOB_NOTIFY_XXX codes (IN).
void Job::addRef
(
);
Increase refference counter.
WARNING! Every call to addRef() MUSTS be followed by one release() call.
TIP #1: Object will not be destroyed until refference counter is greater
than 0.
TIP #2: Don't call destructor directly, use release() instead. If
refference counter achieve 0, object will be destroyed
automatically.
void Job::release
(
);
Decrease refference counter increased by addRef() before.
int Job::workerLoop
(
void * jobPtr
);
Worker loop performing real job in background thread.
This function calls underlying doTheJob() function implemented in child class.
jobPtr - pointer to related Job object (this pointer) (IN/OUT).
void Job::setState
(
int state
);
Change current state. See JOB_STATE_XXX defines in Job.h.
state - new state to set (IN).
int Job::getState
(
);
Get current state code. See JOB_STATE_XXX defines in Job.h.
RETURNS: Current state code.
const char * Job::getStateString
(
);
Get current state as human readable string.
RETURNS: Name of current job's state.
int Job::wait
(
int timeout
);
Wait until job finished or stopped with error.
timeout - maximum time to wait in ms. Set to -1 for infinite (IN).
RETURNS: 0 if OK (job finished/stopped on exit),
-1 otherwise (job still active on exit).
void Job::cancel
(
);
Send stop signal for pending job object.
After that related thread should stop working and state
should change to JOB_STATE_STOPPED.
WARNING#1: Job object MUSTS be still released with release() method.
TIP#1: To stop and release resources related with job use below code:
job -> cancel();
job -> release();
const char * Job::getTitle
(
);
Retrieve job's title set in constructor before.
Job::~Job
(
);
Don't be sucker! Describe your function in source code.
double Job::getPercentCompleted
(
);
Get current job's progress in percentages (0-100%).
int Job::getErrorCode
(
);
Get error code related with object.
This function should be used when job finished with error state.
void Job::setErrorCode
(
int code
);
Set current error code related with job.
This function should be used to inform caller why job object
finished with error state.
void Job::setPercentCompleted
(
double percentCompleted
);
Set current job's progress in percentages (0-100%).
| Title: | LibLock |
| Type: | LIBRARY |
| Author(s): | Radoslaw Kolodziejczyk (radek.kolodziejczyk@gmail.com), Lukasz Bienczyk (lukasz.bienczyk@gmail.com), Sylwester Wysocki (sw143@wp.pl) |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Locks |
| Description: | - |
| Dependences: | LibDebug LibError |
| Used by: | Tegenaria-core LibNetEx LibSecure LibSftp LibNet-example01-thread-server LibNet-example02-single LibNet-example05-HP-server LibIO LibIpc LibJob LibObject LibProcess LibProcess-example03-monitor LibProcess-example04-wait-for-parent LibLock-example01-mutex LibLock-example02-semaphore liblock-example03-requestpool LibIpc-example LibIpc-example2 LibIO-example01-file-mixer LibIO-example02-network-mixer LibIO-example03-timeout-read |
RequestPool::RequestPool
(
int size,
const char * name
);
Constructor.
Allocate and zero pending request table.
size - maximum number of pending request in one time (IN/OPT).
name - arbitrary request pool name to debug code easier (IN/OPT).
RequestPool::~RequestPool
(
);
Destructor.
Free request table created in constructor.
const char * RequestPool::getName
(
);
Get object name.
Request * RequestPool::find
(
int id
);
Find request with given ID.
WARNING: Function is not thread safe itselt. Caller MUSTS use lock()/unlock()
by own.
id - request's ID set int RequestPush() time before (IN).
RETURNS: Pointer to found Request object,
NULL if request with given ID does not exists.
Request * RequestPool::findFree
(
);
Find first not used request in requests table.
WARNING: Function is not thread safe itselt. Caller MUSTS use lock()/unlock()
by own.
RETURNS: Pointer to first not used request,
NULL if too many requests.
int RequestPool::wait
(
int id,
int timeout
);
Wait until given request served by serve() function.
WARNING#1: This function pop request from table even if timeout reached.
WARNING#2: Only one thread can wait for request at one time.
TIP#1: Use serve() method from another thread to serve pending request.
After that wait() will finished with code 0.
Parameters:
id - request ID passed to push() before (IN).
timeout - timeout in ms, -1 for infinity (IN).
RETURNS: 0 if OK,
ERR_WRONG_PARAMETER if there is no request with given ID,
ERR_TIMEOUT if timeout reached.
int RequestPool::serve
(
int id
);
Mark request with given ID as served. After that thread wait() from
another thead will be finished.
id - request ID to serve, set in push() time (IN).
RETURNS: 0 if OK,
ERR_WRONG_PARAMETER if request with given id does not exist.
int RequestPool::serve
(
Request * r
);
Mark request as served. After that thread wait() from another
thread will be finished.
r - pointer to request retrieved from find() function (IN).
RETURNS: 0 if OK,
ERR_WRONG_PARAMETER if request with given id does not exist.
int RequestPool::push
(
int id,
void * inputData,
void * outputData
);
Push new request to pending table.
TIP#1: Another thread should use serve() to finalize (serve) request.
TIP#2: Use wait() to wait until request served.
WARNING#1: Every call to push() MUSTS be followed by one call to serve()
with the same ID.
id - request ID to assign, MUSTS be unique (IN).
inputData - pointer to arbitrary input data, can be NULL (IN/OUT).
outputData - pointer to arbitrary output data, can be NULL (IN/OUT).
RETURNS: 0 if OK,
-1 otherwise.
void RequestPool::lock
(
);
Lock request pool object.
WARNING: Every call to lock() MUSTS be followed by one unlock() call.
void RequestPool::unlock
(
);
Unlock request pool object locked by lock() function before.
void Request::lockData
(
);
Lock data pointers stored inside Request struct.
WARNING: Every calls to lockData() MUSTS be followed by one unlockData()
call.
void Request::unlockData
(
);
Unlock data pointers stored inside Request struct locked by lockData()
before.
void Request::serve
(
);
Mark request as served.
Semaphore::Semaphore
(
int initValue,
const char * name
);
Don't be sucker! Describe your function in source code.
Semaphore::~Semaphore
(
);
Don't be sucker! Describe your function in source code.
int Semaphore::wait
(
int timeout
);
Wait until semafore reach signaled state.
TIP#1: Use signal() function to change object into signaled state.
TIP#2: Use isSignaled() to check is semaphore signaled without falling into
waiting loop.
timeout - timeout in ms, -1 for infinite (IN/OPT).
RETURNS: 0 on success,
1 on timeout,
-1 if error.
void Semaphore::signal
(
);
Don't be sucker! Describe your function in source code.
int Semaphore::tryWait
(
);
Decrement the counter of the semaphore. Do not block if traditional
wait() would block.
int Semaphore::getState
(
);
Retrieve currect semaphore counter.
int Semaphore::unwind
(
);
Decrement the counter untill the wait call would block.
int Semaphore::unwoundWait
(
int timeout
);
Don't be sucker! Describe your function in source code.
void Semaphore::setName
(
const char * name
);
Don't be sucker! Describe your function in source code.
Mutex::Mutex
(
const char * name
);
Constructor. Create named or anonymous mutex object.
name - optional, human readable name (IN/OPT).
Mutex::~Mutex
(
);
Destructor.
void Mutex::lock
(
);
Get ownership of the mutex.
TIP#1: Every call to lock() MUSTS be followed by one call to unlock().
void Mutex::unlock
(
);
Releae mutex locked by lock() method before.
WARNING: Only thread, that called lock() can free mutex.
int Mutex::getState
(
);
Get current mutex state.
Unimplemented.
void Mutex::setName
(
const char * fmt
);
Change mutex name.
fmt - C printf like format (IN).
| Title: | LibProcess |
| Type: | LIBRARY |
| Author(s): | Radoslaw Kolodziejczyk (radek.kolodziejczyk@gmail.com), Lukasz Bienczyk (lukasz.bienczyk@gmail.com), Sylwester Wysocki (sw143@wp.pl) |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Creating and monitoring processes |
| Description: | - |
| Dependences: | LibDebug LibLock LibThread LibStr |
| Used by: | Tegenaria-core LibNet-example01-thread-server LibNet-example02-single LibProcess-example01-sshd LibProcess-example02-wrapper LibProcess-example03-monitor LibProcess-example04-wait-for-parent LibProcess-example05-daemon LibLock-example01-mutex LibLock-example02-semaphore LibIO-example02-network-mixer |
int ProcessCreate
(
const char * argv[],
int fdin,
int fdout,
int fderr,
int fdType,
int options
);
USE:
const char *argv[3 + argv_count];
argv[0] = "path_to_process";
argv[1] = "parameter#1";
argv[2] = "parameter#2";
argv[3] = "parameter#3";
argv[4] = NULL;
argv[] - NULL terminated parameter list (IN).
fdin - FD to set for std input (IN/OPT).
fdout - FD to set for std output (IN/OPT).
fderr - FD to set for std error (IN/OPT).
fdType - type of specified fdin/fdout/fderr values. One of
PROCESS_TYPE_XXX values defined in LibProcess.h. Defaulted
to PROCESS_TYPE_CRT if skipped. (IN/OPT).
options - combination of PROCESS_OPTIONS_XXX flags (IN/OPT).
TIP #1: Set fdin/fdout/fderr to -1 to inherit handle from parent.
TIP #2: Set fdin/fdout/fderr to -2 to redirect handle to nul.
TIP #3: Set fdType to PROCESS_TYPE_HANDLE if you have raw win32 handle on windows.
RETURNS: pid of new process
or -1 if error.
int ProcessIsRunning
(
int pid
);
Check does given proces live.
pid - pid of process to check (IN).
RETURNS: 1 if process is running,
0 if dead or error.
void ProcessKill
(
int pid,
int force
);
Don't be sucker! Describe your function in source code.
int ProcessWait
(
int pid,
int timeout,
int * resultCode
);
Wait until process finished or timeout reached.
WARNING#1: Function does NOT detect zoombi processes on Linux as long
as resultCode parameter is NULL. Process become zoombi when
finished its work, but parent didn't call waitpid to pop
result code from it.
pid - pid of process to wait (IN).
timeout - maximum allowed wait time in miliseconds or -1 for inifinity (IN).
resultCode - if process died before the timeout, this value returns
its result code. Can be NULL if not needed. (OUT/OPT).
RETURNS: 0 if process dead until timeout,
1 if timeout reached,
-1 if error.
TIP #1: you can get resultCode only for child process.
int ProcessGetParentPid
(
);
Find PID of parent process.
RETURNS: PID of parent of current running process,
or -1 if error.
int ProcessGetCurrentPid
(
);
Find PID of own process.
RETURNS: PID of current running process,
or -1 if error.
int ProcessGetModulePath
(
char * path,
int pathSize
);
Retrieve full, absolute path to current running binary
(e.g. c:/dirligo/dirligo.exe)
path - buffer, where to store retrieved path (OUT).
pathSize - size of path[] buffer in bytes (IN).
RETURNS: 0 if OK.
int ProcessExpandRelativePath
(
char * normPath,
int pathSize,
const char * relative
);
Transform relative (to where current binary stored) path into full path.
E.g. it transforms "/somedir" into "<where current process live>/somedir".
We use it becouse daemon (service) doesn't start in path, where current binary
stored until we don't set current directory manually.
WARNING: If passed path is already absolute it returns the same string.
normPath - full, generated path (OUT).
pathSize - size of path buffer in bytes (IN).
relative - relative path postfix to add to base path (IN).
quiet - do not write logs if set to 1 (IN).
RETURNS: 0 if OK.
int ProcessDaemonize
(
);
Create duplicate of current running process and leave it alone in background,
while parent procses (current running) is going to quit.
WARNING#1: Linux only.
Child process : function exits with code 0
Parent process : end of function never reached, process exits in the middle.
RETURNS: 0 for child when success,
-1 for parent if error.
int ProcessGetBinaryPathByPid
(
char * binaryPath,
int binaryPathSize,
int pid
);
Retrieve full, absolute path to binary related with running process.
WARNING#1: Caller MUSTS have PROCESS_VM_READ right to target process
on Windows OS. In other case function will fail with system code
ACCESS_DENIED (5).
Parameters:
binaryPath - buffer, where to store full path to binary file related with
given running process (e.g. c:\windows\explorer.exe) (OUT)
binaryPathSize - size of binaryPath[] buffer in bytes (IN).
pid - pid of process to check (IN).
RETURNS: 0 if OK.
int ProcessClose
(
ProcessHandle_t * proc
);
Close handle retrieved from ProcessCreate() before.
WARNING: Function does NOT terminate process if still running.
proc - handle to process retrieved from ProcessCreate() before (IN).
RETURNS: 0 if success,
-1 otherwise.
int ProcessIsRunning
(
ProcessHandle_t * proc
);
Check does given proces live.
proc - process handle retrievied from ProcessCreate() function before (IN).
RETURNS: 1 if process is running,
0 if dead,
-1 if error.
int ProcessKill
(
ProcessHandle_t * proc
);
Unconditional terminate process.
proc - process handle retrievied from ProcessCreate() function before (IN).
RETURNS: 0 if success,
-1 otherwise.
int ProcessWait
(
ProcessHandle_t * proc,
int timeout,
int * resultCode
);
Wait until process finished or timeout reached.
proc - process handle retrievied from ProcessCreate() function before (IN).
timeout - maximum allowed wait time in miliseconds or -1 for inifinity (IN).
resultCode - if process died before the timeout, this value returns
its result code. Can be NULL if not needed. (OUT/OPT).
RETURNS: 0 if process dead until timeout,
1 if timeout reached,
-1 if error.
TIP #1: On Linux you can get resultCode only for child process.
int ProcessWatch
(
ProcessHandle_t * proc,
ProcessWatchCbProto callback,
int timeout,
void * ctx
);
Add process to monitored processes.
After that process monitor will inform caller when process dead
or specified timeout reached.
TIP#1: Use ProcessCancelWatch() to remove process from monitor.
proc - process handle retrieved from ProcessCreate() before (IN).
callback - callback function to notify user when process dead or
timeout reached (IN).
timeout - maximum allowed life time for process in ms or -1 to infinite (IN).
ctx - caller specified context passed directly to callback (IN).
RETURNS: 0 if OK.
int ProcessCancelWatch
(
ProcessHandle_t * proc
);
Remove process from monitored processes (added by ProcessWatch() before).
proc - process handle retrieved from ProcessCreate() before (IN).
RETURNS: 0 if OK.
int ProcessGetPidByHandle
(
ProcessHandle_t * proc
);
Return pid of given process.
proc - process handle retrieved from ProcessCreate() before (IN).
RETURNS: PID of process given as proc parameter,
or -1 if error.
int ProcessIsRunningById
(
int pid
);
Check does given proces live.
pid - pid of process to check (IN).
RETURNS: 1 if process is running,
0 if dead,
-1 if error.
int ProcessKillByPid
(
int pid
);
Unconditional terminate process.
pid - pid of process, which we want to kill (IN)
RETURNS: 0 if success,
-1 otherwise.
int ProcessWaitByPid
(
int pid,
int timeout,
int * resultCode
);
Wait until process finished or timeout reached.
WARNING#1: Function does NOT detect zoombi processes on Linux as long
as resultCode parameter is NULL. Process become zoombi when
finished its work, but parent didn't call waitpid to pop
result code from it.
pid - pid of process to wait (IN).
timeout - maximum allowed wait time in miliseconds or -1 for inifinity (IN).
resultCode - if process died before the timeout, this value returns
its result code. Can be NULL if not needed. (OUT/OPT).
RETURNS: 0 if process dead until timeout,
1 if timeout reached,
-1 if error.
TIP #1: you can get resultCode only for child process.
int ProcessWatchByPid
(
int pid,
ProcessWatchCbProto callback,
int timeout,
void * ctx
);
Add process to monitored processes.
After that process monitor will inform caller when process dead
or specified timeout reached.
pid - process ID to monitor (IN).
callback - callback function to notify user when process dead or
timeout reached (IN).
timeout - maximum allowed life time for process in ms or -1 to infinite (IN).
ctx - caller specified context passed directly to callback (IN).
RETURNS: 0 if OK.
int ProcessCancelWatchByPid
(
int pid
);
Remove process from monitored processes (added by ProcessWatchByPid() before).
pid - process ID passed to ProcessWatchByPid() before (IN).
RETURNS: 0 if OK.
void ProcessSleepUs
(
int us
);
Sleep current thread for given number of microseconds.
void ProcessSleepMs
(
int ms
);
Sleep current thread for given number of miliseconds.
void ProcessSleepSec
(
double seconds
);
Sleep current thread for given number of seconds.
ProcessHandle_t * ProcessCreate
(
const char *const argv[],
int fdin,
int fdout,
int fderr,
int fdType,
int options
);
USE:
const char *argv[5]
argv[0] = "path_to_process"
argv[1] = "parameter#1"
argv[2] = "parameter#2"
argv[3] = "parameter#3"
argv[4] = NULL
argv[] - NULL terminated parameter list (IN).
fdin - FD to set for std input (IN/OPT).
fdout - FD to set for std output (IN/OPT).
fderr - FD to set for std error (IN/OPT).
fdType - type of specified fdin/fdout/fderr values. One of
PROCESS_TYPE_XXX values defined in LibProcess.h. Defaulted
to PROCESS_FDTYPE_CRT if skipped. (IN/OPT).
options - combination of PROCESS_OPTIONS_XXX flags (IN/OPT).
TIP #1: Set fdin/fdout/fderr to PROCESS_FD_PARENT to inherit handle from parent.
TIP #2: Set fdin/fdout/fderr to PROCESS_FD_NULL to redirect handle to nul.
TIP #3: Set fdType to PROCESS_FD_TYPE_WINAPI_HANDLE if you have raw windows handle.
RETURNS: Pointer to ProcessHandle_t structure,
or NULL if error.
| Title: | LibReg |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | High-level API to query and modify windows registry. |
| Description: | - |
| Dependences: | LibDebug |
| Used by: | Tegenaria-core LibReg-example01-simple LibReg-example02-list-subkeys |
int RegSetDword
(
HKEY rootKey,
const char * path,
const char * element,
DWORD value,
DWORD flags
);
Write DWORD value to registry. If key not exist yet, function creates new one.
rootKey - one of HKEY_XXX defines (e.g. HKEY_LOCAL_MACHINE) (IN).
path - key path (e.g SYSTEM\CurrentControlSet\Control\FileSystem) (IN).
element - element name (e.g. Win95TruncatedExtensions) (IN).
value - DWORD value to set (IN).
flags - combination of REG_OPTION_XXX flags (e.g. REG_OPTION_VOLATILE) (IN/OPT).
RETURNS: 0 if OK,
WINAPI error code otherwise.
int RegSetString
(
HKEY rootKey,
const char * path,
const char * element,
const char * value,
DWORD flags
);
Write string value to registry. If key not exist yet, function creates new one.
rootKey - one of HKEY_XXX defines (e.g. HKEY_LOCAL_MACHINE) (IN).
path - key path (e.g SYSTEM\CurrentControlSet\Control\FileSystem) (IN).
element - element name (e.g. Win95TruncatedExtensions) (IN).
value - ASCIZ string to set (IN).
flags - combination of REG_OPTION_XXX flags (e.g. REG_OPTION_VOLATILE) (IN/OPT).
RETURNS: 0 if OK,
WINAPI error code otherwise.
int RegSetStringW
(
HKEY rootKey,
const char * path,
const char * element,
const wchar_t * value,
DWORD flags
);
Write string value to registry. If key not exist yet, function creates new one.
rootKey - one of HKEY_XXX defines (e.g. HKEY_LOCAL_MACHINE) (IN).
path - key path (e.g SYSTEM\CurrentControlSet\Control\FileSystem) (IN).
element - element name (e.g. Win95TruncatedExtensions) (IN).
value - ASCIZ string to set (IN).
flags - combination of REG_OPTION_XXX flags (e.g. REG_OPTION_VOLATILE) (IN/OPT).
RETURNS: 0 if OK,
WINAPI error code otherwise.
int RegSetStringList
(
HKEY rootKey,
const char * path,
const char * element,
list<string> values,
DWORD flags
);
Write string list to registry. If key not exist yet, function creates new one.
rootKey - one of HKEY_XXX defines (e.g. HKEY_LOCAL_MACHINE) (IN).
path - key path (e.g SYSTEM\CurrentControlSet\Control\FileSystem) (IN).
element - element name (e.g. Win95TruncatedExtensions) (IN).
values - list of strings to set (IN).
flags - combination of REG_OPTION_XXX flags (e.g. REG_OPTION_VOLATILE) (IN/OPT).
RETURNS: 0 if OK,
WINAPI error code otherwise.
int RegRemove
(
HKEY rootKey,
const char * path
);
Remove given key from registry.
rootKey - one of HKEY_XXX defines (e.g. HKEY_LOCAL_MACHINE) (IN).
path - key path to remove (e.g SYSTEM\CurrentControlSet\Control\FileSystem) (IN).
RETURNS: 0 if OK,
WINAPI error code otherwise.
int RegGetDword
(
DWORD * value,
HKEY rootKey,
const char * path,
const char * element
);
Read DWORD value from registry. Quered key should be REG_DWORD type.
value - output buffer, where to store readed value (OUT).
rootKey - one of HKEY_XXX defines (e.g. HKEY_LOCAL_MACHINE) (IN).
path - key path (e.g SYSTEM\CurrentControlSet\Control\FileSystem) (IN).
element - element name (e.g. Win95TruncatedExtensions) (IN).
RETURNS: 0 if OK,
WINAPI error code otherwise.
int RegGetString
(
char * value,
int valueSize,
HKEY rootKey,
const char * path,
const char * element
);
Read ASCIZ string value from registry. Quered key should be REG_SZ type.
value - output buffer, where to store readed string (OUT).
valueSize - size of value[] buffer in bytes (IN).
rootKey - one of HKEY_XXX defines (e.g. HKEY_LOCAL_MACHINE) (IN).
path - key path (e.g SYSTEM\CurrentControlSet\Control\BiosInfo) (IN).
element - element name (e.g. SystemBiosDate) (IN).
RETURNS: 0 if OK,
WINAPI error code otherwise.
int RegGetStringList
(
list<string> &values,
HKEY rootKey,
const char * path,
const char * element
);
Read ASCIZ string list from registry. Quered key should be REG_MULTI_SZ type.
values - string list where to store readed list (OUT).
rootKey - one of HKEY_XXX defines (e.g. HKEY_LOCAL_MACHINE) (IN).
path - key path (e.g SYSTEM\CurrentControlSet\Control\ContentIndex) (IN).
element - element name (e.g. DllsToRegister) (IN).
RETURNS: 0 if OK,
WINAPI error code otherwise.
int RegListSubkeys
(
vector<string> &subkeys,
HKEY rootKey,
const char * path
);
List subkeys inside given key.
const char * RegGetTypeName
(
DWORD type
);
Translate REG_XXX registry type into human readable string.
type - one of REG_XXX (e.g. REG_DWORD) value (IN).
RETURNS: human readable type's name
or "UNKNOWN" if type not recognized.
const char * RegGetRootKeyName
(
HKEY key
);
Retrieve human readable name for one of HKEY_XXX predefined root keys
(e.g. HKEY_LOCAL_MACHINE).
key - one of HKEY_XXX predefined keys (IN).
RETURNS: Human readable key name
or "UNKNOWN" if key not recognized.
| Title: | LibRuntime |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Manage runtime loaded code. |
| Description: | - |
| Dependences: | |
| Used by: | Tegenaria-core |
| Title: | LibService |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | High level API to manage windows services. |
| Description: | - |
| Dependences: | LibDebug |
| Used by: | Tegenaria-core |
int ServiceGetTypeCode
(
const char * serviceType
);
Convert service type string to int code.
serviceType - string with start type (eg. "FILE_SYSTEM") (IN).
RETURNS: Service type code or -1 if error.
int ServiceGetStartTypeCode
(
const char * startType
);
Convert service start type string to int code.
serviceStartType - string with start type (IN).
RETURNS: Start type code or -1 if error.
int ServiceOpen
(
SC_HANDLE * serviceManager,
SC_HANDLE * service,
const char * name,
DWORD rights,
int quiet
);
Open service manager and given service.
WARNING! serviceManager and service MUST be closed by
CloseServiceHandle() function.
serviceManager - handle to service manager (IN/OUT).
If NULL, new handle opened, otherside
given handle used as manager.
service - handle to opened service with given name (OUT).
name - name of service to open (IN).
rights - requested access right for opened service (IN).
quiet - don't write error messages if set to 1 (IN).
RETURNS: 0 if OK.
int ServiceAdd
(
const char * name,
const char * displayName,
int type,
int startType,
const char * path,
bool failIfExists,
const char * obj,
const char * pass,
int startAfter,
int quiet
);
Install and start new service.
name - service name (IN)
displayName - service "long" name. Can be NULL. (IN)
type - service type (IN).
startType - start type (IN).
path - path to executable file with service's code (IN).
failIfExists - function will fail if service already exists (IN).
obj - target account name e.g. ".\\nx" (IN).
pass - account's password if obj parameter specified (IN).
startAfter - start service after add (default set to 1) (IN/OPT).
quiet - do not write error messages if 1 (IN/OPT).
RETURNS: 0 if OK.
int ServiceChange
(
const char * name,
const char * displayName,
int type,
int startType,
const char * path
);
Change parameters for existing service.
name - service name (IN)
displayName - service "long" name. Can be NULL. (IN)
type - service type (IN).
startType - start type (IN).
path - path to executable file with service's code (IN).
RETURNS: 0 if OK.
int ServiceDelete
(
const char * name,
int quiet
);
Stop and delete existing service.
name - service name to delete (IN).
quiet - do not write error messages if 1 (IN/OPT).
RETURNS: 0 if OK.
int ServiceGetStatus
(
SERVICE_STATUS * status,
const char * name,
int quiet
);
Retrieve status of given service.
status - buffer, where to store retrieved status (OUT).
name - service name to query (IN).
quiet - don't write log on errors if 1 (IN).
RETURNS: 0 if OK.
int ServiceStart
(
const char * name,
int argc,
const char ** argv
);
Start service.
name - name of service to start (IN).
argc - number of elements in argv table (IN).
argv - table with input arguments for service binary (IN).
RETURNS: 0 if OK.
int ServiceStop
(
const char * name,
int timeout
);
Send stop signal to given service and optionally
wait until service reach stopped.
name - name of service to stop (IN).
timeout - maximum time in ms to wait. If service not stopped before
we kill it manually (IN/OPT).
RETURNS: 0 if OK.
int ServiceGetConfig
(
QUERY_SERVICE_CONFIG ** config,
const char * name,
int quiet
);
Retrieve config of given service.
WARNING: Output config buffer MUST be free by caller.
config - pointer to new allocated config struct (OUT).
name - service name to query (IN).
quiet - don't write log on errors if 1 (IN).
RETURNS: 0 if OK.
int ServiceExists
(
const char * name
);
Check does service already exists.
name - short name of service (IN)
RETURNS: 1 if exists,
0 if not exists or error.
int ServiceWaitUntilRunning
(
SC_HANDLE service,
DWORD initState,
DWORD targetState,
int timeout,
int quiet
);
Wait up to <timeout> ms until given service change state from <initState>
to <targetState> state.
We use it to wait until start/stop operations finished.
WARNING: Input handle MUST have SERVICE_QUERY_STATUS right.
service - handle to opened service (IN).
targetState - expected state, when reached we quit with success (IN).
timeout - maximum time limit in ms. If missed default one used. (IN/OPT).
quiet - do not write errors on stderr if 1 (IN/OPT).
RETURNS: 0 if service is running on function's exit.
int ServiceKill
(
SC_HANDLE service,
int quiet
);
Retrieve PID for opened process and terminate it.
WARNING: Handle MUSTS have SERVICE_QUERY_STATE right.
WARNING: Caller user MUSTS have SE_DEBUG right to open not-own processes.
service - handle to opened service (IN).
quiet - do not write errors on stderr if 1 (IN/OPT).
RETURNS: 0 if OK.
int ServiceGetPid
(
const char * name
);
Retrieve PID of service process.
name - service name (IN).
RETURNS: PID of service process,
or -1 if error.
int ExpandRelativePath
(
char * normPath,
int pathSize,
const char * relative,
int quiet
);
Transform relative (to where dlsetup stored) path into full path.
E.g. it transforms "/somedir" into "<where is dlsetup.exe>/somedir".
WARNING: If passed path is already absolute it returns the same string.
normPath - full, generated path (OUT).
pathSize - size of path buffer in bytes (IN).
relative - relative path postfix to add to base path (IN).
quiet - do not write logs if set to 1 (IN).
RETURNS: 0 if OK.
int SetPrivilege
(
const char * privName,
int enabled
);
Enable or disable privilege for current running process
privName - privilege name (IN)
enabled - 1 for enabling, 0 for disabling (IN)
RETURNS: 0 if OK.
| Title: | LibSSMap |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Wrapper for map<string, string> class to read/write content from/to external file easly. |
| Description: | - |
| Dependences: | LibDebug |
| Used by: | Tegenaria-core LibCGI LibSSMap-example01-simple LibSSMap-example02-serialize |
int SSMap::saveToFile
(
const string &fname
);
Save SSMap to file.
fname - destination filename, where to dump map (IN).
RETURNS: 0 if OK.
int SSMap::saveToFileEx
(
const string &fname,
int flags
);
Save SSMap to file.
fname - destination filename, where to dump map (IN).
flags - extra flags to format output file, see SSMap.h SSMAP_FLAGS_XXX defines (IN).
RETURNS: 0 if OK.
int SSMap::loadFromFile
(
const string &fname
);
Load SSMap from file.
fname - source filename, where to load map from (IN).
RETURNS: 0 if OK.
void SSMap::saveToString
(
string &data
);
Serialize SSMap object into one continuos string.
data - string, where to write serialized data (OUT).
int SSMap::loadFromString
(
char * data
);
Load SSMap object from one continous string created by saveToString()
method before.
WARNING: Function destroys input data[] string.
data - source, single continous string created by saveToString() before (IN).
RETURNS: 0 if OK.
void SSMap::set
(
const char * lvalue,
const char * rvalue
);
Set lvalue key to rvalue string.
lvalue - key, where to assign data (IN).
rvalue - string value to assign (IN).
TIP#1: Use getXXX() methods to get back set value.
void SSMap::setInt
(
const char * lvalue,
int rvalue
);
WARNING: rvalue will be converted to string internally.
TIP#1: Use getXXX() methods to get back set value.
void SSMap::setPtr
(
const char * lvalue,
const void * rvalue
);
Set lvalue key to rvalue pointer.
WARNING: rvalue will be converted to string internally.
lvalue - key, where to assign data (IN).
rvalue - pointer value to assign (IN).
TIP#1: Use getXXX() methods to get back set value.
const char * SSMap::get
(
const char * lvalue
);
Get value assigned to lvalue key as string.
rvalue - key, where to search data (IN).
RETURNS: String value assigned to key lvalue or
NULL if key does not exist.
const char * SSMap::get
(
const string &lvalue
);
Get value assigned to lvalue key as string.
rvalue - key, where to search data (IN).
RETURNS: String value assigned to key lvalue or
NULL if key does not exist.
const char * SSMap::safeGet
(
const char * lvalue
);
Get value assigned to lvalue key as string with not-null warranty.
rvalue - key, where to search data (IN).
RETURNS: String value assigned to key lvalue or
empty string if key does not exist.
const char * SSMap::safeGet
(
const string &lvalue
);
Get value assigned to lvalue key as string with not-null warranty.
rvalue - key, where to search data (IN).
RETURNS: String value assigned to key lvalue or
empty string if key does not exist.
int SSMap::getInt
(
const char * lvalue
);
Get value assigned to lvalue key and convert it to integer.
rvalue - key, where to search data (IN).
RETURNS: Integer value assigned to key lvalue or
0 if key does not exist.
int SSMap::getInt
(
const string &lvalue
);
Get value assigned to lvalue key and convert it to integer.
rvalue - key, where to search data (IN).
RETURNS: Integer value assigned to key lvalue or
0 if key does not exist.
void * SSMap::getPtr
(
const char * lvalue
);
Get value assigned to lvalue key and convert it to hex pointer format.
rvalue - key, where to search data (IN).
RETURNS: Pointer value assigned to key lvalue or
NULL if key does not exist.
int SSMap::isset
(
const char * lvalue
);
Check is lvalue key exist in map.
rvalue - key, where to search data (IN).
RETURNS: 1 if key exist,
0 otherwise.
int SSMap::isset
(
const string &lvalue
);
Check is lvalue key exist in map.
rvalue - key, where to search data (IN).
RETURNS: 1 if key exist,
0 otherwise.
void SSMap::setStringList
(
const char * lvalue,
vector<string> &stringList
);
Assign string list to given lvalue.
lvalue - key, where to assign data (IN).
stringList - string's list to assign (IN).
void SSMap::getStringList
(
vector<string> &stringList,
const char * lvalue
);
Get value assigned to lvalue key and convert it to string's list.
WARNING: Stored value must be in token1;token2;token3... format.
stringList - stl vector, where to store readed list (OUT).
lvalue - key, where to search data (IN).
RETURNS: Pointer value assigned to key lvalue or
NULL if key does not exist.
| Title: | LibStr |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Process strings and binary buffers. |
| Description: | - |
| Dependences: | LibDebug LibError libstrptime |
| Used by: | Tegenaria-core qcbuild LibCGI LibSftp LibSftp-example01-sftp-client LibArgs LibProcess LibSystem LibStr-example01-binary-packet LibStr-example02-verify LibStr-example03-date LibProcess-example02-wrapper LibLock-example01-mutex LibLock-example02-semaphore |
int StrCountChar
(
const char * s,
char c
);
Count how many time given char <c> exist in string.
s - input string to scan (IN).
c - character to be counted (IN).
RETURNS: How many times char <c> exist in string <s>
int StrCountDigits
(
const char * s
);
Count how many digit character (0-9) exists in string.
s - input string to scan (IN).
RETURNS: How many digits exist in string <s>
int StrCountAlpha
(
const char * s
);
Count how many alpha (a-z and A-Z) characters exist in string.
s - input string to scan (IN).
RETURNS: How many alpha characters exist in string <s>
int StrPopInt
(
const char ** it
);
Pop integer (%d) value from string.
it - pointer source string (IN/OUT).
RETURNS: Popped integer.
double StrPopDouble
(
const char ** it
);
Pop double (%lf) value from string.
it - pointer source string (IN/OUT).
RETURNS: Popped integer.
int StrMatchChar
(
const char ** it,
char expected
);
Peek first character in string and pop it if it's match with
expected character.
NOTE #1: Character is popped only if matches with <expected> parameter.
NOTE #2: Input string <*it> is NOT changed if first character NOT matches
to <expected> parameter.
EXAMPLE 1:
----------
Before call:
*it = "jozek"
expected = 'j'
After call:
*it = "ozek"
expected = 'j'
RETURNS: 0
EXAMPLE2:
---------
Before call:
*it = "jozek"
expected = 'x'
After call:
*it = "jozek"
expected = 'x'
RETURNS: -1
it - pointer source string (IN/OUT).
expected - character to match (IN).
RETURNS: 0 if character matched and popped
-1 otherwise.
char StrPopChar
(
const char ** it
);
Pop first character from string.
it - pointer input string (IN/OUT).
RETURNS: Popped character.
void StrPopAlphaWord
(
const char ** it,
char * word,
int wordSize
);
Pop alpha (a-z and A-Z) only word from string.
Functin stops reading on first non alpha character.
it - pointer to input string (IN/OUT).
word - buffer where to store readed word (OUT).
wordSize - size of word[] buffer in bytes (IN).
void StrPopAlphaWordBound
(
const char ** it,
char * word,
int wordSize
);
Pop bound/alpha (a-z and A-Z and [] and $) only word from string.
Functin stops reading on first characer other than alpha, [] or $.
it - pointer to input string (IN/OUT).
word - buffer where to store readed word (OUT).
wordSize - size of word[] buffer in bytes (IN).
int StrPopInt
(
char ** it
);
Pop integer (%d) value from string.
it - pointer source string (IN/OUT).
RETURNS: Popped integer.
char StrPopChar
(
char ** it
);
Pop first character from string.
it - pointer input string (IN/OUT).
RETURNS: Popped character.
double StrPopDouble
(
char ** it
);
Pop double (%lf) value from string.
it - pointer source string (IN/OUT).
RETURNS: Popped integer.
int StrMatchChar
(
char ** it,
char expected
);
Peek first character in string and pop it if it's match with
expected character.
NOTE #1: Character is popped only if matches with <expected> parameter.
NOTE #2: Input string <*it> is NOT changed if first character NOT matches
to <expected> parameter.
EXAMPLE 1:
----------
Before call: After call:
*it = "jozek" *it = "ozek"
expected = 'j' expected = 'j'
Return value : 0
EXAMPLE2:
---------
Before call: After call:
*it = "jozek" *it = "jozek"
expected = 'x' expected = 'x'
Return value: -1
it - pointer source string (IN/OUT).
expected - character to match (IN).
RETURNS: 0 if character matched and popped
-1 otherwise.
void StrPopAlphaWord
(
char ** it,
char * word,
int wordSize
);
Pop alpha (a-z and A-Z) only word from string.
Functin stops reading on first non alpha character.
it - pointer to input string (IN/OUT).
word - buffer where to store readed word (OUT).
wordSize - size of word[] buffer in bytes (IN).
void StrPopAlphaWordBound
(
char ** it,
char * word,
int wordSize
);
Pop bound/alpha (a-z and A-Z and [] and $) only word from string.
Functin stops reading on first characer other than alpha, [] or $.
it - pointer to input string (IN/OUT).
word - buffer where to store readed word (OUT).
wordSize - size of word[] buffer in bytes (IN).
const char * StrSkipWhites
(
const char * s
);
Skip whites characters.
s - input string (IN).
RETURNS: Pointer to first non-white character in string.
const char * StrMatch
(
const char ** it,
const char * pattern
);
Peek begin of string and pop it if matches with input <pattern>.
Example 1:
----------
Before call: After call:
*it = "dirligo" *it = "ligo"
pattern = "dir" pattern = "dir"
Return value: "ligo"
Example 2:
----------
Before call: After call:
*it = "dirligo" *it = "dirligo"
pattern = "xxx" pattern = "xxx"
Return value: NULL
it - pointer to input string (IN/OUT).
pattern - pattern word to be matched (IN).
RETURNS: Pointer to begin of patter found in string
or NULL if pattern not found.
void StringSet
(
char * &destination,
const char * source
);
Don't be sucker! Describe your function in source code.
void StringAdd
(
char * &destination,
const char * source1,
const char * source2,
const char * source3,
const char * source4
);
Don't be sucker! Describe your function in source code.
void StringReset
(
char * &destination
);
Don't be sucker! Describe your function in source code.
void StrReplace
(
char * str,
char oldChar,
char newChar
);
Replace all occurences of character <oldChar> by <newChar>.
str - string to modify (IN/OUT).
oldChar - character to be replaced (IN).
newChar - character to use for replacement (IN).
RETURNS: Pointer to str[] parameter,
or NULL if error.
void StrReplace
(
string &str,
char oldChar,
char newChar
);
Replace all occurences of character <oldChar> by <newChar>.
str - string to modify (IN/OUT).
oldChar - character to be replaced (IN).
newChar - character to use for replacement (IN).
RETURNS: Pointer to str[] parameter,
or NULL if error.
char * StrRemoveChar
(
char * str,
char c
);
Remove all occurences of character <c> from string <str>.
str - string to modify (IN/OUT).
c - character to be removed (IN).
RETURNS: Pointer to str[] parameter,
or NULL if error.
string StrRemoveChar
(
const string &str,
char c
);
Remove all occurences of character <c> from string <str>.
str - string to modify (IN).
c - character to be removed (IN).
RETURNS: new string with removed characters.
char * StrRemoveString
(
char * buf,
const char * pattern
);
Remove all occurences of given <pattern> from string e.g.
Before call:
buf[] = "hello world hello!"
pattern[] = "hello"
After call:
buf[] = "world!"
pattern[] = "hello"
buf - buffer to change (IN/OUT).
pattern - pattern to remove (IN).
RETURNS: Pointer to buf[] parameter,
or NULL if error.
char * StrRemoveCaseString
(
char * buf,
const char * pattern
);
Remove all occurences of given <pattern> without case sensity
from string e.g.
Before call:
buf[] = "HeLLo world hello!"
pattern[] = "hello"
After call:
buf[] = "world!"
pattern[] = "hello"
buf - buffer to change (IN/OUT).
pattern - pattern to remove (IN).
RETURNS: Pointer to buf[] parameter,
or NULL if error.
string StrRemoveDeclensionPostfixPL
(
string word
);
Remove declination postfix if any.
WARNING: Function need pure ASCII text on input (i.e. with already
tarnslated polish chars to coresponding ASCII eg. ¥ to a).
Example:
Input : domy
Output: dom
Input : samochodow
Output: samochod
string & StrReplaceString
(
string &s,
const char * oldStr,
const char * newStr
);
Replace all <oldStr> occurences by <newStr> one.
s - string to modify (IN/OUT).
oldStr - pattern to be replaced (IN).
newStr - new pattern for replacement (IN).
RETURNS: Refference to input/output <s> parmatere.
int StrMaskPhone
(
char * p
);
Mask last digits in phone number by 'x' characters e.g.
Before call : 123-456-789
After call : 123-456-xxx
p - buffer where telefone number to change (IN/OUT).
RETURNS: 0 if OK,
-1 otherwise.
int StrMaskEmail
(
char * p
);
Mask email address e.g.
Before call : sucker@dirligo.com
After call : xxxxxx@xxxxxxx.xxx
p - buffer where mail to mask is stored (IN/OUT).
RETURNS: 0 if OK,
-1 otherwise.
string StrEncodeToHtml
(
const string &str,
unsigned int flags
);
Encode special chars e.g. '<' into HTML data.
str - text to encode (IN).
flags - combination of STR_HTML_XXX flags defines in Str.h (IN/OPT).
RETURNS: Text encoded to html.
string StrNormalizeWhiteSpaces
(
string s
);
Don't be sucker! Describe your function in source code.
string StrRemoveWhiteSpaces
(
const string &str
);
Remove all whitespaces from string.
int StrFormatMoney
(
char * money,
int moneySize,
const char * value
);
Format money string by adding extra space per every 3 digits.
For example it converts 5000000 into 5 000 000.
money - output buffer, where to put formatted string (OUT).
moneySize - size of money[] buffer in bytes (IN).
value - input value string to format (IN).
RETURNS: 0 if OK.
int StrPopRaw
(
void * raw,
int rawSize,
string &buf
);
Pop <rawSize> bytes from begin of string.
Buffer before: xx xx xx xx xx xx ... yy yy yy yy
Buffer after : ... yy yy yy yy
raw - buffer, where to write popped data (OUT).
rawSize - how much bytes to pop (IN).
string - buffer from pop data (IN/OUT).
RETURNS: 0 if all bytes popped,
-1 if error.
int StrPopQword
(
uint64_t * value,
string &buf,
int flags
);
Pop QWORD from begin of string.
Buffer before: 01 02 03 04 05 06 07 08 xx xx xx xx
Buffer after : xx xx xx xx
value - buffer, where to write popped QWORD (OUT).
string - buffer from pop data (IN/OUT).
flags - set to STR_BIG_ENDIAN or STR_LITTLE_ENDIAN (IN).
RETURNS: 0 if all 8 bytes popped,
-1 if error.
int StrPopDword
(
uint32_t * value,
string &buf,
int flags
);
Pop DWORD from begin of string.
Buffer before: 01 02 03 04 xx xx xx xx
Buffer after : xx xx xx xx
value - buffer, where to write popped DWORD (OUT).
string - buffer from pop data (IN/OUT).
flags - set to STR_BIG_ENDIAN or STR_LITTLE_ENDIAN (IN).
RETURNS: 0 if all 4 bytes popped,
-1 if error.
int StrPopByte
(
uint8_t * value,
string &buf
);
Pop one byte from begin of string.
Buffer before: 01 xx xx xx xx
Buffer after : xx xx xx xx
value - buffer, where to write popped byte (OUT).
string - buffer from pop data (IN/OUT).
RETURNS: 0 if byte popped,
-1 if error.
int StrPushRaw
(
string &buf,
const void * raw,
int rawSize
);
Append <rawSize> buffer to the end of string.
Buffer before: xx xx xx xx
Buffer after : xx xx xx xx yy yy yy yy yy ...
buf - buffer, where to append data (IN/OUT).
rawSize - how much bytes to append (IN).
raw - source buffer with data to append (IN).
RETURNS: 0 if all data appended,
-1 if error.
int StrPushQword
(
string &buf,
uint64_t value,
int flags
);
Append QWORD value to the end of string.
Buffer before: xx xx xx xx
Buffer after : xx xx xx xx 01 02 03 04 05 06 07 08
buf - buffer, where to append data (IN/OUT).
value - QWORD value to append (IN).
flags - set to STR_BIG_ENDIAN or STR_LITTLE_ENDIAN (IN).
RETURNS: 0 if all data appended,
-1 if error.
int StrPushDword
(
string &buf,
uint32_t value,
int flags
);
Append DWORD value to the end of string.
Buffer before: xx xx xx xx
Buffer after : xx xx xx xx 01 02 03 04
buf - buffer, where to append data (IN/OUT).
value - DWORD value to append (IN).
flags - set to STR_BIG_ENDIAN or STR_LITTLE_ENDIAN (IN).
RETURNS: 0 if all data appended,
-1 if error.
int StrPushByte
(
string &buf,
uint8_t value
);
Append one byte to the end of string.
Buffer before: xx xx xx xx
Buffer after : xx xx xx xx 01
buf - buffer, where to append data (IN/OUT).
value - byte to append (IN).
RETURNS: 0 if byte appended,
-1 if error.
int StrPushString
(
string &buf,
const char * str
);
Append string to the end of string buffer.
Buffer before: xx xx xx xx
Buffer after : xx xx xx xx ll ll ll ll ss ss ss ss ss ... 00
WHERE:
ll - little endian size of string including zero terminator
ss - string data
00 - zero terminator
buf - buffer, where to append data (IN/OUT).
str - C-style string to append (IN).
RETURNS: 0 if byte appended,
-1 if error.
inline char StrIsDelim
(
char * p,
const char * delims
);
Peek first character from input <p> string and check is it one of
allowed delimer character from <delims> set.
p - input string (IN).
delims - list of allowed delims e.g. "\t\n " (IN)
RETURNS: Delim character if detected or
0 if delim character NOT found.
void StrTokenize
(
vector<string> &tokens,
const string &inputStr,
const char * delims
);
Tokenize string.
tokens - std::vector containing generated tokens (OUT).
inputStr - string to tokenize (IN).
delims - list of delim characters e.g. "\t " (IN).
void StrTokenize
(
set<string> &tokens,
const string &inputStr,
const char * delims
);
Tokenize string.
tokens - std::set containing generated tokens (OUT).
inputStr - string to tokenize (IN).
delims - list of delim characters e.g. "\t " (IN).
void StrTokenize
(
vector<char *> &tokens,
char * inputStr,
const char * delims,
const char * delimsExtra
);
Tokenize string.
TIP #1: Set <delimsExtra> to '"' if your string containing quoted "words",
which should NOT be tokenized.
tokens - vector containing generated tokens (OUT).
inputStr - string to tokenize (IN).
delims - list of delim characters e.g. "\t " (IN).
delimsExtra - quatation characters to mark words should NOT be processed
by tokenizer (IN).
void StrTokenize
(
vector<string> &tokens,
const string &inputStr,
const char * delims,
const char * delimsExtra
);
Tokenize string.
TIP #1: Set <delimsExtra> to '"' if your string containing quoted "words",
which should NOT be tokenized.
tokens - vector containing generated tokens (OUT).
inputStr - string to tokenize (IN).
delims - list of delim characters e.g. "\t " (IN).
delimsExtra - quatation characters to mark words should NOT be processed
by tokenizer (IN).
void StrTokenize
(
set<string> &tokens,
const string &inputStr,
const char * delims,
const char * delimsExtra
);
Tokenize string.
TIP #1: Set <delimsExtra> to '"' if your string containing quoted "words",
which should NOT be tokenized.
tokens - std:set containing generated tokens (OUT).
inputStr - string to tokenize (IN).
delims - list of delim characters e.g. "\t " (IN).
delimsExtra - quatation characters to mark words should NOT be processed
by tokenizer (IN).
void StrStrTokenize
(
vector<char *> &tokens,
char * str,
const char * delim
);
Tokenize string with multiple characters delimiter.
TIP #1: Set <delimsExtra> to '"' if your string containing quoted "words",
which should NOT be tokenized.
tokens - vector containing generated tokens (OUT).
inputStr - string to tokenize (IN).
delims - multiple character delimiter e.g. "<end>" (IN).
delimsExtra - quatation characters to mark words should NOT be processed
by tokenizer (IN).
void StrStrTokenize
(
vector<string> &tokens,
const string &inputStr,
const char * delim
);
Tokenize string with multiple characters delimiter.
TIP #1: Set <delimsExtra> to '"' if your string containing quoted "words",
which should NOT be tokenized.
tokens - vector containing generated tokens (OUT).
inputStr - string to tokenize (IN).
delims - multiple character delimiter e.g. "<end>" (IN).
delimsExtra - quatation characters to mark words should NOT be processed
by tokenizer (IN).
int StrSplit
(
char * token,
char ** left,
char ** right,
char splitChar
);
Split input string into <left> and <right> parts separated by <spliChar>.
Eg. it can splits "variable=value" string into "variable" and "value" tokens.
token - input string to split. Warning input token will be destroyed (IN/OUT).
left - pointer to left token (OUT).
right - pointer to right token (first character after splitChar) (OUT).
RETURNS: 0 if <splitChar> found and string are splitteng sucessfuly,
-1 otherwise.
char * stristr
(
const char * arg1,
const char * arg2
);
Don't be sucker! Describe your function in source code.
char * StrFindIWord
(
const char * arg1,
const char * arg2
);
Don't be sucker! Describe your function in source code.
char * StrFindWord
(
const char * arg1,
const char * arg2
);
Don't be sucker! Describe your function in source code.
string StrGetTextBeetwen
(
const char * buf,
const char * startStr,
const char * endStr
);
Don't be sucker! Describe your function in source code.
char * strstrex
(
const char * s,
const char * pattern
);
Don't be sucker! Describe your function in source code.
char * strchrex
(
const char * s,
char pattern
);
Don't be sucker! Describe your function in source code.
const char * StrFindCharMulti
(
const char * p,
const char * chars,
int zeroByteMatch
);
Multi character version of strchr.
p - pointer to begin of buffer string (IN).
chars - string containing list of characters to find (IN).
zeroByteMatch - treat zero terminator as matching character if set to 1 (IN).
RETURNS: Pointer to first character matching any of chars[] character
or NULL if character not found.
inline unsigned int GetUtf8
(
unsigned const char * zIn,
unsigned const char ** pzNext
);
Pop next UTF8 character from string.
char * stristr_utf8
(
const char * arg1,
const char * arg2,
int * byteLen
);
Case insensitive UTF-8 version of C strstr().
char * StrFindIWord_utf8
(
const char * arg1,
const char * arg2
);
int StrRemovePlChars_utf8
(
unsigned char * dst,
unsigned char * src
);
Change polish local characters into pure ASCII equivalent.
dst - buffer where to store pure ASCIIZ string (OUT).
src - source utf8 string potentially containing polish chars (IN).
RETURNS: 0 if OK.
string StrCyr2Lat
(
const string &cyrtext
);
Don't be sucker! Describe your function in source code.
int StrConvertCodePage
(
string &str,
int sourceCP,
int targetCP
);
Convert code page from <sourceCP> to <targetCP>.
str - string to convert (IN/OUT).
sourceCP - original code page of input string (IN).
targetCP - destination code page, we want convert to (IN).
RETURNS: 0 if OK.
int StrRemovePlChars
(
string &str,
DWORD sourceCP
);
Replace all polish non-lating characters by lating equvalent.
str - string to convert (IN/OUT).
sourceCP - code page of input string (IN).
RETURNS: 0 if OK.
int StrPopRaw
(
void * raw,
int rawSize,
char ** it,
int * bytesLeft
);
Pop <rawSize> bytes from begin of buffer.
raw - buffer, where to write popped data (OUT).
rawSize - how much bytes to pop (IN).
it - pointer inside raw buffer, where to read data from (IN/OUT).
bytesLeft - number of bytes left in buffer (IN/OUT).
RETURNS: 0 if all bytes popped,
-1 if error.
int StrPopQword
(
uint64_t * value,
char ** it,
int * bytesLeft,
int flags
);
Pop QWORD from begin of string.
value - buffer, where to write popped QWORD (OUT).
it - pointer inside raw buffer, where to read data from (IN/OUT).
bytesLeft - number of bytes left in buffer (IN/OUT).
flags - set to STR_BIG_ENDIAN or STR_LITTLE_ENDIAN (IN).
RETURNS: 0 if all 8 bytes popped,
-1 if error.
int StrPopDword
(
uint32_t * value,
char ** it,
int * bytesLeft,
int flags
);
Pop DWORD from begin of string.
value - buffer, where to write popped DWORD (OUT).
it - pointer inside raw buffer, where to read data from (IN/OUT).
bytesLeft - number of bytes left in buffer (IN/OUT).
flags - set to STR_BIG_ENDIAN or STR_LITTLE_ENDIAN (IN).
RETURNS: 0 if all 4 bytes popped,
-1 if error.
int StrPopByte
(
uint8_t * value,
char ** it,
int * bytesLeft
);
Pop one byte from begin of string.
value - buffer, where to write popped byte (OUT).
it - pointer inside raw buffer, where to read data from (IN/OUT).
bytesLeft - number of bytes left in buffer (IN/OUT).
RETURNS: 0 if byte popped,
-1 if error.
int StrPopString
(
const char ** str,
int * strLen,
char ** it,
int * bytesLeft
);
Pop C string from buffer.
str - pointer to begin of string (OUT).
len - length of string in bytes, can be NULL if not needed (OUT/OPT).
it - pointer inside raw buffer, where to read data from (IN/OUT).
bytesLeft - number of bytes left in buffer (IN/OUT).
RETURNS: 0 if byte popped,
-1 if error.
int StringToInt
(
const string &str,
StringToIntAlgorithm algorithm
);
Convert std::string to integer.
str - input string e.g. "1234" (IN).
algorithm - algorithm to use for conversion (IN).
Possible <algorithms> are:
- SimpleAtoi : Call C atoi() function on string.
- EveryDigits : Skip all non-decimal number e.g. it converts "1-234xx-56"
into 123456 number.
- UntilAlpha : stop converting on first alpha charcter e.g. it
converts "123-456xxx789" into 123456.
RETURNS: Decoded integer.
int StringToInt
(
const char * str,
StringToIntAlgorithm algorithm
);
Convert std::string to integer.
str - input string e.g. "1234" (IN).
algorithm - algorithm to use for conversion (IN).
Possible <algorithms> are:
- SimpleAtoi : Call C atoi() function on string.
- EveryDigits : Skip all non-decimal number e.g. it converts "1-234xx-56"
into 123456 number.
- UntilAlpha : stop converting on first alpha charcter e.g. it
converts "123-456xxx789" into 123456.
RETURNS: Decoded integer.
double StringToDouble
(
const string &str
);
Convert std::string into double value.
RETURNS: Double value stored in input string.
string StringFromInt
(
int x
);
Create std::string from input integer value.
string StringFromDouble
(
double x
);
Create std::string from input double value.
void StrListSplit
(
vector<string> &vec,
const char * str
);
Split input string list in format "elem1;elem2;..." into STL vector
containig [elem1,elem2,...] strings.
vec - STL string vector, where to store retrieved elements list (OUT).
str - string list in "elem1;elem2;..." format (IN).
void StrListInit
(
string &str,
vector<string> &vec
);
Create one conitous "elem1;elem2;..." string from stl vector
containig [elem1,elem2,...].
str - STL string, where to store created list (OUT).
vec - STL vector containing string elements (IN).
int StrListAdd
(
string &str,
const char * elem
);
Add element to list.
Example:
Input str : "jozek;janek;"
Input elem : "maciek"
Output str : "jozek;janek;maciek;"
TIP#1: Element is added only if not exists on list yet.
Parameters:
str - string containing list in format "elem1;elem2;...", where to add
new element (IN/OUT).
elem - element to add (IN).
RETURNS: 0 if element added,
ERR_XXX code otherwise.
int StrListRemove
(
string &str,
const char * elem
);
Remove element from list.
Example:
Input str : "jozek;janek;maciek;"
Input elem : "janek"
Output str : "jozek;maciek;"
Parameters:
str - string containing list in format "elem1;elem2;...", which we want
to modify (IN/OUT).
elem - element to remove (IN).
RETURNS: 0 if element removed,
ERR_XXX code otherwise.
int StrListExists
(
const string &str,
const char * elem
);
Check is elem exists on list.
str - string containing list in format "elem1;elem2;...", which we want
search (IN).
elem - element to found (IN).
RETURNS: 1 if element exists in the list,
0 otherwise.
void StrCapitalize
(
string &str
);
Capitalize string.
str - string to captalize (IN/OUT).
void StrCapitalize
(
char * str
);
Capitalize string.
str - string to captalize (IN/OUT).
string & StrLowerize
(
string &s
);
Lowerize string.
s - string to captalize (IN/OUT).
void StrLowerize
(
char * s
);
Lowerize string.
s - string to captalize (IN/OUT).
int StrEmailVerify
(
const char * email
);
Check is given email is in correct X@Y format.
email - email address to verify (IN).
RETURNS: 0 if email seems correct,
one of ERR_VERIFY_XXX code otherwise.
int StrLoginVerify
(
const char * login
);
Check is given login correct.
Allowed chars are: A-Z a-z 0-9 -_@.
(No space allowed, dot allowed).
Minimum login length is STR_MIN_LOGIN_LEN.
Maximum login length is STR_MAX_LOGIN_LEN.
login - login to verify (IN).
RETURNS: 0 if login seems correct,
one of ERR_VERIFY_XXX code otherwise.
int StrPassVerify
(
const char * pass
);
Minimum login length is STR_MIN_PASS_LEN.
Maximum login length is STR_MAX_PASS_LEN.
pass - password to verify (IN).
RETURNS: 0 if password seems correct,
one of ERR_VERIFY_XXX code otherwise.
int StrPassStrength
(
const char * pass
);
Compute password strength in <0;6> scale.
pass - password to check (IN).
RETURNS: Password strength in <0;6> scale.
const string StrDateGetToday
(
);
Get local today date string in format: YYYY-MM-DD.
RETURNS: String containing today date e.g. "2014-10-14".
const string StrDateGetTodayUTC0
(
);
Get UTC0 today date string in format: YYYY-MM-DD.
RETURNS: String containing today date e.g. "2014-10-14".
const string StrDateAddDays
(
string date,
int nDays
);
Add N days to date string.
Example: "2014-10-14" + 1 day = "2014-10-15"
date - input date string to increase (IN).
nDays - how many days to add (IN).
RETURNS: Date string increased by given number of days.
const string StrDateAddDaysUTC0
(
string date,
int nDays
);
Add N days to UTC0 date string.
Example: "2014-10-14" + 1 day = "2014-10-15"
date - input date string to increase (IN).
nDays - how many days to add (IN).
RETURNS: Date string increased by given number of days.
string StrMinifyCode
(
const string &code,
const char * singleComment,
const char * multiCommentBegin,
const char * multiCommentEnd,
int removeWhites
);
Minimalize source code (e.g. JS/CSS) by removing whitespaces and comments.
code - source code to minify (IN).
singleComment - string used as comment line e.g. '//' in C/C++ (IN/OPT).
multiCommentBegin - string used to begin comment e.g. '/*' in C/C++ (IN/OPT).
multiCommentEnd - string used to close comment e.g. '*/' in C/C++ (IN/OPT).
removeWhites - remove redundant whites if set to 1 (IN/OPT).
RETURNS: New string containing minimalized code.
string StrRemoveSingleLineComments
(
string code,
const char * commentString
);
Remove single line comments from string.
code - string containg source code (IN).
commentString - string used as comment line e.g. '//' in C/C++ (IN).
RETURNS: New string with removed comments.
string StrRemoveMultiLineComments
(
const string &code,
const char * commentBegin,
const char * commentEnd
);
Remove multiline comments from string.
code - string containg source code (IN).
commentBegin - string used to begin comment e.g. '/*' in C/C++ (IN).
commentEnd - string used to close comment e.g. '*/' in C/C++ (IN).
RETURNS: New string with removed comments.
string RandomIntString
(
);
Generate random 64-byte decimal only string.
RETURNS: Random decimal-only string.
string RandomString
(
int len,
int minChar,
int maxChar
);
Generate general random string.
len - length of string to generate (IN).
minChar - minimum character to use e.g. 'a' (IN).
maxChar - maximum character to use e.g. 'z' (IN).
RETURNS: Random string containing characters from <minChar, maxChar>
range.
| Title: | LibSystem |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Platform independend API to retrieve info about system and OS. |
| Description: | - |
| Dependences: | LibStr LibDebug |
| Used by: | Tegenaria-core LibSystem-example01-simple |
int SystemGetCpuCores
(
);
Retrieve number of CPU cores installed on system.
void SystemCpuId
(
unsigned int func,
unsigned int * eax,
unsigned int * ebx,
unsigned int * ecx,
unsigned int * edx
);
Run native cpuid instruction.
func - CPU id function, see INTEL or AMD manual for more (IN).
eax - copy of returned eax register (OUT).
ebx - copy of returned ebx register (OUT).
ecx - copy of returned ecx register (OUT).
edx - copy of returned edx register (OUT).
int SystemCpuHasSSE3
(
);
Check does current running CPU has SSE3 extension.
int SystemCpuHasSSE2
(
);
Check does current running CPU has SSE2 extension.
int SystemCpuHasMMX
(
);
Check does current running CPU has MMX extension.
const char * SystemGetOsName
(
);
Retrieve name of current running OS (e.g. Windows).
const char * SystemGetOsVersionString
(
);
Get version string of current running OS (e.g. XP 5.1.2600).
int SystemGetMachineName
(
char * machineName,
int machineNameSize
);
Get name of current running machine.
machineName - buffer, where to store retrieved machine name (OUT).
machineNameSize - size of machineName[] buffer in bytes (IN).
RETURNS: 0 if OK.
int SystemGenerateClientId
(
char * clientId,
int clientIdSize
);
Generate unique string identyfing current running machine.
Output string has format:
X:<machine-name>:<random-id>,
where:
- X is 'W' for Windows, 'L' for Linux, 'M' for MacOS,
'A' for Android, 'i' for iOS, 'U' for unknown.
- machineName is name of current machine retreved from
SystemGetMachineName()
- random-id is random 4 characters
Example: W:Office-12345678:fsd2
clientId - buffer, where to store generated client ID (OUT).
clientIdSize - size of clientId[] buffer in bytes (IN).
RETURNS: 0 if OK.
int SystemParseClientId
(
string &os,
string &machineName,
string &id,
const char * clientId
);
Split client ID into OS (operating system), machine name and ID part.
See SystemGenerateClientId() for more about client ID.
os - OS part found in given client ID (OUT).
machineName - machine name found in given client ID (OUT).
id - random ID part found in given client ID (OUT).
clientId - client ID to parse, generated by SystemGenerateClientId() before (IN).
RETURNS: 0 if OK,
-1 if error.
int64_t SystemGetFreeMemory
(
);
Retrieve number of free bytes available in system.
int64_t SystemGetUsedMemory
(
);
Retrieve numer of bytes allocated by current running process.
int SystemGetFdLimit
(
);
Retrieve current limit of allowed opened FD for current user.
RETURNS: Current set FD limit
or -1 if error.
int SystemSetFdLimit
(
int limit
);
Set limit of maximum opened FD for current user.
limit - new limit to set (IN).
RETURNS: 0 if OK.
int SystemCheckForAdmin
(
);
Check does current process has admin privilege.
RETURNS: 0 if current process has admin privilege,
1 if current process has NO admin privilege,
-1 if error.
int SystemGetCurrentUser
(
char * user,
int userSize
);
Retrieve name of current running user.
user - buffer, where to store retrieved username (OUT).
userSize - size of user[] buffer in bytes (IN).
RETURNS: 0 if OK.
int SystemGetEnvironmentBlock
(
map<string ,
string> &env
);
Retrieve all environment variables as string |-> string map.
env - std string to string map, where to store retrieved
environment block (OUT).
RETURNS: 0 if OK.
| Title: | LibThread |
| Type: | LIBRARY |
| Author(s): | Radoslaw Kolodziejczyk (radek.kolodziejczyk@gmail.com), Lukasz Bienczyk (lukasz.bienczyk@gmail.com) |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Creating threads |
| Description: | - |
| Dependences: | LibDebug |
| Used by: | Tegenaria-core LibNet LibNetEx LibSftp LibNet-example01-thread-server LibNet-example02-single LibNet-example05-HP-server LibIO LibIpc LibJob LibProcess LibThread-example01-simple LibThread-example02-wait LibProcess-example03-monitor LibProcess-example04-wait-for-parent LibLock-example01-mutex LibLock-example02-semaphore liblock-example03-requestpool LibIO-example01-file-mixer LibIO-example02-network-mixer LibIO-example03-timeout-read |
static ThreadHandle_t * _ThreadHandleAlloc
(
void * handle,
int id
);
Allocate new ProcessHandle_t struct basing on system handle/pid data.
handle - underlying system handle (IN).
id - underlying thread id (IN).
RETURNS: Pointer to new allocated handle,
or NULL if error.
static void * _ThreadEntryWrapperLinux
(
void * rawCtx
);
Internal wrapper over caller entry point to:
- hide OS differences (entry point on Linux has different proto)
- get signal, when thread finished in easy way
ThreadHandle_t * ThreadCreate
(
ThreadEntryProto entry,
void * ctx
);
Create new thread.
entry - thread entry point i.e. pointer to function, where code execution
will be started (MUST be static) (IN).
ctx - arbitrary data passed directly to the thread entry point. Can
be NULL if not needed (IN/OPT).
RETURNS: handle to new thread,
or NULL if error.
int ThreadIsRunning
(
ThreadHandle_t * th
);
Check is thread running.
handle - thread handle returned by threadCreate() before (IN).
RETURN: 1 if thread running,
0 if thread dead,
-1 if error.
int ThreadClose
(
ThreadHandle_t * th
);
Close handle retrieved from ThreadCreate() before.
WARNING: Function does NOT terminate thread if it still running.
TIP#1: Use ThreadKill() if you want to terminate thread before close.
TIP#2: Use ThreadWait() if you want to wait until thread finished before close.
th - handle to thread retrieved from ThreadCreate() before (IN).
RETURNS: 0 if thread finished before timeout,
-1 if thread still working.
int ThreadKill
(
ThreadHandle_t * th
);
Unconditionaly terminate thread.
th - thread handle retrieved from ThreadCrate() before (IN).
RETURNS: 0 if thread terminated,
-1 otherwise.
int ThreadWait
(
ThreadHandle_t * th,
int * result,
int timeoutMs
);
Wait until thread finished work or timeout.
WARNING: Function DOES not clear resources allocated by thread event
if thread terminated before funtion return. Use ThreadClose()
to free thread handle, when no needed longer.
th - thread handle retrieved from ThreadCreate() before (IN).
result - buffer, where to store exit code returned by thread.
Can be NULL if not needed (OUT/OPT).
timeout - maximum time to wait im milisecond. Defaulted to infinite if
skipped or set to -1. (IN/OPT).
RETURNS: 0 if thread finished before timeout,
1 if thread still working,
-1 if error.
int ThreadGetCurrentId
(
);
Get id of current running thread.
void ThreadSleepUs
(
int us
);
Sleep current thread for given number of microseconds.
void ThreadSleepMs
(
int ms
);
Sleep current thread for given number of miliseconds.
void ThreadSleepSec
(
double seconds
);
Sleep current thread for given number of seconds.
| Title: | LibVariant |
| Type: | LIBRARY |
| Author(s): | Sylwester Wysocki |
| Copyright: | (C) Sylwester Wysocki 2010, 2014 (inherited from project's root) |
| License: | MIT (See LICENSE.txt file) (inherited from project's root) |
| Purpose: | Variant (mutable) variables |
| Description: | - |
| Dependences: | LibDebug LibObject |
| Used by: | Tegenaria-core |
Variant::printAsText
(
FILE * f,
unsigned int flags
);
Don't be sucker! Describe your function in source code.
const char * Variant::getTypeName
(
);
Don't be sucker! Describe your function in source code.
int Variant::vaprint
(
FILE * f,
unsigned int flags,
int count
);
Don't be sucker! Describe your function in source code.
const string Variant::toStdString
(
);
Don't be sucker! Describe your function in source code.
const Variant Variant::toString
(
);
Don't be sucker! Describe your function in source code.
const Variant Variant::toStringEscapedForC
(
);
Don't be sucker! Describe your function in source code.