soap.c (1324B)
1 /* See LICENSE file for copyright and license details. */ 2 #include <stdlib.h> 3 #include <stdio.h> 4 #include <regex.h> 5 6 typedef struct { 7 const char *regex; 8 const char *action; 9 } Pair; 10 11 #include "config.h" 12 13 int 14 main(int argc, char *argv[]){ 15 size_t g, h, i; 16 char cmd[BUFSIZ], sharg[BUFSIZ]; 17 regex_t regex; 18 19 /* we only take one argument */ 20 if (argc != 2) 21 return EXIT_FAILURE; 22 23 /* make the argument shell-ready 24 * 1) start with ' 25 * 2) escape ' to '\'' 26 * 3) close with '\0 27 */ 28 sharg[0] = '\''; 29 for (g=0, h=1; argv[1][g] && h < BUFSIZ-1-3-2; ++g, ++h) { 30 sharg[h] = argv[1][g]; 31 if (argv[1][g] == '\'') { 32 sharg[++h] = '\\'; 33 sharg[++h] = '\''; 34 sharg[++h] = '\''; 35 } 36 } 37 sharg[h] = '\''; 38 sharg[++h] = 0; 39 40 /* check regex and launch action if it matches argv[1] */ 41 for (i=0; i < sizeof(pairs)/sizeof(*pairs); ++i) { 42 if (regcomp(®ex, pairs[i].regex, 43 REG_EXTENDED | REG_NOSUB)) { 44 fprintf(stderr, "invalid regex: %s\n", pairs[i].regex); 45 return EXIT_FAILURE; 46 } 47 if (!regexec(®ex, argv[1], 0, NULL, 0)) { 48 snprintf(cmd, sizeof cmd, pairs[i].action, sharg); 49 system(cmd); 50 regfree(®ex); 51 return EXIT_SUCCESS; 52 } 53 regfree(®ex); 54 } 55 56 /* alternatively, fall back to xdg-open_ */ 57 snprintf(cmd, sizeof cmd, "xdg-open_ %s", sharg); 58 system(cmd); 59 return EXIT_SUCCESS; 60 }