1 /* 2 * e_loop helper program 3 * Copyright (c) 2015, Qualcomm Atheros, Inc. 4 * All Rights Reserved. 5 * Licensed under the Clear BSD license. See README for more details. 6 */ 7 8 #include <stdlib.h> 9 #include <stdio.h> 10 #include <stdarg.h> 11 #include <string.h> 12 #include <unistd.h> 13 #include <sys/wait.h> 14 15 16 char *e_loop_cmd_file = "/data/local/hs2/To_Phone/tag_file"; 17 char *e_loop_log_file = "/data/local/hs2/To_Phone/Logs/e_loop.log"; 18 static const char *log_file = NULL; 19 static const char *tag_file = NULL; 20 21 22 int main(int argc, char *argv[]) 23 { 24 char *buf = NULL; 25 char *cmd = NULL; 26 long pos; 27 int c, ret; 28 size_t len = 0; 29 FILE *f, *f2 = NULL; 30 31 /* Set the defaults */ 32 log_file = e_loop_log_file; 33 tag_file = e_loop_cmd_file; 34 35 for (;;) { 36 c = getopt(argc, argv, "l:t:"); 37 if (c < 0) 38 break; 39 switch (c) { 40 case 'l': 41 log_file = optarg; 42 break; 43 case 't': 44 tag_file = optarg; 45 break; 46 default: 47 printf("usage: e_loop [-l<log_filename>] [-t<tag_filename>]\n"); 48 exit(0); 49 break; 50 } 51 } 52 53 /* Main command event loop */ 54 while (1) { 55 /* Wait for a tag_file with a command to process */ 56 while (!(f = fopen(tag_file, "rb"))) 57 sleep(1); 58 59 len = 80; 60 /* Figure out how long the file is */ 61 if (fseek(f, 0, SEEK_END) < 0 || (pos = ftell(f)) < 0) { 62 fclose(f); 63 return -1; 64 } 65 len = pos; 66 if (fseek(f, 0, SEEK_SET) < 0) { 67 fclose(f); 68 return -1; 69 } 70 buf = malloc(len); 71 if (!buf) { 72 fclose(f); 73 return -1; 74 } 75 /* Read up the command line */ 76 if (fread(buf, 1, len, f) != len) { 77 fclose(f); 78 free(buf); 79 return -1; 80 } 81 fclose(f); 82 83 buf[len - 1] = '\0'; 84 85 if (log_file) { 86 len = strlen(buf) + strlen(log_file) + 7; 87 cmd = malloc(len); 88 if (cmd == NULL) { 89 free(buf); 90 return -1; 91 } 92 ret = snprintf(cmd, len, "%s > %s", buf, log_file); 93 if (ret < 0 || (size_t) ret >= len) { 94 free(buf); 95 free(cmd); 96 return -1; 97 } 98 free(buf); 99 buf = NULL; 100 } else { 101 cmd = buf; 102 } 103 104 cmd[len - 1] = '\0'; 105 106 /* 107 * This string "cmd" will contain the command passed in by 108 * hs20-action.sh. And the name of the "logfile". Which can be 109 * monitored for the result. 110 */ 111 ret = system(cmd); 112 113 if (WIFEXITED(ret)) { 114 ret = WEXITSTATUS(ret); 115 } 116 117 if ((f2 = fopen(log_file, "a")) == NULL) { 118 free(cmd); 119 return -1; 120 } 121 122 if (fprintf(f2,"\nELOOP_CMD : %s\n", cmd) <= 0) { 123 fclose(f2); 124 free(cmd); 125 return -1; 126 } 127 128 if (fprintf(f2,"\nELOOP_CMD_STATUS : %d\n", ret) <= 0) { 129 fclose(f2); 130 free(cmd); 131 return -1; 132 } 133 134 /* Only free the cmd buffer. It is all that is left allocated */ 135 free(cmd); 136 137 fclose(f2); 138 139 /* Clean up */ 140 unlink(tag_file); 141 } 142 143 return ret; 144 } 145