diff --git a/mhl/shell_escape.h b/mhl/shell_escape.h
new file mode 100644
index 0000000..7b47e0a
-
|
+
|
|
| 1 | #ifndef __MHL_SHELL_ESCAPE_H |
| 2 | #define __MHL_SHELL_ESCAPE_H |
| 3 | |
| 4 | /* Micro helper library: shell escaping functions */ |
| 5 | |
| 6 | #include <string.h> |
| 7 | #include <stdlib.h> |
| 8 | |
| 9 | #define __char_to_escape(x) \ |
| 10 | (((x)==' ')||((x)=='!')||((x)=='#')||((x)=='$')||((x)=='%')|| \ |
| 11 | ((x)=='(')||((x)==')')||((x)=='\'')||((x)=='&')||((x)=='~')|| \ |
| 12 | ((x)=='{')||((x)=='}')||((x)=='[')||((x)==']')||((x)=='`')|| \ |
| 13 | ((x)=='?')||((x)=='|')||((x)=='<')||((x)=='>')||((x)==';')|| \ |
| 14 | ((x)=='*')||((x)=='\\')||((x)=='"')) |
| 15 | |
| 16 | #define __char_not_escape(x) \ |
| 17 | (((x)!=0) && (!__char_to_escape((x)))) |
| 18 | |
| 19 | static inline char* mhl_shell_escape_dup(const char* src) |
| 20 | { |
| 21 | if ((src==NULL)||(!(*src))) |
| 22 | return strdup(""); |
| 23 | |
| 24 | char* buffer = calloc(1, strlen(src)*2+2); |
| 25 | char* bufptr = buffer; |
| 26 | |
| 27 | /* look for the first char to escape */ |
| 28 | while (1) |
| 29 | { |
| 30 | char c; |
| 31 | /* copy over all chars not to escape */ |
| 32 | while ((c=*src) && __char_not_escape(c)) |
| 33 | { |
| 34 | *bufptr = c; |
| 35 | bufptr++; |
| 36 | src++; |
| 37 | } |
| 38 | |
| 39 | /* at this point we either have an \0 or an char to escape */ |
| 40 | if (!c) |
| 41 | return buffer; |
| 42 | |
| 43 | *bufptr = '\\'; |
| 44 | bufptr++; |
| 45 | *bufptr = c; |
| 46 | bufptr++; |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | #endif |