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