1/*
2 * Copyright (c) 2000-2001 Proofpoint, 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#include <sm/gen.h>
16SM_RCSID("@(#)$Id: snprintf.c,v 1.25 2013-11-22 20:51:43 ca Exp $")
17#include <limits.h>
18#include <sm/varargs.h>
19#include <sm/io.h>
20#include <sm/string.h>
21#include "local.h"
22
23/*
24**  SM_SNPRINTF -- format a string to a memory location of restricted size
25**
26**	Parameters:
27**		str -- memory location to place formatted string
28**		n -- size of buffer pointed to by str, capped to
29**			a maximum of INT_MAX
30**		fmt -- the formatting directives
31**		... -- the data to satisfy the formatting
32**
33**	Returns:
34**		Failure: -1
35**		Success: number of bytes that would have been written
36**			to str, not including the trailing '\0',
37**			up to a maximum of INT_MAX, as if there was
38**			no buffer size limitation.  If the result >= n
39**			then the output was truncated.
40**
41**	Side Effects:
42**		If n > 0, then between 0 and n-1 bytes of formatted output
43**		are written into 'str', followed by a '\0'.
44*/
45
46int
47#if SM_VA_STD
48sm_snprintf(char *str, size_t n, char const *fmt, ...)
49#else /* SM_VA_STD */
50sm_snprintf(str, n, fmt, va_alist)
51	char *str;
52	size_t n;
53	char *fmt;
54	va_dcl
55#endif /* SM_VA_STD */
56{
57	int ret;
58	SM_VA_LOCAL_DECL
59	SM_FILE_T fake;
60
61	/* While snprintf(3) specifies size_t stdio uses an int internally */
62	if (n > INT_MAX)
63		n = INT_MAX;
64	SM_VA_START(ap, fmt);
65
66	/* XXX put this into a static? */
67	fake.sm_magic = SmFileMagic;
68	fake.f_file = -1;
69	fake.f_flags = SMWR | SMSTR;
70	fake.f_cookie = &fake;
71	fake.f_bf.smb_base = fake.f_p = (unsigned char *)str;
72	fake.f_bf.smb_size = fake.f_w = n ? n - 1 : 0;
73	fake.f_timeout = SM_TIME_FOREVER;
74	fake.f_timeoutstate = SM_TIME_BLOCK;
75	fake.f_close = NULL;
76	fake.f_open = NULL;
77	fake.f_read = NULL;
78	fake.f_write = NULL;
79	fake.f_seek = NULL;
80	fake.f_setinfo = fake.f_getinfo = NULL;
81	fake.f_type = "sm_snprintf:fake";
82	ret = sm_io_vfprintf(&fake, SM_TIME_FOREVER, fmt, ap);
83	if (n > 0)
84		*fake.f_p = '\0';
85	SM_VA_END(ap);
86	return ret;
87}
88