tech-pkg archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: Theo chiming in on strlcpy



In article <20131222200544.GA15715%weiss.in-berlin.de@localhost>,
Holger Weiss  <lists%jhweiss.de@localhost> wrote:
>* Marc Espie <espie%nerim.net@localhost> [2013-12-22 00:54]:
>> On Sat, Dec 21, 2013 at 03:43:20PM -0800, John Nemeth wrote:
>> >      All my code either verify that it will fit the destination
>> > string before hand, or use strn* and deals properly with potential
>> > truncation.  Overruning a string isn't the only thing that causes
>> > security problems.  Truncation is quite capable of doing it as
>> > well.  At the very least, the app won't behave properly.  Once you
>> > acknowlege this, strl* buys you nothing over strn* or just plain
>> > str* with length calculation done before hand.
>> 
>> Okay, show me your code.
>
>    static char *
>    concat(const char *s1, const char *s2)
>    {
>        size_t l1 = strlen(s1);
>        size_t l2 = strlen(s2);
>        size_t size;
>
>        if (((size = l1 + l2) <= l1 && l2 != 0) || ++size == 0)
>            abort(); /* Handle `size_t' overflow. */
>        return strcat(strcpy(xmalloc(size), s1), s2);
>    }
>
>(Yes, with pre-calculated lengths, you could use memcpy(3) instead of
>the str* functions, trading readability a bit.  And yes, depending on
>context, you want to use a variant that allows for limiting the size.)
>
>Actually, the strl* functions can be used to implement stuff like this
>slightly nicer, which is why I like them myself.  The problem is that
>they tend to be advocated not as a prettier way to implement sane code,
>but as a critical tool for replacing arbitrary str* calls in a
>quick'n'dirty manner, which is a rationale that is easy to argue
>against.

Easier:

static char *
concat(const char *s1, const char *s2) {
        char *p;
        return asprintf(&p, "%s%s", p1, p2) == -1 ? NULL : p;
}

christos



Home | Main Index | Thread Index | Old Index