/*
 * Copyright (c) 2000-2002, 2004, 2005 Sendmail, Inc. and its suppliers.
 *      All rights reserved.
 * Copyright (c) 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Chris Torek.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: wsetup.c,v 1.15 2005/01/17 21:35:22 ca Exp $")
#include "sm/error.h"
#include "sm/io.h"
#include "io-int.h"

/*
**  SM_WSETUP -- check whether writing is safe
**
**  Various output routines call wsetup to be sure it is safe to write,
**  because either flags does not include SMMWR, or buf is NULL.
**  Used in the macro "cantwrite" found in "io-int.h".
**
**	Parameters:
**		fp -- the file pointer
**
**	Results:
**		usual sm_error code
*/

sm_ret_T
sm_wsetup(sm_file_T *fp)
{
	/* If we are not writing, we had better be reading and writing. */
	if ((f_flags(*fp) & SMWR) == 0)
	{
		if ((f_flags(*fp) & SMRW) == 0)
			return sm_error_perm(SM_EM_IO, EBADF);
		SM_IO_TO_WR(fp);
		if (f_flags(*fp) & SMRD)
			f_flags(*fp) &= ~(SMRD|SMFEOF);
		f_flags(*fp) |= SMWR;
	}

	/*
	**  Make a buffer if necessary, then set w.
	**  Notice: the result of sm_makefilebuf() is ignored since it is
	**  indirectly communicated via f_flags: SMNBUF (which might be
	**  set by other means).
	*/

	if (f_bfbase(*fp) == NULL)
	{
		(void) sm_makefilebuf(fp);
		f_w(*fp) = f_flags(*fp) & SMNBF ? 0 : f_bfsize(*fp);
	}
	else if (!sm_io_double(fp))
		f_w(*fp) = f_flags(*fp) & SMNBF ? 0 : f_bfsize(*fp);
	return SM_SUCCESS;
}


syntax highlighted by Code2HTML, v. 0.9.1