blob: 96c673fd55c8fce17f7b483b3af62c19e8590afb [file] [log] [blame]
Jouni Malinencd4e3c32015-10-29 12:39:56 +02001/*
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
16char *e_loop_cmd_file = "/data/local/hs2/To_Phone/tag_file";
17char *e_loop_log_file = "/data/local/hs2/To_Phone/Logs/e_loop.log";
18static const char *log_file = NULL;
19static const char *tag_file = NULL;
20
21
22int 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 return -1;
73 /* Read up the command line */
74 if (fread(buf, 1, len, f) != len) {
75 fclose(f);
76 free(buf);
77 return -1;
78 }
79 fclose(f);
80
81 buf[len - 1] = '\0';
82
83 if (log_file) {
84 len = strlen(buf) + strlen(log_file) + 7;
85 cmd = malloc(len);
86 if (cmd == NULL) {
87 free(buf);
88 return -1;
89 }
90 ret = snprintf(cmd, len, "%s > %s", buf, log_file);
91 if (ret < 0 || (size_t) ret >= len) {
92 free(buf);
93 free(cmd);
94 return -1;
95 }
96 free(buf);
97 buf = NULL;
98 } else {
99 cmd = buf;
100 }
101
102 cmd[len - 1] = '\0';
103
104 /*
105 * This string "cmd" will contain the command passed in by
106 * hs20-action.sh. And the name of the "logfile". Which can be
107 * monitored for the result.
108 */
109 ret = system(cmd);
110
111 if (WIFEXITED(ret)) {
112 ret = WEXITSTATUS(ret);
113 }
114
115 if ((f2 = fopen(log_file, "a")) == NULL) {
116 free(cmd);
117 return -1;
118 }
119
120 if (fprintf(f2,"\nELOOP_CMD : %s\n", cmd) <= 0) {
121 fclose(f2);
122 free(cmd);
123 return -1;
124 }
125
126 if (fprintf(f2,"\nELOOP_CMD_STATUS : %d\n", ret) <= 0) {
127 fclose(f2);
128 free(cmd);
129 return -1;
130 }
131
132 /* Only free the cmd buffer. It is all that is left allocated */
133 free(cmd);
134
135 fclose(f2);
136
137 /* Clean up */
138 unlink(tag_file);
139 }
140
141 return ret;
142}