Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 16 Jul 1999 12:24:47 +0300 (EDT)
From:      "Valentin Nechayev" <nx@nn.kiev.ua>
To:        freebsd-hackers@freebsd.org
Subject:   Re: OpenBSD's strlcpy(3) and strlcat(3)
Message-ID:  <ABVflZtee0@nn.kiev.ua>
References:  <199907152358.QAA01894@dingo.cdrom.com>

next in thread | previous in thread | raw e-mail | index | archive | help
Mike Smith wrote:

>   pw = getpwuid(getuid());
>   strlcpy(buf, pw->dir, sizeof(buf));
>   strlcat(buf, "/.appname/", sizeof(buf));
>   strlcat(buf, conffilename, sizeof(buf));
>   if (strlen(buf) >= sizeof(buf))
>       return(error);
>   fp = fopen(buf, "r");
>   ...
>
> That works, as long as MAXPATHLEN is actually long enough.  In this

It is incorrect in two places. 1st, strlen(buf) always will be less than
buffer size (it is told here yet). 2nd, if the last addition to buffer is
zero-length, you cannot check the overflow using return value of last
strlcat() (it was not in your code, but I have seen it in idea in your
code;)) To check overflow, you can either
1) check result of _each_ strlcpy/strlcat function,
2) [this is hack, but beauty hack;))] create buffer of size
{max_possible_length}+2 and test string length after all catenations;
if it is more then {max_possible_length}, the overflow was there.

>   if (asprintf(&buf, "%s/.appname/%s", pw->dir, conffilename) == -1)
>       return(error);
>   fp = fopen(buf, "r");
>   free(buf);
>   ...
>
> The latter has a few really clear advantages:
>
>  - you can see what the string is meant to look like.
>  - it doesn't matter how long any of the components are.
>  - the constructed value is on the heap, so you can return it (just
>    imagine how much nicer ctime() would be if it did this).

Yes, let you wrap around ctime() with asprintf() ;)

--
NN




To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?ABVflZtee0>