Re: [RFC] strcpys(): New function for copying strings safely

From: Alejandro Colomar (man-pages)
Date: Mon Jun 28 2021 - 08:00:28 EST


On 6/28/21 1:32 PM, Alejandro Colomar (man-pages) wrote:

The other use is where you want a sequence of:
    len *= str_copy(dest + len, dest_len - len, src);
But don't really want to test for overflow after each call.

This is a legitimate use of strscpy().  Please, add it to glibc, as there is no libc function to do that.


In this case returning the buffer length (including the added
'\0' on truncation works quite nicely.
No chance of writing outside the buffer, safe truncation and
a simple 'len == dest_len' check for overflow.

OTOH there are already too many string copy functions.

There are, but because the standard ones don't serve all purposes correctly, so people need to develop their own.  If libc provided the necessary functions, less custom string copy functions would be necessary, as Christoph said a long time ago, which is a good thing.

As I see it, there are the following, each of which has its valid usage:

strcpy(3):
    known input && known buffer
strncpy(3):
    not for C strings; only for fixed width buffers of characters!
strlcpy)3bsd):
    known input && unknown buffer
    Given that performance-wise it's similar to strscpy(),
    it should probably always be replaced by strscpy().
strscpy():
    unknown input && truncation is silently ignored
    Except for performance-critical applications,
    this call may replace strcpy(3), to add some extra safety.
strcpys():
    unknown input && truncation may be an error (or not).
    This call can replace strscpy() in most cases,
    simplifying usage.
    The only case I can see that strscpy() is superior
    is for chains of strscpy(), where I'd only use strcpys()
    in the last one (if any strscpy() in the chain has been
    trunncated, so will the last strcpys() (unless it's "")).



BTW, for chains of str_cpy(), a strscat() and a strcats() function should probably replace chained strcpy()s, so it would be something like:

l = strscpy(n, dest, src);
l = strscat(n - l, dest + l, src2);
l = strscat(n - l, dest + l, src3);
...
if (strcats(n - l, dest + l, srcN, NULL))
goto handle_truncation_or_error;

And the user should make sure that srcN is not "" unless he doesn't care about truncation. Otherwise, check at every step.

I'll send my source code for strscat and strcats, if strscpy and strcpys are considered for addition.


--
Alejandro Colomar
Linux man-pages comaintainer; https://www.kernel.org/doc/man-pages/
http://www.alejandro-colomar.es/