1 /* 2 * Copyright (c) 2000-2001 Sendmail, Inc. and its suppliers. 3 * All rights reserved. 4 * Copyright (c) 1990, 1993 5 * The Regents of the University of California. All rights reserved. 6 * 7 * This code is derived from software contributed to Berkeley by 8 * Chris Torek. 9 * 10 * By using this file, you agree to the terms and conditions set 11 * forth in the LICENSE file which can be found at the top level of 12 * the sendmail distribution. 13 */ 14 15 #pragma ident "%Z%%M% %I% %E% SMI" 16 17 #include <sm/gen.h> 18 SM_RCSID("@(#)$Id: snprintf.c,v 1.24 2006/10/12 21:50:10 ca Exp $") 19 #include <limits.h> 20 #include <sm/varargs.h> 21 #include <sm/io.h> 22 #include <sm/string.h> 23 #include "local.h" 24 25 /* 26 ** SM_SNPRINTF -- format a string to a memory location of restricted size 27 ** 28 ** Parameters: 29 ** str -- memory location to place formatted string 30 ** n -- size of buffer pointed to by str, capped to 31 ** a maximum of INT_MAX 32 ** fmt -- the formatting directives 33 ** ... -- the data to satisfy the formatting 34 ** 35 ** Returns: 36 ** Failure: -1 37 ** Success: number of bytes that would have been written 38 ** to str, not including the trailing '\0', 39 ** up to a maximum of INT_MAX, as if there was 40 ** no buffer size limitation. If the result >= n 41 ** then the output was truncated. 42 ** 43 ** Side Effects: 44 ** If n > 0, then between 0 and n-1 bytes of formatted output 45 ** are written into 'str', followed by a '\0'. 46 */ 47 48 int 49 #if SM_VA_STD 50 sm_snprintf(char *str, size_t n, char const *fmt, ...) 51 #else /* SM_VA_STD */ 52 sm_snprintf(str, n, fmt, va_alist) 53 char *str; 54 size_t n; 55 char *fmt; 56 va_dcl 57 #endif /* SM_VA_STD */ 58 { 59 int ret; 60 SM_VA_LOCAL_DECL 61 SM_FILE_T fake; 62 63 /* While snprintf(3) specifies size_t stdio uses an int internally */ 64 if (n > INT_MAX) 65 n = INT_MAX; 66 SM_VA_START(ap, fmt); 67 68 /* XXX put this into a static? */ 69 fake.sm_magic = SmFileMagic; 70 fake.f_file = -1; 71 fake.f_flags = SMWR | SMSTR; 72 fake.f_cookie = &fake; 73 fake.f_bf.smb_base = fake.f_p = (unsigned char *)str; 74 fake.f_bf.smb_size = fake.f_w = n ? n - 1 : 0; 75 fake.f_timeout = SM_TIME_FOREVER; 76 fake.f_timeoutstate = SM_TIME_BLOCK; 77 fake.f_close = NULL; 78 fake.f_open = NULL; 79 fake.f_read = NULL; 80 fake.f_write = NULL; 81 fake.f_seek = NULL; 82 fake.f_setinfo = fake.f_getinfo = NULL; 83 fake.f_type = "sm_snprintf:fake"; 84 ret = sm_io_vfprintf(&fake, SM_TIME_FOREVER, fmt, ap); 85 if (n > 0) 86 *fake.f_p = '\0'; 87 SM_VA_END(ap); 88 return ret; 89 } 90