xref: /freebsd/contrib/sendmail/libsm/wsetup.c (revision c17d43407fe04133a94055b0dbc7ea8965654a9f)
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 #include <sm/gen.h>
16 SM_RCSID("@(#)$Id: wsetup.c,v 1.19 2001/09/11 04:04:49 gshapiro Exp $")
17 #include <stdlib.h>
18 #include <errno.h>
19 #include <sm/io.h>
20 #include "local.h"
21 
22 /*
23 **  SM_WSETUP -- check writting 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 			fp->f_flags &= ~(SMRD|SMFEOF);
59 			fp->f_r = 0;
60 			fp->f_p = fp->f_bf.smb_base;
61 		}
62 		fp->f_flags |= SMWR;
63 	}
64 
65 	/* Make a buffer if necessary, then set w. */
66 	if (fp->f_bf.smb_base == NULL)
67 		sm_makebuf(fp);
68 	if (fp->f_flags & SMLBF)
69 	{
70 		/*
71 		**  It is line buffered, so make lbfsize be -bufsize
72 		**  for the sm_putc() macro.  We will change lbfsize back
73 		**  to 0 whenever we turn off SMWR.
74 		*/
75 
76 		fp->f_w = 0;
77 		fp->f_lbfsize = -fp->f_bf.smb_size;
78 	}
79 	else
80 		fp->f_w = fp->f_flags & SMNBF ? 0 : fp->f_bf.smb_size;
81 	return 0;
82 }
83