fetchmail-friends
[Top] [All Lists]

Re: [fetchmail][PATCH] general cleanup and anti-format-string patch

2001-06-24 08:27:36
"Eric S. Raymond" <esr(_at_)thyrsus(_dot_)com> writes:

Todd Sabin <tas(_at_)webspan(_dot_)net>:
Your usage of strncat is wrong.  Don't feel bad, though; nearly
everyone misuses it the same way.  strncat is one of the worst
designed apis in existence.  I'd suggest not using it at all.

Are you planning to send a patch to address this claim?


Sorry, no.  I don't even have the version of fetchmail against which
the first patch is supposed to be applied.  But here's the longer
version of why strncat sucks:

The natural way to call it is

strncat (buf, str, sizeof (buf));

but this is wrong because the third arg is the number of chars to
append, not the size of the buffer.  So, what you "obviously" need
to do is

strncat (buf, str, sizeof (buf) - strlen (buf));

except that this is still wrong, because the number of characters
to append doesn't include the terminating null, so you can still
overrun by one byte.  So the really correct usage is

strncat (buf, str, sizeof (buf) - strlen (buf) -1);

at which point, you realize you might just as well do

strncpy (buf+strlen (buf), str, sizeof (buf) - strlen (buf) - 1);
buf[sizeof (buf) -1] = 0;

because at least then people will understand what you've done.
Sometimes, you can just use snprintf and avoid the headaches.

Thank god for the standard C library!  cough.


Speaking of the trouble of doing string manipulation properly in C,
one of the messages a bit ago was mentioning python and almost sounded
like fetchmail might be rewritten it in.  Any hope of that being true?

I'm toying with the idea.

Consider this to be encouragement.

A couple of times in the past, I've sat down to try to review
fetchmail for these kinds of overflows, etc.  But first I wanted to
make sure it still fetched my mail for me.  The first time, I ended up
fixing problems with SIGCHLD being delivered at the wrong time which
made plugins not work right.  The next time, I ended up debugging
problems with the new-fangled plugin support doing string manipulation
wrong.  The time after that SIGCHLD was being delivered at an
unexpected time again.  I just gave up at that point and went back to
5.3.5.

In other words, before I could try to look for problems which really
only happen in C, I was wasting even more time fixing yet other
problems that pretty much only happen in C.

I'm now writing a mini-fetchmail just for myself in, of all things,
lisp.  :) :) :)

But I'd probably give that up and come back to fetchmail if it were
rewritten in something (anything) other than C/C++.


Todd