/* $OpenBSD: strlcat.c,v 1.15 2015/03/02 21:41:08 millert Exp $ */12/*3* SPDX-License-Identifier: ISC4*5* Copyright (c) 1998, 2015 Todd C. Miller <[email protected]>6*7* Permission to use, copy, modify, and distribute this software for any8* purpose with or without fee is hereby granted, provided that the above9* copyright notice and this permission notice appear in all copies.10*11* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES12* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF13* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR14* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES15* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN16* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF17* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.18*/1920#include <stdio.h>21#include <string.h>2223#include <ssp/string.h>2425/*26* Appends src to string dst of size dsize (unlike strncat, dsize is the27* full size of dst, not space left). At most dsize-1 characters28* will be copied. Always NUL terminates (unless dsize <= strlen(dst)).29* Returns strlen(src) + MIN(dsize, strlen(initial dst)).30* If retval >= dsize, truncation occurred.31*/32size_t33__strlcat_chk(char * __restrict dst, const char * __restrict src, size_t dsize,34size_t dbufsize)35{36const char *odst = dst;37const char *osrc = src;38size_t n = dsize;39size_t dlen;4041if (dsize > dbufsize)42__chk_fail();4344/* Find the end of dst and adjust bytes left but don't go past end. */45while (n-- != 0 && *dst != '\0') {46dst++;47}4849dlen = dst - odst;50n = dsize - dlen;5152if (n-- == 0)53return (dlen + strlen(src));54while (*src != '\0') {55if (n != 0) {56if (dbufsize-- == 0)57__chk_fail();58*dst++ = *src;59n--;60}6162src++;63}6465if (dbufsize-- == 0)66__chk_fail();67*dst = '\0';68return (dlen + (src - osrc)); /* count does not include NUL */69}707172