lib/inet_proto: Review inet_proto_{a2n,n2a}()

The original intent was to make sure strings written by those functions
are NUL-terminated at all times, though it was suggested to get rid of
the 15 char protocol name limit as well which this patch accomplishes.

In addition to that, simplify inet_proto_a2n() a bit: Use the error
checking in get_u8() to find out whether passed 'buf' contains a valid
decimal number instead of checking the first character's value manually.

Signed-off-by: Phil Sutter <phil@nwl.cc>
This commit is contained in:
Phil Sutter 2017-08-24 11:51:47 +02:00 committed by Stephen Hemminger
parent eab4507898
commit cfda500a7d
1 changed files with 13 additions and 11 deletions

View File

@ -25,7 +25,7 @@
const char *inet_proto_n2a(int proto, char *buf, int len) const char *inet_proto_n2a(int proto, char *buf, int len)
{ {
static char ncache[16]; static char *ncache;
static int icache = -1; static int icache = -1;
struct protoent *pe; struct protoent *pe;
@ -34,9 +34,12 @@ const char *inet_proto_n2a(int proto, char *buf, int len)
pe = getprotobynumber(proto); pe = getprotobynumber(proto);
if (pe) { if (pe) {
if (icache != -1)
free(ncache);
icache = proto; icache = proto;
strncpy(ncache, pe->p_name, 16); ncache = strdup(pe->p_name);
strncpy(buf, pe->p_name, len); strncpy(buf, pe->p_name, len - 1);
buf[len - 1] = '\0';
return buf; return buf;
} }
snprintf(buf, len, "ipproto-%d", proto); snprintf(buf, len, "ipproto-%d", proto);
@ -45,24 +48,23 @@ const char *inet_proto_n2a(int proto, char *buf, int len)
int inet_proto_a2n(const char *buf) int inet_proto_a2n(const char *buf)
{ {
static char ncache[16]; static char *ncache;
static int icache = -1; static int icache = -1;
struct protoent *pe; struct protoent *pe;
__u8 ret;
if (icache>=0 && strcmp(ncache, buf) == 0) if (icache != -1 && strcmp(ncache, buf) == 0)
return icache; return icache;
if (buf[0] >= '0' && buf[0] <= '9') { if (!get_u8(&ret, buf, 10))
__u8 ret;
if (get_u8(&ret, buf, 10))
return -1;
return ret; return ret;
}
pe = getprotobyname(buf); pe = getprotobyname(buf);
if (pe) { if (pe) {
if (icache != -1)
free(ncache);
icache = pe->p_proto; icache = pe->p_proto;
strncpy(ncache, pe->p_name, 16); ncache = strdup(pe->p_name);
return pe->p_proto; return pe->p_proto;
} }
return -1; return -1;