21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Unfortunately, strlcpy( ) and strlcat( ) are not available on all platforms; at<br />

present, they seem to be available only on Darwin, FreeBSD, NetBSD, and Open-<br />

BSD. Fortunately, they are easy to implement yourself—but you don’t have to,<br />

because we provide implementations here:<br />

#include <br />

#include <br />

size_t strlcpy(char *dst, const char *src, size_t size) {<br />

char *dstptr = dst;<br />

size_t tocopy = size;<br />

const char *srcptr = src;<br />

if (tocopy && --tocopy) {<br />

do {<br />

if (!(*dstptr++ = *srcptr++)) break;<br />

} while (--tocopy);<br />

}<br />

if (!tocopy) {<br />

if (size) *dstptr = 0;<br />

while (*srcptr++);<br />

}<br />

return (srcptr - src - 1);<br />

}<br />

size_t strlcat(char *dst, const char *src, size_t size) {<br />

char *dstptr = dst;<br />

size_t dstlen, tocopy = size;<br />

const char *srcptr = src;<br />

while (tocopy-- && *dstptr) dstptr++;<br />

dstlen = dstptr - dst;<br />

if (!(tocopy = size - dstlen)) return (dstlen + strlen(src));<br />

while (*srcptr) {<br />

if (tocopy != 1) {<br />

*dstptr++ = *srcptr;<br />

tocopy--;<br />

}<br />

srcptr++;<br />

}<br />

*dstptr = 0;<br />

return (dstlen + (srcptr - src));<br />

}<br />

As part of its security push, Microsoft has developed a new set of string-handling functions<br />

for C and C++ that are defined in the header file strsafe.h. The new functions handle<br />

both ANSI and Unicode character sets, and each function is available in byte count<br />

and character count versions. For more information regarding using strsafe.h functions<br />

in your Windows programs, visit the Microsoft Developer’s Network (MSDN) reference<br />

for strsafe.h.<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.<br />

Preventing Buffer Overflows | 81

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!