Re: [PATCH v2] staging/wlan-ng: remove strcpy() use in favor of strscpy()

From: Dan Carpenter
Date: Fri Oct 13 2023 - 04:39:31 EST


On Thu, Oct 12, 2023 at 05:01:57PM +0300, Calvince Otieno wrote:
> In response to the suggestion by Dan Carpenter on the initial patch,
> this patch provides a correct usage of the strscpy() in place of the
> current strcpy() implementation.
>
> strscpy() copies characters from the source buffer to the destination
> buffer until one of the following conditions is met:
> - null-terminator ('\0') is encountered in the source string.
> - specified maximum length of the destination buffer is reached.
> - source buffer is exhausted.
> Example:
> char dest[11];
> const char *PRISM2_USB_FWFILE = "prism2_ru.fw";
> strscpy(dest, PRISM2_USB_FWFILE, sizeof(dest));
>
> In this case, strscpy copies the first 10 characters of src into dest
> and add a null-terminator. dest will then contain "prism2_ru.f" with
> proper null-termination.
>
> Since the specified length of the dest buffer is not derived from the
> dest buffer itself and rather form plug length (s3plug[i].len),
> replacing strcpy() with strscpy() is a better option because it will
> ensures that the destination string is always properly terminated.

Ok, the original code also ensured that the destination string was NUL
terminated.

Here is what I want this commit message to look like:
===
Checkpatch encourages everyone to use strscpy() instead of strncpy().
The advantages are that it always adds a NUL terminator and it prevents
a read overflow if the src string is not properly terminated. One
potential disadvantage is that it doesn't zero pad the string like
strncpy() does.

In this code, strscpy() and strncpy() are equivalent and it does not
affect runtime behavior. The string is zeroed on the line before
using memset(). The resulting string was always NUL terminated and
PRISM2_USB_FWFILE is string literal "prism2_ru.fw" so it's NUL
terminated.

However, even though using strscpy() does not fix any bugs, it's
still nicer and makes checkpatch happy.
===

>
> Signed-off-by: Calvince Otieno <calvncce@xxxxxxxxx>
> ---

v2: Update the commit message. Remove the " - 1" from the strcpy().

regards,
dan carpenter