xref: /freebsd/contrib/sendmail/libsm/wsetup.c (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
1 /*
2  * Copyright (c) 2000-2002 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>
16 SM_RCSID("@(#)$Id: wsetup.c,v 1.21 2013-11-22 20:51:44 ca Exp $")
17 #include <stdlib.h>
18 #include <errno.h>
19 #include <sm/io.h>
20 #include "local.h"
21 
22 /*
23 **  SM_WSETUP -- check writing is safe
24 **
25 **  Various output routines call wsetup to be sure it is safe to write,
26 **  because either flags does not include SMMWR, or buf is NULL.
27 **  Used in the macro "cantwrite" found in "local.h".
28 **
29 **	Parameters:
30 **		fp -- the file pointer
31 **
32 **	Results:
33 **		Failure: SM_IO_EOF and sets errno
34 **		Success: 0 (zero)
35 */
36 
37 int
38 sm_wsetup(fp)
39 	register SM_FILE_T *fp;
40 {
41 	/* make sure stdio is set up */
42 	if (!Sm_IO_DidInit)
43 		sm_init();
44 
45 	/* If we are not writing, we had better be reading and writing. */
46 	if ((fp->f_flags & SMWR) == 0)
47 	{
48 		if ((fp->f_flags & SMRW) == 0)
49 		{
50 			errno = EBADF;
51 			return SM_IO_EOF;
52 		}
53 		if (fp->f_flags & SMRD)
54 		{
55 			/* clobber any ungetc data */
56 			if (HASUB(fp))
57 				FREEUB(fp);
58 
59 			/* discard read buffer */
60 			fp->f_flags &= ~(SMRD|SMFEOF);
61 			fp->f_r = 0;
62 			fp->f_p = fp->f_bf.smb_base;
63 		}
64 		fp->f_flags |= SMWR;
65 	}
66 
67 	/* Make a buffer if necessary, then set w. */
68 	if (fp->f_bf.smb_base == NULL)
69 		sm_makebuf(fp);
70 	if (fp->f_flags & SMLBF)
71 	{
72 		/*
73 		**  It is line buffered, so make lbfsize be -bufsize
74 		**  for the sm_putc() macro.  We will change lbfsize back
75 		**  to 0 whenever we turn off SMWR.
76 		*/
77 
78 		fp->f_w = 0;
79 		fp->f_lbfsize = -fp->f_bf.smb_size;
80 	}
81 	else
82 		fp->f_w = fp->f_flags & SMNBF ? 0 : fp->f_bf.smb_size;
83 	return 0;
84 }
85