Skip to content

Commit

Permalink
replace atoi with strtol (sonic-net#6)
Browse files Browse the repository at this point in the history
From Semgrep: https://semgrep.dev/r?q=c.lang.correctness.incorrect-use-ato-fn.incorrect-use-ato-fn

> Avoid the 'ato*()' family of functions. Their use can lead to undefined behavior, integer overflows, and lack of appropriate error handling. Instead prefer the 'strtol*()' family of functions.

From atoi() man page: https://www.man7.org/linux/man-pages/man3/atoi.3.html

> The atoi() function converts the initial portion of the string pointed to by nptr to int.  The behavior is the same as
>            strtol(nptr, NULL, 10);
> except that atoi() does not detect errors.

Therefore, replace atoi() with strtol()

Verified by kill dhcpmon process, installing new .deb change to dhcp_relay docker, execute dhcpmon process, check if counters is printing in syslog, compare counters before and after this change.
logs: 
[before.txt](https://github.com/sonic-net/sonic-dhcpmon/files/11377335/before.txt)
[after.txt](https://github.com/sonic-net/sonic-dhcpmon/files/11377336/after.txt)

example commands: 
[command.txt](https://github.com/sonic-net/sonic-dhcpmon/files/11423945/command.txt)
  • Loading branch information
maipbui authored Jun 27, 2023
1 parent 32c0c3f commit 824a144
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,13 @@ int main(int argc, char **argv)
{
int rv = EXIT_FAILURE;
int i;
char *endptr;
int window_interval = dhcpmon_default_health_check_window;
int max_unhealthy_count = dhcpmon_default_unhealthy_max_count;
size_t snaplen = dhcpmon_default_snaplen;
int make_daemon = 0;
bool debug_mode = false;
errno = 0;

setlogmask(LOG_UPTO(LOG_INFO));
openlog(basename(argv[0]), LOG_CONS | LOG_PID | LOG_NDELAY, LOG_DAEMON);
Expand Down Expand Up @@ -150,15 +152,27 @@ int main(int argc, char **argv)
i++;
break;
case 's':
snaplen = atoi(argv[i + 1]);
snaplen = strtol(argv[i + 1], &endptr, 10);
if (errno != 0 || *endptr != '\0') {
fprintf(stderr, "%s: %s: Invalid snap length\n", basename(argv[0]), argv[i + 1]);
usage(basename(argv[0]));
}
i += 2;
break;
case 'w':
window_interval = atoi(argv[i + 1]);
window_interval = strtol(argv[i + 1], &endptr, 10);
if (errno != 0 || *endptr != '\0') {
fprintf(stderr, "%s: %s: Invalid window interval\n", basename(argv[0]), argv[i + 1]);
usage(basename(argv[0]));
}
i += 2;
break;
case 'c':
max_unhealthy_count = atoi(argv[i + 1]);
max_unhealthy_count = strtol(argv[i + 1], &endptr, 10);
if (errno != 0 || *endptr != '\0') {
fprintf(stderr, "%s: %s: Invalid max unhealthy count\n", basename(argv[0]), argv[i + 1]);
usage(basename(argv[0]));
}
i += 2;
break;
case 'D':
Expand Down

0 comments on commit 824a144

Please sign in to comment.