1: /*************************************************************************
2: * (C) 2010 AITNET ltd - Sofia/Bulgaria - <misho@aitnet.org>
3: * by Michael Pounov <misho@elwix.org>
4: *
5: * $Author: misho $
6: * $Id: aitio.h,v 1.16.2.7 2012/04/05 11:11:48 misho Exp $
7: *
8: **************************************************************************
9: The ELWIX and AITNET software is distributed under the following
10: terms:
11:
12: All of the documentation and software included in the ELWIX and AITNET
13: Releases is copyrighted by ELWIX - Sofia/Bulgaria <info@elwix.org>
14:
15: Copyright 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
16: by Michael Pounov <misho@elwix.org>. All rights reserved.
17:
18: Redistribution and use in source and binary forms, with or without
19: modification, are permitted provided that the following conditions
20: are met:
21: 1. Redistributions of source code must retain the above copyright
22: notice, this list of conditions and the following disclaimer.
23: 2. Redistributions in binary form must reproduce the above copyright
24: notice, this list of conditions and the following disclaimer in the
25: documentation and/or other materials provided with the distribution.
26: 3. All advertising materials mentioning features or use of this software
27: must display the following acknowledgement:
28: This product includes software developed by Michael Pounov <misho@elwix.org>
29: ELWIX - Embedded LightWeight unIX and its contributors.
30: 4. Neither the name of AITNET nor the names of its contributors
31: may be used to endorse or promote products derived from this software
32: without specific prior written permission.
33:
34: THIS SOFTWARE IS PROVIDED BY AITNET AND CONTRIBUTORS ``AS IS'' AND
35: ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
36: IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37: ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
38: FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
39: DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
40: OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
41: HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
42: LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
43: OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44: SUCH DAMAGE.
45: */
46: #ifndef __AITIO_H
47: #define __AITIO_H
48:
49:
50: #define COMPAT_43TTY
51:
52: #include <assert.h>
53: #include <openssl/evp.h>
54: #include <openssl/aes.h>
55: #include <sys/tty.h>
56: #include <sys/ioctl_compat.h>
57: #include <sys/socket.h>
58: #include <sys/un.h>
59: #include <net/if_dl.h>
60: #include <netinet/in.h>
61:
62:
63: #define VACUUM_LEFT 1
64: #define VACUUM_BETWEEN 2
65:
66: /* AIT arrays */
67:
68: typedef void ** sarr_seg_t;
69: typedef struct _tagSplitArray {
70: int sarr_num;
71: int sarr_seg;
72: int sarr_siz;
73: sarr_seg_t *sarr_data;
74: } sarr_t;
75:
76: typedef struct _tagArray {
77: int arr_num;
78: void **arr_data;
79: } array_t;
80:
81: /* AIT RPC variables and managment */
82:
83: typedef enum {
84: empty, ptr, data, /* empty -> variable is not set; ptr -> void*; data -> data after struct */
85: buffer, string, blob, /* buffer -> uint8_t*; string -> int8_t*; blob -> uint32_t blobID(+socket); */
86: f32, f64, /* float -> f32; double -> f64 */
87: u8, u16, u32, u64, /* unsigned integers ... */
88: i8, i16, i32, i64, /* integers ... */
89: } ait_type_t;
90:
91: typedef struct {
92: uint8_t val_type;
93: uint8_t val_pad;
94: uint16_t val_key;
95: uint32_t val_len;
96: union {
97: uint64_t net;
98:
99: void *ptr;
100: uint8_t *buffer;
101: int8_t *string;
102: uint32_t blob;
103: float f32;
104: double f64;
105: uint8_t u8;
106: uint16_t u16;
107: uint32_t u32;
108: uint64_t u64;
109: int8_t i8;
110: int16_t i16;
111: int32_t i32;
112: int64_t i64;
113: } val;
114: uint8_t val_data[0];
115: } __packed ait_val_t;
116:
117: #define AIT_TYPE(_vl) ((ait_type_t) (_vl)->val_type)
118: #define AIT_LEN(_vl) (_vl)->val_len
119: #define AIT_KEY(_vl) (_vl)->val_key
120: #define AIT_RAW(_vl) (_vl)->val.net
121: #define AIT_VOID(_vl) (_vl)->val.ptr
122: #define AIT_BLOB_CHUNKS(_vl, _n) (AIT_LEN((_vl)) / _n + (AIT_LEN((_vl)) % _n) ? 1 : 0)
123: #define AIT_ISEMPTY(_vl) (AIT_TYPE((_vl)) == empty)
124:
125: #define AIT_GET_LIKE(_vl, _type) ((_type) (_vl)->val.ptr)
126:
127: #define AIT_GET_PTR(_vl) (assert(AIT_TYPE((_vl)) == ptr), (_vl)->val.ptr)
128: #define AIT_GET_DATA(_vl) (assert(AIT_TYPE((_vl)) == data), (_vl)->val_data)
129: #define AIT_GET_BUF(_vl) (assert(AIT_TYPE((_vl)) == buffer), (_vl)->val.buffer)
130: #define AIT_GET_STR(_vl) (assert(AIT_TYPE((_vl)) == string), (char*) (_vl)->val.string)
131: #define AIT_GET_BLOB(_vl) (assert(AIT_TYPE((_vl)) == blob), (_vl)->val.blob)
132: #define AIT_GET_U8(_vl) (assert(AIT_TYPE((_vl)) == u8), (_vl)->val.u8)
133: #define AIT_GET_U16(_vl) (assert(AIT_TYPE((_vl)) == u16), (_vl)->val.u16)
134: #define AIT_GET_U32(_vl) (assert(AIT_TYPE((_vl)) == u32), (_vl)->val.u32)
135: #define AIT_GET_U64(_vl) (assert(AIT_TYPE((_vl)) == u64), (_vl)->val.u64)
136: #define AIT_GET_I8(_vl) (assert(AIT_TYPE((_vl)) == i8), (_vl)->val.i8)
137: #define AIT_GET_I16(_vl) (assert(AIT_TYPE((_vl)) == i16), (_vl)->val.i16)
138: #define AIT_GET_I32(_vl) (assert(AIT_TYPE((_vl)) == i32), (_vl)->val.i32)
139: #define AIT_GET_I64(_vl) (assert(AIT_TYPE((_vl)) == i64), (_vl)->val.i64)
140: #define AIT_GET_F32(_vl) (assert(AIT_TYPE((_vl)) == f32), (_vl)->val.f32)
141: #define AIT_GET_F64(_vl) (assert(AIT_TYPE((_vl)) == f64), (_vl)->val.f64)
142:
143: #define AIT_SET_DATA(_vl, _p, _len) do { ait_val_t *__val = (_vl); \
144: __val = realloc(__val, sizeof(ait_val_t) + _len); \
145: if (__val) { \
146: __val->val_type = data; AIT_LEN(__val) = _len; \
147: if ((_p)) \
148: memcpy(__val->val_data, (_p), _len); \
149: } \
150: (_vl) = __val; \
151: } while (0);
152: #define AIT_SET_PTR(_vl, _p, _len) do { ait_val_t *__val = (_vl); assert(__val); \
153: __val->val_type = ptr; AIT_LEN(__val) = _len; \
154: __val->val.ptr = _p; } while (0)
155: #define AIT_SET_BUF(_vl, _v, _len) do { ait_val_t *__val = (_vl); assert(__val); \
156: __val->val.buffer = malloc(_len); \
157: if (__val->val.buffer) { \
158: __val->val_type = buffer; AIT_LEN(__val) = _len; \
159: memcpy(__val->val.buffer, (_v), _len); \
160: } } while (0)
161: #define AIT_SET_STR(_vl, _v) do { ait_val_t *__val = (_vl); assert(__val); \
162: __val->val.string = (int8_t*) strdup((_v)); \
163: if (__val->val.string) { \
164: __val->val_type = string; \
165: AIT_LEN(__val) = strlen((_v)) + 1; \
166: } } while (0)
167: #define AIT_SET_STRCAT(_vl, _v) do { ait_val_t *__val = (_vl); assert(__val); \
168: assert(AIT_TYPE(__val) == string); \
169: void *__p = realloc(__val->val.string, \
170: AIT_LEN(__val) + strlen((_v))); \
171: if (__p) { \
172: __val->val.string = __p; \
173: AIT_LEN(__val) += strlen((_v)); \
174: strlcat((char*) __val->val.string, (_v), \
175: AIT_LEN(__val)); \
176: } } while (0)
177: #define AIT_SET_BLOB(_vl, _n, _len) do { ait_val_t *__val = (_vl); assert(__val); \
178: __val->val_type = blob; AIT_LEN(__val) = _len; \
179: __val->val.blob = _n; } while (0)
180: #define AIT_SET_BLOB2(_vl, _bv) do { ait_val_t *__val = (_vl); assert(__val); assert((_bv)); \
181: __val->val_type = blob; AIT_LEN(__val) = (_bv)->blob_len; \
182: __val->val.blob = (_bv)->blob_var; } while (0)
183: #define AIT_NEW_BLOB(_vl, _len) AIT_SET_BLOB((_vl), 0, _len)
184:
185: #define AIT_SET_U8(_vl, _n) do { ait_val_t *__val = (_vl); assert(__val); \
186: __val->val_type = u8; __val->val.u8 = _n; \
187: AIT_LEN(__val) = sizeof(uint8_t); } while (0)
188: #define AIT_SET_U16(_vl, _n) do { ait_val_t *__val = (_vl); assert(__val); \
189: __val->val_type = u16; __val->val.u16 = _n; \
190: AIT_LEN(__val) = sizeof(uint16_t); } while (0)
191: #define AIT_SET_U32(_vl, _n) do { ait_val_t *__val = (_vl); assert(__val); \
192: __val->val_type = u32; __val->val.u32 = _n; \
193: AIT_LEN(__val) = sizeof(uint32_t); } while (0)
194: #define AIT_SET_U64(_vl, _n) do { ait_val_t *__val = (_vl); assert(__val); \
195: __val->val_type = u64; __val->val.u64 = _n; \
196: AIT_LEN(__val) = sizeof(uint64_t); } while (0)
197: #define AIT_SET_I8(_vl, _n) do { ait_val_t *__val = (_vl); assert(__val); \
198: __val->val_type = i8; __val->val.i8 = _n; \
199: AIT_LEN(__val) = sizeof(int8_t); } while (0)
200: #define AIT_SET_I16(_vl, _n) do { ait_val_t *__val = (_vl); assert(__val); \
201: __val->val_type = i16; __val->val.i16 = _n; \
202: AIT_LEN(__val) = sizeof(int16_t); } while (0)
203: #define AIT_SET_I32(_vl, _n) do { ait_val_t *__val = (_vl); assert(__val); \
204: __val->val_type = i32; __val->val.i32 = _n; \
205: AIT_LEN(__val) = sizeof(int32_t); } while (0)
206: #define AIT_SET_I64(_vl, _n) do { ait_val_t *__val = (_vl); assert(__val); \
207: __val->val_type = i64; __val->val.i64 = _n; \
208: AIT_LEN(__val) = sizeof(int64_t); } while (0)
209: #define AIT_SET_F32(_vl, _n) do { ait_val_t *__val = (_vl); assert(__val); \
210: __val->val_type = f32; __val->val.f32 = _n; \
211: AIT_LEN(__val) = sizeof(float); } while (0)
212: #define AIT_SET_F64(_vl, _n) do { ait_val_t *__val = (_vl); assert(__val); \
213: __val->val_type = f64; __val->val.f64 = _n; \
214: AIT_LEN(__val) = sizeof(double); } while (0)
215:
216: /* if attribute zeroCopy is set not execute free() */
217: #define AIT_FREE_VAL(_vl) do { ait_val_t *__val = (_vl); assert(__val); \
218: switch (AIT_TYPE(__val)) { \
219: case buffer: \
220: if (__val->val.buffer) { \
221: free(__val->val.buffer); \
222: __val->val.buffer = NULL; \
223: } \
224: break; \
225: case string: \
226: if (__val->val.string) { \
227: free(__val->val.string); \
228: __val->val.string = NULL; \
229: } \
230: break; \
231: default: \
232: break; \
233: } \
234: __val->val_type = empty; \
235: AIT_LEN(__val) = 0; \
236: } while (0)
237:
238: struct io_ether_addr {
239: u_int8_t ether_addr_octet[6];
240: };
241: typedef struct io_ether_addr io_ether_addr_t;
242:
243: typedef union {
244: struct sockaddr_storage ss;
245: struct sockaddr sa;
246: struct sockaddr_un sun;
247: struct sockaddr_in sin;
248: struct sockaddr_in6 sin6;
249: struct sockaddr_dl sdl;
250: } io_sockaddr_t;
251:
252:
253: #define io_align(x, a) (((x) + (a)) & ~(a))
254:
255:
256: // io_GetErrno() Get error code of last operation
257: inline int io_GetErrno();
258: // io_GetError() Get error text of last operation
259: inline const char *io_GetError();
260:
261:
262: /*
263: * io_ether_ntoa() - Convert ethernet address to string
264: *
265: * @n = ethernet address structure, like struct ether_addr
266: * @a = string
267: * @len = string length
268: * return: NULL error or !=NULL string a
269: */
270: inline char *io_ether_ntoa(const struct io_ether_addr *n, char * __restrict a, int len);
271: /*
272: * io_ether_aton() - Convert string to ethernet address
273: *
274: * @a = string
275: * @e = ethernet address structure, like struct ether_addr
276: * return: NULL error or !=NULL ethernet address structure
277: */
278: inline struct io_ether_addr *io_ether_aton(const char *a, struct io_ether_addr *e);
279: /*
280: * io_n2port() - Extract port from network structure
281: *
282: * @addr = Address
283: * return: 0 not supported family type or port number
284: */
285: inline u_short io_n2port(io_sockaddr_t * __restrict addr);
286: /*
287: * io_n2addr() - Extract address from network structure
288: *
289: * @addr = Address
290: * @val = Value for store string address
291: * return: NULL error or !=NULL string address from val
292: */
293: const char *io_n2addr(io_sockaddr_t * __restrict addr, ait_val_t * __restrict val);
294: /*
295: * io_gethostbyname() - Get host and port and make network structure
296: *
297: * @psHost = Hostname
298: * @port = Port
299: * @addr = Network address structure
300: * return: NULL error or !=NULL network structure
301: */
302: io_sockaddr_t *io_gethostbyname(const char *psHost, unsigned short port,
303: io_sockaddr_t * __restrict addr);
304:
305: /*
306: * io_vars2buffer() - Marshaling data from array with variables to buffer
307: *
308: * @buf = Buffer
309: * @buflen = Size of buffer
310: * @vars = Variable array
311: * return: -1 error, 0 nothing done or >0 size of marshaled data
312: */
313: int io_vars2buffer(unsigned char *buf, int buflen, array_t *vars);
314: /*
315: * io_buffer2vars() - De-marshaling data from buffer to array with variables
316: *
317: * @buf = Buffer
318: * @buflen = Size of buffer
319: * @vnum = Number of variables into buffer
320: * @zcpy = Zero-copy for variables, if !=0 don't use io_arrayFree() for free variables and
321: *DON'T MODIFY OR DESTROY BUFFER*. =0 call io_arrayFree() before io_arrayDestroy()
322: * return: =NULL error, !=NULL allocated variable array, after use must free with io_arrayDestroy()
323: */
324: array_t *io_buffer2vars(unsigned char *buf, int buflen, int vnum, int zcpy);
325: /*
326: * io_vars2map() - Marshaling data from array with variables to memory map
327: *
328: * @buf = Buffer
329: * @buflen = Size of buffer
330: * @vars = Variable array
331: * return: -1 error, 0 nothing done or >0 size of marshaled data
332: */
333: int io_vars2map(unsigned char *buf, int buflen, array_t *vars);
334: /*
335: * io_map2vars() - De-marshaling data from memory map to array with variables
336: *
337: * @buf = Buffer
338: * @buflen = Size of buffer
339: * @vnum = Number of variables into buffer
340: * @zcpy = Zero-copy for variables, if !=0 don't use io_arrayFree() for free variables and
341: *DON'T MODIFY OR DESTROY BUFFER*. =0 call io_arrayFree() before io_arrayDestroy()
342: * return: =NULL error, !=NULL allocated variable array, after use must free with io_arrayDestroy()
343: */
344: array_t *io_map2vars(unsigned char *buf, int buflen, int vnum, int zcpy);
345:
346: /*
347: * io_allocVar() - Allocate memory for variable
348: *
349: * return: NULL error or new variable, after use free variable with io_freeVar()
350: */
351: inline ait_val_t *io_allocVar(void);
352: /*
353: * io_freeVar() - Free allocated memory for variable
354: *
355: * @val = Variable
356: * return: none
357: */
358: inline void io_freeVar(ait_val_t * __restrict val);
359: /*
360: * io_allocVars() - Allocate ait_val_t array
361: *
362: * @varnum = Number of variables
363: * return: =NULL error or !=NULL allocated array
364: */
365: inline array_t *io_allocVars(int varnum);
366: /*
367: * io_clrVars() - Clear ait_val_t elements from array
368: *
369: * @vars = Variable array
370: * return: -1 error or size of array
371: */
372: inline int io_clrVars(array_t * __restrict vars);
373: /*
374: * io_freeVars() - Free ait_val_t array
375: *
376: * @vars = Variable array
377: * return: none
378: */
379: inline void io_freeVars(array_t ** __restrict vars);
380: /*
381: * io_sortVars() - Sorting array with variables
382: *
383: * @vars = Variable array
384: * @order = Sort order. If =0 ascend ot !=0 descend
385: * @cmp = Compare function for sorting. If =NULL compare by key
386: * return: none
387: */
388: inline void io_sortVars(array_t * __restrict vars, int order,
389: int (*cmp)(const void*, const void*));
390: /*
391: * io_findKeyVars() - Find variable by key from array
392: *
393: * @vars = Variables
394: * @key = Search key
395: * return: NULL error or not found, !=NULL valid element
396: */
397: ait_val_t *io_findKeyVars(array_t * __restrict vars, u_short key);
398:
399:
400: /*
401: * ioPromptRead() - Read data from input h[0] with prompt to output h[1]
402: *
403: * @h = file handles h[0] = input, h[1] = output, if NULL use stdin, stdout
404: * @csPrompt = Prompt before input, may be NULL
405: * @psData = Readed data
406: * @dataLen = Length of data
407: * return: 0 EOF; -1 error:: can`t read; >0 count of readed chars
408: */
409: int ioPromptRead(int *h, const char *csPrompt, char * __restrict psData, int dataLen);
410: /*
411: * ioPromptPassword() - Read password from input h[0] with prompt to output h[1]
412: *
413: * @h = file handles h[0] = input, h[1] = output, if NULL use stdin, stdout
414: * @csPrompt = Prompt before input, may be NULL
415: * @psPass = Readed password
416: * @passLen = Length of password
417: * @confirm = Confirm password, 0 - get password, !=0 Ask for confirmation
418: * return: 0 EOF; -1 error:: can`t read; >0 count of readed chars
419: */
420: int ioPromptPassword(int *h, const char *csPrompt, char * __restrict psPass, int passLen, int confirm);
421:
422: /*
423: * ioRegexVerify() - Function for verify data match in regex expression
424: *
425: * @csRegex = Regulare expression pattern
426: * @csData = Data for check and verify
427: * @startPos = Return start positions
428: * @endPos = Return end positions
429: * return: NULL not match or error; !=NULL begin of matched data
430: */
431: const char *ioRegexVerify(const char *csRegex, const char *csData, int *startPos, int *endPos);
432: /*
433: * ioRegexGet() - Function for get data match in regex expression
434: *
435: * @csRegex = Regulare expression pattern
436: * @csData = Data from get
437: * @psString = Returned string if match
438: * @strLen = Length of string
439: * return: 0 not match; >0 count of returned chars
440: */
441: int ioRegexGet(const char *csRegex, const char *csData, char * __restrict psString, int strLen);
442: /*
443: * ioRegexReplace() - Function for replace data match in regex expression with newdata
444: *
445: * @csRegex = Regulare expression pattern
446: * @csData = Source data
447: * @csNew = Data for replace
448: * return: NULL not match or error; !=NULL allocated new string, must be free after use!
449: */
450: char *ioRegexReplace(const char *csRegex, const char *csData, const char *csNew);
451:
452: /*
453: * ioStrAst() - Function for evaluate string like asterisk variable "{text[:[-]#[:#]]}"
454: *
455: * @csString = Input string
456: * return: NULL error, !=NULL Allocated new string evaluated from input string, must be free()
457: */
458: char *ioStrAst(const char *csString);
459:
460: /*
461: * io_UnquotStr() - Remove quots from input text string
462: *
463: * @psLine = Text string
464: * return: 0 nothing to do; 1 successful unquoted string
465: */
466: inline int io_UnquotStr(char * __restrict psLine);
467: /*
468: * io_LTrimStr() - Remove left whitespaces from text string
469: *
470: * @psLine = Text string
471: * return: 0 nothing to do; !=0 Removed bytes
472: */
473: inline int io_LTrimStr(char * __restrict psLine);
474: /*
475: * io_RTrimStr() - Remove right whitespaces from text string
476: *
477: * @psLine = Text string
478: * return: 0 nothing to do; !=0 Removed bytes
479: */
480: inline int io_RTrimStr(char * __restrict psLine);
481: /*
482: * io_TrimStr() - Remove left and right whitespaces from text string
483: *
484: * @psLine = Text string
485: * return: 0 nothing to do; !=0 Removed bytes
486: */
487: inline int io_TrimStr(char * __restrict psLine);
488: /*
489: * io_Ch2Hex() - Convert from Char string to Hex string
490: *
491: * @psLine = Text string
492: * @lineLen = Length of Text string
493: * return: NULL nothing to do or error; !=0 Allocated new converted data without term\0 (must be free)
494: */
495: inline unsigned char *io_Ch2Hex(unsigned char *psLine, int lineLen);
496: /*
497: * io_Hex2Ch() - Convert from Hex string to Char string
498: *
499: * @psLine = Text string
500: * @lineLen = Length of Text string
501: * return: NULL nothing to do or error; !=0 Allocated new converted string(must be free)
502: */
503: inline char *io_Hex2Ch(unsigned char *psLine, int lineLen);
504:
505: /*
506: * io_Path2File() - Parse and make path/filename pair
507: *
508: * @csArgs = Input argument line
509: * @psPath = Output Path, if ==NULL path not returned
510: * @pathLen = Size of path array
511: * @psFile = Output File
512: * @fileLen = Size of file array
513: * return: 0 error format; -1 error:: can`t read; >0 ok, number of readed items
514: */
515: inline int
516: io_Path2File(const char * __restrict csArgs, char * __restrict psPath,
517: int pathLen, char * __restrict psFile, int fileLen);
518:
519: /*
520: * io_arrayInit() - Create and initialize dynamic array
521: *
522: * @numItems = Number of Items
523: * return: NULL error, != NULL allocated memory for array
524: */
525: inline array_t *io_arrayInit(int numItems);
526: /*
527: * io_arrayDestroy() - Free and destroy dynamic array
528: *
529: * @parr = Array
530: * return: none
531: */
532: inline void io_arrayDestroy(array_t ** __restrict parr);
533: /*
534: * io_arrayFree() - Free all data in dynamic array items
535: * (WARNING! If assign static array dont use this!!!)
536: *
537: * @arr = Array
538: * return: none
539: */
540: inline void io_arrayFree(array_t * __restrict arr);
541: /*
542: * io_arrayFrom() - Create and fill array from array with pointers
543: *
544: * @pargv = Array with pointers
545: * @argc = Number of Items, if 0 walk through argv and stop when reach NULL item
546: * return: NULL error, != NULL allocated new array
547: */
548: inline array_t *io_arrayFrom(const char *** __restrict pargv, int argc);
549: /*
550: * io_arrayTo() - Create and fill array with pointers from dynamic array
551: *
552: * @arr = Array
553: * return: NULL error, != NULL allocated memory for array, NULL terminated
554: */
555: inline char **io_arrayTo(array_t * __restrict arr);
556: /*
557: * io_arrayLen() - Get last used element in dynamic array (array Length)
558: *
559: * @arr = Array
560: * return: -1 error, 0 empty or >0 position of last used element
561: */
562: inline int io_arrayLen(array_t * __restrict arr);
563: /*
564: * io_arrayConcat() Concat source array to destination array
565: *
566: * @dest = Destination array
567: * @src = Source array
568: * return: -1 error; >0 new count of destination array
569: */
570: int io_arrayConcat(array_t * __restrict dest, array_t * __restrict src);
571: /*
572: * io_arrayCopy() Copy source array to destination array
573: *
574: * @dest = Destination array, after use free with io_arrayDestroy()
575: * @src = Source array
576: * return: -1 error; >0 count of destination array
577: */
578: int io_arrayCopy(array_t ** __restrict dest, array_t * __restrict src);
579: /*
580: * io_arrayGrow() - Grow/Shrink dynamic array, Use with care when it shrink!!!
581: *
582: * @arr = Array
583: * @newNumItems = Number of Items
584: * @freeShrink = Free elements before shrink array
585: * return: -1 error, 0 ok
586: */
587: int io_arrayGrow(array_t * __restrict arr, int newNumItems, int freeShrink);
588: /*
589: * io_arrayVacuum() - Vacuum dynamic array, empty elements will be deleted
590: *
591: * @arr = Array
592: * @fromWhere = 1 begin, 2 ALL empty elements
593: * return: -1 error, 0 ok
594: */
595: int io_arrayVacuum(array_t * __restrict arr, int fromWhere);
596:
597: #define io_arraySize(_arr) ((_arr) ? (_arr)->arr_num : 0)
598: #define io_arrayZero(_arr) (assert((_arr)), memset((_arr)->arr_data, 0, \
599: io_arraySize((_arr)) * sizeof(void*)))
600:
601: #define io_arrayGet(_arr, _d) (assert((_arr) && (_arr)->arr_num > _d), *((_arr)->arr_data + _d))
602: #define io_array(_arr, _d, _type) (assert((_arr) && (_arr)->arr_num > _d), \
603: ((_type) *((_arr)->arr_data + _d)))
604: #define io_arraySet(_arr, _d, _ptr) do { \
605: assert((_arr) && (_arr)->arr_num > _d); \
606: *((_arr)->arr_data + _d) = (void*) (_ptr); \
607: } while (0)
608: #define io_arrayDel(_arr, _d, _fri) do { \
609: assert((_arr) && (_arr)->arr_num > _d); \
610: if (_fri) \
611: free(*((_arr)->arr_data + _d)); \
612: *((_arr)->arr_data + _d) = NULL; \
613: } while (0)
614:
615: /*
616: * io_arrayElem() - Always GET/PUT element into dynamic array, if not enough elements grow array
617: *
618: * @arr = Array
619: * @n = Position
620: * @data = Element, if set NULL GET element at position or !=NULL PUT element at position
621: * return: -1 error or !=-1 return element at position
622: */
623: inline void *io_arrayElem(array_t * __restrict arr, int n, void *data);
624: /*
625: * io_arrayPush() - Push element into dynamic array like stack manner, place at first empty position
626: *
627: * @arr = Array
628: * @data = Element, if set NULL return only first empty position
629: * return: -1 not found empty position, array is full!, >-1 return position of stored element into array
630: */
631: inline int io_arrayPush(array_t * __restrict arr, void **data);
632: /*
633: * io_arrayPop() - Pop element from dynamic array like stack manner, last used position
634: *
635: * @arr = Array
636: * @data = Element, if set NULL return only last used position
637: * @delAfter = Delete after Pop element, !=0 delete element from array after return data
638: * return: -1 not found used position, array is empty!, >-1 return element position
639: */
640: inline int io_arrayPop(array_t * __restrict arr, void ** __restrict data, int delAfter);
641:
642: /*
643: * io_argsNum() - Parse and calculate number of arguments
644: *
645: * @csArgs = Input arguments line
646: * @csDelim = Delimiter(s) for separate
647: * return: 0 error format; -1 error:: can`t read; >0 ok, number of items
648: */
649: inline int io_argsNum(const char *csArgs, const char *csDelim);
650:
651: /*
652: * io_arrayMake() - Parse and make array from arguments ... (input string will be modified!!!
653: * and output array must be free with io_arrayDestroy() after use!)
654: *
655: * @psArgs = Input arguments line, after execute string is modified!!!
656: * @nargs = Maximum requested count of arguments from input string psArgs, if 0 all psArgs
657: * @csDelim = Delimiter(s) for separate
658: * @parr = Output array of arguments ... (must be free with io_arrayDestroy() after use!)
659: * return: 0 error format; -1 error:: can`t read; >0 ok, number of readed items
660: */
661: int io_arrayMake(char * __restrict psArgs, int nargs, const char *csDelim,
662: array_t ** __restrict parr);
663:
664: /*
665: * io_MakeAV() - Parse and make attribute/value pair
666: *
667: * @csArgs = Input argument line
668: * @csDelim = Delimiter for separate
669: * @psAttr = Output Attribute
670: * @attrLen = Size of attribute array
671: * @psValue = Output Value, if ==NULL this element not present value or not wanted for return
672: * @valLen = Size of value array
673: * return: 0 error format; -1 error:: can`t read; >0 ok, number of readed items
674: */
675: int io_MakeAV(const char * __restrict csArgs, const char *csDelim,
676: char * __restrict psAttr, int attrLen, char * __restrict psValue, int valLen);
677:
678: /*
679: * io_sarrInit() - Create and initialize dynamic split-order array
680: *
681: * @numItems = Number of Items
682: * @segLen = Length of segment
683: * return: NULL error, != NULL allocated memory for array
684: */
685: inline sarr_t *io_sarrInit(int numItems, int segLen);
686: /*
687: * io_sarrDestroy() - Free all data in dynamic split-order array and Destroy array
688: *
689: * @parr = Array
690: * return: none
691: */
692: inline void io_sarrDestroy(sarr_t ** __restrict parr);
693: /*
694: * io_sarrGrow() - Grow/Shrink dynamic split-order array, Use with care when it shrink!!!
695: *
696: * @arr = Array
697: * @newNumItems = Number of Items
698: * return: -1 error, 0 ok
699: */
700: int io_sarrGrow(sarr_t * __restrict arr, int newNumItems);
701: /*
702: * io_sarrVacuum() - Vacuum dynamic split-order array, empty segments will be freed
703: *
704: * @arr = Array
705: * return: -1 error, >-1 freed segments
706: */
707: inline int io_sarrVacuum(sarr_t * __restrict arr);
708: #define io_sarrSize(_arr) ((_arr) ? (_arr)->sarr_num : 0)
709: #define io_sarrSeg(_arr) (assert((_arr)), (_arr)->sarr_seg)
710: /*
711: * io_sarrCopy() Copy source split array to destination split array
712: *
713: * @dest = Destination split array, after use free with io_sarrDestroy()
714: * @src = Source split array
715: * return: -1 error; >0 count of destination split array
716: */
717: int io_sarrCopy(sarr_t ** __restrict dest, sarr_t * __restrict src);
718: /*
719: * io_sarrGet() - Get element from dynamic split-order array
720: *
721: * @arr = Array
722: * @idx = Index (warning 1st element is at position 1)
723: * return: NULL not found, !=NULL element
724: */
725: inline void *io_sarrGet(sarr_t * __restrict arr, unsigned int idx);
726: /*
727: * io_sarrGet2() - Always get element from dynamic split-order array
728: * Function automatic grow array. Good use for Hash tables!
729: *
730: * @arr = Array
731: * @idx = Index (warning 1st element is at position 1)
732: * return: NULL not found, !=NULL element
733: */
734: void *io_sarrGet2(sarr_t * __restrict arr, unsigned int idx);
735: /*
736: * io_sarrSet() - Set element to dynamic split-order array
737: *
738: * @arr = Array
739: * @idx = Index (warning 1st element is at position 1)
740: * @data = Value
741: * return: NULL error or empty, !=NULL old value in element
742: */
743: inline void *io_sarrSet(sarr_t * __restrict arr, unsigned int idx, void *data);
744: #define io_sarrDel(_arr, _idx) io_sarrSet((_arr), _idx, NULL)
745: #define io_sarr(_arr, _idx, _type) (_type)io_sarrGet((_arr), _idx)
746: /*
747: * io_sarr2array() - Convert from split-order array to dynamic array
748: *
749: * @sa = split array
750: * @sarrFree = after convert split array !=0 will be destroyed sarray
751: * return: NULL error or != NULL new array
752: */
753: array_t *io_sarr2array(sarr_t ** __restrict sa, int sarrFree);
754: /*
755: * io_array2sarr() - Convert from dynamic array to split-order array
756: *
757: * @a = array
758: * @segLen = Length of segment
759: * @arrFree = after convert array !=0 will be destroyed
760: * return: NULL error or != NULL new sarr
761: */
762: sarr_t *io_array2sarr(array_t ** __restrict a, int segLen, int arrFree);
763:
764: /*
765: * io_CopyEnv() - Copy environment to new environment array;
766: *
767: * @oldenv = Environment array
768: * return: NULL error; !=NULL Allocated new environment array(must be free)
769: */
770: char **io_CopyEnv(const char **oldenv);
771: /*
772: * io_ExecArgs() - Build exec arguments from other array
773: *
774: * @psProg = Program name for execute
775: * @oldarg = Arguments array
776: * return: NULL error; !=NULL Allocated execution array(must be free)
777: */
778: char **io_ExecArgs(const char *psProg, const char **oldarg);
779: /*
780: * io_FreeNullTerm() - Free dynamic allocated null terminated array with strings
781: *
782: * @arr = Pointer to array for free
783: * return: none
784: */
785: inline void io_FreeNullTerm(char *** __restrict arr);
786:
787: /*
788: * ioMkDir() - Function for racursive directory creation and validation
789: *
790: * @csDir = Full directory path
791: * @mode = Mode for directory creation if missing dir
792: * return: -1 error, 0 directory path exist, >0 created missing dirs
793: */
794: int ioMkDir(const char *csDir, int mode);
795:
796: /*
797: * ioWatchDirLoop() - Function for watching changes in directory and fire callback
798: *
799: * @csDir = Full directory path
800: * @callback = Callback if raise event! nOp -1 delete, 0 change/move, 1 create
801: * return: -1 error, !=-1 ok, number of total signaled events
802: */
803: int ioWatchDirLoop(const char *csDir, int (*callback)(const char *csName, int nOp));
804:
805:
806: /*
807: * io_rread() - Raw VFS read function
808: *
809: * @fd = File handle
810: * @buf = Read buffer
811: * @nbytes = Read buffer size
812: * @offset = Read from position, if -1 read nbytes from current position
813: * @update = Update file handle position !0
814: * return: -1 error or !=-1 readed bytes
815: */
816: inline int io_rread(int fd, void * __restrict buf, size_t nbytes, off_t offset, int update);
817: /*
818: * io_rwrite() - Raw VFS write function
819: *
820: * @fd = File handle
821: * @buf = Write buffer
822: * @nbytes = Write bytes from buffer
823: * @offset = Write at position, if -1 write nbytes from current position
824: * @update = Update file handle position !0
825: * return: -1 error or !=-1 writed bytes
826: */
827: inline int io_rwrite(int fd, void * __restrict buf, size_t nbytes, off_t offset, int update);
828:
829: /* Disk I/O helper macros */
830: #define io_read(f, b, n) io_rread(f, b, n, -1, 1)
831: #define io_write(f, b, n) io_rwrite(f, b, n, -1, 1)
832:
833:
834: /* Debug helper macros */
835: extern int io_Debug;
836:
837: #define io_enableDEBUG int io_Debug
838: #define io_initDebug(x) (io_Debug = (x))
839: #define io_incDebug (io_Debug++)
840: #define io_decDebug (io_Debug--)
841:
842: /* Debug macros */
843: #define ioVERBOSE(x) if ((x) <= io_Debug)
844: #define ioTRACE(x) if ((x) <= io_Debug) \
845: syslog(LOG_DEBUG, "I'm in %s(%d)", __func__, __LINE__)
846: #define ioDEBUG(x, fmt, ...) do { \
847: assert((fmt)); \
848: char str[STRSIZ] = { 0 }; \
849: snprintf(str, sizeof str, (fmt), ##__VA_ARGS__); \
850: if ((x) <= io_Debug) \
851: syslog(LOG_DEBUG, "Debug(%d):%s(%d): %s\n", \
852: (x), __func__, __LINE__, str); \
853: } while (0)
854:
855: /* Logger macro */
856: #define ioLOGGER(x, fmt, ...) do { \
857: assert((fmt)); \
858: char str[STRSIZ] = { 0 }; \
859: snprintf(str, sizeof str, (fmt), ##__VA_ARGS__); \
860: syslog((x), "Logger:%s(%d): %s\n", \
861: __func__, __LINE__, str); \
862: } while (0)
863:
864: /* Error state macros */
865: #define ioERROR(x, fmt, ...) do { \
866: assert((fmt)); \
867: char str[STRSIZ] = { 0 }; \
868: snprintf(str, sizeof str, (fmt), ##__VA_ARGS__); \
869: syslog(LOG_ERR, "Error:%s(%d): #%d - %s\n", \
870: __func__, __LINE__, (x), str); \
871: } while (0)
872: #define ioSYSERR(x) do { \
873: if (x > 0 || errno) \
874: syslog(LOG_ERR, "Error(sys):%s(%d): #%d - %s\n", \
875: __func__, __LINE__, x > 0 ? x : errno, \
876: strerror(x > 0 ? x : errno)); \
877: } while (0)
878: #define ioLIBERR(ait) do { \
879: if (ait##_GetErrno()) \
880: syslog(LOG_ERR, "Error(lib):%s(%d): #%d - %s\n", \
881: __func__, __LINE__, ait##_GetErrno(), \
882: ait##_GetError()); \
883: } while (0)
884:
885:
886: /* Crypto framework */
887:
888: /*
889: * ioCipher() - Cipher wrapper for all supported crypto algorythms
890: *
891: * @pInput = input buffer
892: * @inLen = input buffer len
893: * @ppOutput = output allocated buffe, must be free after use
894: * @Cipher = cipher engine, like EVP_bf_cbc() or etc...
895: * @pKey = key
896: * @pIV = IV, salt (8 bytes)
897: * @nMode = Mode 0 - decrypting or 1 - encrypting
898: * return: 0 not present data or error!; >0 number of processed and returned bytes into ppOutput
899: */
900: int ioCipher(unsigned char *pInput, int inLen, unsigned char **ppOutput, const EVP_CIPHER *Cipher,
901: unsigned char *pKey, unsigned char *pIV, int nMode);
902:
903: /*
904: * io_Blowfish() - Blowfish cipher algorythm, work with ASCII hex strings
905: *
906: * @pInput = input buffer
907: * @inLen = input buffer len
908: * @ppOutput = output allocated buffe, must be free after use
909: * @pKey = key
910: * @pIV = IV, salt (8 bytes)
911: * @nMode = Mode 0 - decrypting or 1 - encrypting
912: * return: 0 not present data or error!; >0 number of processed and returned bytes into ppOutput
913: */
914: int io_Blowfish(unsigned char *pInput, int inLen, unsigned char **ppOutput,
915: unsigned char *pKey, unsigned char *pIV, int nMode);
916: /*
917: * io_ctr_AES() - Encrypt/Decrypt stream cipher CTR_AES
918: *
919: * @pInput = Input buffer with ASCII
920: * @inLen = Input buffer data length
921: * @ppOutput = Output buffer with cipher data, must be free after use
922: * @pKey = Key
923: * @IV = IVector/Nonce/Counter, Warning: IV must be variable, because we write there!!!
924: * return: -1 error or >-1 how many cipher blocks proceeded
925: */
926: int io_ctr_AES(unsigned char *pInput, int inLen, unsigned char **ppOutput,
927: unsigned char *pKey, unsigned char IV[AES_BLOCK_SIZE]);
928:
929:
930: /*
931: * ioAllocPTY() - Allocate new PTY and TTY
932: *
933: * @ptyfd = master fd, pty
934: * @ttyfd = slave fd, tty
935: * @name = tty device name if not null
936: * @namesiz = name length, must be above 63 bytes.
937: * @term = termios for terminal
938: * @winz = winsize for terminal
939: * return: -1 error or 0 ok
940: */
941: inline int ioAllocPTY(int *ptyfd, int *ttyfd, char * __restrict name, int namesiz,
942: struct termios * __restrict term, struct winsize * __restrict winz);
943: /*
944: * ioFreePTY() - Release PTY and TTY device
945: *
946: * @ptyfd = master fd, pty (==-1 skip closing pty)
947: * @ttyname = tty filename
948: * return: none
949: */
950: inline void ioFreePTY(int ptyfd, const char *ttyname);
951: /*
952: * ioChgWinPTY() - Change window size of PTY
953: *
954: * @ptyfd = master fd, pty
955: * @row = row
956: * @col = col
957: * @xpxl = x pixels
958: * @ypxl = y pixels
959: * return: -1 error or 0 ok
960: */
961: inline int ioChgWinPTY(int ptyfd, unsigned short row, unsigned short col,
962: unsigned short xpxl, unsigned short ypxl);
963: /*
964: * ioSetOwnerTTY() - Set owner to TTY
965: *
966: * @ttyname = tty filename
967: * @UID = uid
968: * @GID = gid
969: * return: -1 error or 0 ok
970: */
971: int ioSetOwnerTTY(const char *ttyname, uid_t UID, gid_t GID);
972: /*
973: * ioSetSidTTY() - Makes the process's controlling TTY and sets it to sane modes.
974: *
975: * @ttyfd = slave fd, tty
976: * @ttyname = tty filename
977: * return: -1 error or 0 ok
978: */
979: int ioSetSidTTY(int *ttyfd, const char *ttyname);
980: /*
981: * ioSetRAWMode() - Enter into RAW mode
982: *
983: * @fd = tty fd
984: * @otio = saved old termios for later restore if !=NULL
985: * return: -1 error or 0 ok
986: */
987: inline int ioSetRAWMode(int fd, struct termios *otio);
988: /*
989: * ioRestoreMode() - Restore termios to tty fd
990: *
991: * @fd = tty fd
992: * @tio = termios structure for restore
993: * return: -1 error or 0 ok
994: */
995: inline int ioRestoreMode(int fd, struct termios tio);
996: /*
997: * ioForkPTY() - Fork new process with session leader and new TTY
998: *
999: * @ptyfd = master fd, pty
1000: * @name = tty device name if not null
1001: * @namesiz = name length, must be above 63 bytes.
1002: * @term = termios for terminal
1003: * @winz = winsize for terminal
1004: * @otio = old termios structure for restore
1005: * return: -1 error, 0 child process or >0 parent: pid of child
1006: */
1007: pid_t ioForkPTY(int *ptyfd, char * __restrict name, int namesiz, struct termios * __restrict term,
1008: struct winsize * __restrict winz, struct termios * __restrict otio);
1009:
1010: /*
1011: * ioCreatePIDFile() - Create PID file
1012: *
1013: * @csName = PID filename
1014: * @ifExists = !=0 if filename exists return error
1015: * return: -1 error or 0 ok
1016: */
1017: inline int ioCreatePIDFile(const char *csName, int ifExists);
1018:
1019: /*
1020: * ioSendFile() - AITNET sendfile() userland implementation, not dependant from OS
1021: *
1022: * @s = socket
1023: * @csFile = file for send
1024: * @sendLen = bytes to send, if 0 send all data
1025: * @offset = start file offset
1026: * @sndbuf = SO_SNDBUF value, if 0 use default
1027: * return: 0 error, >0 ok, sended bytes
1028: */
1029: size_t ioSendFile(int s, const char *csFile, size_t sendLen, off_t offset, int sndbuf);
1030: /*
1031: * ioRecvFile() - Receive file from socket, fastest (zero-copy) way
1032: *
1033: * @s = socket
1034: * @csFile = file for receive
1035: * @recvLen = receive bytes
1036: * @over = overwrite file if exists with mode like 0644
1037: * @rcvbuf = SO_RCVBUF value, if 0 use default
1038: * return: 0 error, >0 ok, received bytes
1039: */
1040: size_t ioRecvFile(int s, const char *csFile, size_t recvLen, int over, int rcvbuf);
1041:
1042:
1043: /* Buffered file access over memory block */
1044:
1045: /*
1046: * io_fmemopen() - File buffered stream operations over memory block
1047: *
1048: * @base = Base address of memory block, if =NULL Infinit length(auto-grow)
1049: * @basesize = Size of memory block
1050: * return: NULL error or !=NULL Opened file resource
1051: */
1052: FILE *io_fmemopen(void ** __restrict base, off_t basesize);
1053: /*
1054: * io_fmapopen() - File buffered stream operations over MMAP block
1055: *
1056: * @csFile = Filename for MMAP, if =NULL private MMAP block
1057: * @mode = File open mode
1058: * @perm = If file not exists will be created with this access permissions
1059: * @prot = MMAP protection
1060: * @flags = MMAP mode flags
1061: * @offset = Map from file offset, if csFile==NULL then this is size of MMAP private block
1062: * return: NULL error or !=NULL Opened file resource
1063: */
1064: FILE *io_fmapopen(const char *csFile, int mode, int perm, int prot, int flags, off_t offset);
1065: /*
1066: * io_fd2buf() - Convert open file handle to buffered file I/O
1067: *
1068: * @fd = File handle
1069: * @mode = Permissions for new buffered file I/O
1070: * return: NULL error or open buffered file
1071: */
1072: inline FILE *io_fd2buf(int fd, const char *mode);
1073: /*
1074: * io_dumbFile() - Create empry or dumb file with fixed size
1075: *
1076: * @csFile = Filename for create
1077: * @mode = File access permissions
1078: * @size = File size
1079: * return: -1 error or open file handle
1080: */
1081: int io_dumbFile(const char *csFile, int mode, off_t size);
1082:
1083:
1084: #endif
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>