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

Re: [leafnode-list] [ANNOUNCE:] leafnode-1.9.12



krasel@xxxxxxxxxxxxxxxxxxxxxxxxxxxx (Cornelius Krasel) writes:

> Bruno Rohee wrote:
> 
> > Second thought on the problem : why not having in miscutils.c
> > 
> > [ ... ]
> >
> > So platform having snprintf() will use theirs and those who haven't will
> > use sprintf().
> 
> Sure, that was what I was thinking of. It is actually already the same
> with strdup().
> 
> I put the following into miscutil.c; please have a short look and check
> whether it is correct:
> 
> #ifndef HAVE_SNPRINTF
> int snprintf(char *str, size_t n, const char *fmt, ...) {
>     int rval;
>     va_list ap;
> 
>     va_start(ap, fmt);
>     rval = vsprintf(str, fmt, ap);
>     if ( strlen(str) > n ) {
>     ^^^^^^^^^^^^^^^^^^^^^^^^
>         syslog( LOG_NOTICE, "snprintf buffer overflow" );
>         str[n] = '\0';
>     }
>     va_end(ap);
> 
>     return rval;
> }
> #endif

Well, it turns out that in the line I marked above, your test will not
prevent segmentation faults, unfortuntately.  Suppose that the
function is called like this:

   char buffer[10];
   char *whatever = "something";
   int result = snprintf(buffer, sizeof(buffer) - 1,
                         "12345678901234567890%s", whatever);

In this case, `buffer' will overflow and probably cause some kind of
stack or data fault before your `strlen' test ever takes place.

If it's important to have such a test, then you should either
`vsprintf' into a huge temporary buffer first, or else use something
other than `vsprintf' which can dynamically allocate its result.  Even
using a huge temporary buffer is no guaranty, however, because your
idea of "huge" might still end up being smaller than someone else's
idea of a reasonable set of arguments for the function.

As for a sprintf-like something that dynamically allocates, I wrote
something like that eons ago ... I'll see if I can find it.  Or
perhaps there's now something similar in the public domain.  I'll
check.

-- 
 Lloyd Zusman
 ljz@xxxxxxxxxx

-- 
leafnode-list@xxxxxxxxxxxxxxxxxxxxxxxxxxxx -- mailing list for leafnode
To unsubscribe, send mail with "unsubscribe" in the subject to the list