Skip to content

Instantly share code, notes, and snippets.

@dualbus
Created April 21, 2014 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dualbus/11160603 to your computer and use it in GitHub Desktop.
Save dualbus/11160603 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
char *shell_escape(char *, size_t);
int main(int argc, char **argv) {
puts(shell_escape("'; echo shell'", 14));
}
char *shell_escape(char *data, size_t n) {
size_t i, j, single_quotes = 0;
char *p, *o;
for(i = 0, p = data; i < n && *p != (char *)NULL; i++, p++) {
if(*p == '\'') {
single_quotes++;
}
}
o = (char *)malloc(3*single_quotes + i + 3);
if(o == (char *)NULL) {
exit(EXIT_FAILURE);
}
for(i = 0, j = 1, p = data; i < n && *p != (char *)NULL; i++, j++, p++) {
if(*p == '\'') {
o[j] = '\'';
o[j+1] = '\\';
o[j+2] = '\'';
o[j+3] = '\'';
j += 3;
} else {
o[j] = *p;
}
}
o[0] = '\'';
o[3*single_quotes + i + 1] = '\'';
o[3*single_quotes + i + 2] = '\0';
return o;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment