Skip to content

Commit bd8e9f5

Browse files
Fixed: Fix exit code handling
strtol() returns 0 on conversion failure and errno is not set, which resulted in wrong exit codes passed by server to be assumed to be exit code 0. Moreover, shell exit codes are limited to 0-255 and that was not being checked. Out of bound exit codes would return with exit code `44` `Channel number out of range`.
1 parent f7f1cdd commit bd8e9f5

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

termux-am.cpp

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ bool recv_part(const int fd, char* data, int len) {
6565
return false;
6666
}
6767

68+
bool is_number(const std::string& s) {
69+
std::string::const_iterator it = s.begin();
70+
while (it != s.end() && std::isdigit(*it)) ++it;
71+
return !s.empty() && it == s.end();
72+
}
6873

6974
int main(int argc, char* argv[]) {
7075
struct sockaddr_un adr = {.sun_family = AF_UNIX};
@@ -99,15 +104,28 @@ int main(int argc, char* argv[]) {
99104
{
100105
char tmp[10];
101106
memset(tmp, '\0', sizeof(tmp));
102-
if (! recv_part(fd, tmp, sizeof(tmp)-1)) {
103-
fputs("Exit code too long", stderr);
107+
if (!recv_part(fd, tmp, sizeof(tmp) - 1)) {
108+
std::string errmsg = "Exit code \"" + std::string(tmp) + "\" is too long. It must be valid number between 0-255";
109+
if (errno == 0)
110+
std::cerr << errmsg << std::endl;
111+
else
112+
perror(errmsg.c_str());
104113
close(fd);
105114
return 1;
106115
}
116+
117+
// strtol returns 0 if conversion failed and allows leading whitespaces
107118
errno = 0;
108119
exit_code = strtol(tmp, NULL, 10);
109-
if (errno != 0) {
110-
perror("Exit code not a valid number");
120+
if (!is_number(std::string(tmp)) || (exit_code == 0 && std::string(tmp) != "0")) {
121+
std::cerr << "Exit code \"" + std::string(tmp) + "\" is not a valid number between 0-255" << std::endl;
122+
close(fd);
123+
return 1;
124+
}
125+
126+
// Out of bound exit codes would return with exit code `44` `Channel number out of range`.
127+
if (exit_code < 0 || exit_code > 255) {
128+
std::cerr << "Exit code \"" << std::string(tmp) << "\" is not a valid exit code between 0-255" << std::endl;
111129
close(fd);
112130
return 1;
113131
}

0 commit comments

Comments
 (0)