Remove usage of snprintf() from patty_ax25_ntop()
Remove usage of snprintf() from patty_ax25_ntop() to gain better control over the behavior of how the 'len' argument and nul terminator are handled
This commit is contained in:
parent
c98d07e876
commit
02033990a6
1 changed files with 31 additions and 10 deletions
41
src/ax25.c
41
src/ax25.c
|
@ -1,4 +1,3 @@
|
||||||
#include <stdio.h>
|
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
|
@ -84,6 +83,21 @@ error_invalid_callsign:
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static inline int expt(int base, int e) {
|
||||||
|
int ret = base,
|
||||||
|
i;
|
||||||
|
|
||||||
|
if (e == 0) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (i=1; i<e; i++) {
|
||||||
|
ret *= base;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
int patty_ax25_ntop(const patty_ax25_addr *addr,
|
int patty_ax25_ntop(const patty_ax25_addr *addr,
|
||||||
char *dest,
|
char *dest,
|
||||||
size_t len) {
|
size_t len) {
|
||||||
|
@ -96,7 +110,7 @@ int patty_ax25_ntop(const patty_ax25_addr *addr,
|
||||||
uint8_t c;
|
uint8_t c;
|
||||||
|
|
||||||
if (o == len) {
|
if (o == len) {
|
||||||
goto error_overflow;
|
goto error;
|
||||||
}
|
}
|
||||||
|
|
||||||
c = (addr->callsign[i] & 0xfe) >> 1;
|
c = (addr->callsign[i] & 0xfe) >> 1;
|
||||||
|
@ -109,25 +123,32 @@ int patty_ax25_ntop(const patty_ax25_addr *addr,
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ssid) {
|
if (ssid) {
|
||||||
int formatted;
|
int digits = ssid > 9? 2: 1,
|
||||||
|
d;
|
||||||
|
|
||||||
if ((formatted = snprintf(&dest[o], 1 + len - o, "-%d", ssid)) < 0) {
|
if (o + 1 + digits > len) {
|
||||||
goto error_format_ssid;
|
goto error;
|
||||||
} else {
|
}
|
||||||
o += formatted;
|
|
||||||
|
dest[o++] = '-';
|
||||||
|
|
||||||
|
for (d=0; d<digits; d++) {
|
||||||
|
int place = expt(10, digits - d - 1),
|
||||||
|
num = ((int)ssid % (place * 10)) / place;
|
||||||
|
|
||||||
|
dest[o++] = num + '0';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (o > len) {
|
if (o > len) {
|
||||||
goto error_overflow;
|
goto error;
|
||||||
}
|
}
|
||||||
|
|
||||||
dest[o] = '\0';
|
dest[o] = '\0';
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
|
|
||||||
error_format_ssid:
|
error:
|
||||||
error_overflow:
|
|
||||||
errno = EOVERFLOW;
|
errno = EOVERFLOW;
|
||||||
|
|
||||||
return -1;
|
return -1;
|
||||||
|
|
Loading…
Add table
Reference in a new issue