Created
May 28, 2013 15:54
-
-
Save reyjrar/5663806 to your computer and use it in GitHub Desktop.
Implement shell escaping, relies on caller to clean up the memory for the escaped string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Escape a set of characters */ | |
char *os_shell_escape(const char *src) { | |
// Maximum Length of the String is 2xthe current length | |
char shell_escapes[] = { '\\', '"', '\'', ' ', '\t', ';', '`', '>', '<', '|', '#', | |
'*', '[', ']', '{', '}', '&', '$', '!', ':', '(', ')' }; | |
char *escaped_string; | |
int length = 0; | |
int i = 0; | |
// Determine how long the string will be | |
char *iterator = src; | |
for (; *iterator; iterator++) { | |
if( strchr(shell_escapes, *iterator) ) { | |
length++; | |
} | |
length++; | |
} | |
// Allocate the memory | |
if( (escaped_string = malloc( length + 1 )) == NULL ) { | |
// Return NULL | |
return NULL; | |
} | |
memset(escaped_string, '\0', length + 1); | |
// Escape the escapable characters | |
iterator=src; | |
for( i=0; *iterator; iterator++ ) { | |
if ( strchr(shell_escapes, *iterator) ) { | |
escaped_string[i] = '\\'; | |
i++; | |
} | |
escaped_string[i] = *iterator; | |
i++; | |
} | |
// Return Success | |
return escaped_string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment