Hacker News new | ask | show | jobs
by holisd 4884 days ago
strlcpy is flawed. And often times silent truncation is not a "best-effort", but a huge hole. This is especially so when strcpy is blindly replaced with strlcpy. For new code, strlcpy is flawed.
2 comments

Ulrich Drepper? Is that you?

There are valid reasons not to use strlcpy, but we need something like it. What we do not need is this _s shit, which has all the same problems (which sometimes matter, and sometimes don't) WHILE BEING MASSIVELY HARDER TO USE. And what's the advantage? Just that it returns an errno. That's fine, but what about the rest of it? Just read the instructions for it - it's crap! (I can imagine why they think they want it to work this way, because it gives you a fighting chance again non-0-terminated source strings, but it's just never going to work properly if you've only got one size argument.)

Using strlcpy, by contrast, is simplicity itself.

About 99% of the time when you're using strlcpy (and strlcat), you can just do your calls, passing the same size value into each one (how convenient), then check the length of the result using strlen. Is it one less than the size of the buffer? Yes? Then assume there's an overflow, and disregard the result, assuming you even care about that. This is very straightforward to do, and (unlike this _s junk) doesn't require you to go updating counts or checking maximum values or any of that error-prone nonsense. Just one check at the end, rather than a bunch of updates and stuff scattered all through your string code.

strlcpy! Just say yes!

As far as I'm aware Ulrich Drepper hates strcpy_s just as much as everyone else does. Certainly glibc had no plans to implement it when last I checked.
Whatever. Ulrich Drepper is/was an asshat for numerous reasons but was not the only one that was not happy with strlcpy. The best part is that as of a year ago, OpenSSH itself still contained buggy usages of strlcpy, and at least one with a security problem.

I agree that the _s functions API are crap and quite bizarre, notice I did not say they weren't, but that doesn't mean another flawed solution should have been chosen instead.

It's a very rare situation in which truncation is worse than a buffer overflow. I'd also bet that erasing the destination string is more liable to cause problems than truncating it. For example, the programmer might have pointers to locations in the destination string passed to str*cat. All of a sudden, these pointers are to garbage data.

strlcpy's behavior is the same as snprintf: return what the length would have been if there was enough room. That way one can recover from the error and realloc enough space. C programmers are used to this pattern.