1 /* GNU Mailutils -- a suite of utilities for electronic mail
2    Copyright (C) 2009-2021 Free Software Foundation, Inc.
3 
4    This library is free software; you can redistribute it and/or modify
5    it under the terms of the GNU Lesser General Public License as published by
6    the Free Software Foundation; either version 3, or (at your option)
7    any later version.
8 
9    This library is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU Lesser General Public License for more details.
13 
14    You should have received a copy of the GNU Lesser General Public License
15    along with GNU Mailutils.  If not, see <http://www.gnu.org/licenses/>. */
16 
17 #ifdef HAVE_CONFIG_H
18 # include <config.h>
19 #endif
20 #include <string.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <fcntl.h>
24 
25 #include <errno.h>
26 #include <mailutils/types.h>
27 #include <mailutils/stream.h>
28 #include <mailutils/sys/stream.h>
29 #include <mailutils/sys/file_stream.h>
30 
31 int
mu_stdio_stream_create(mu_stream_t * pstream,int fd,int flags)32 mu_stdio_stream_create (mu_stream_t *pstream, int fd, int flags)
33 {
34   int rc;
35   char *filename;
36   mu_stream_t transport;
37   int need_cache;
38   struct _mu_file_stream *fstr;
39 
40   switch (fd)
41     {
42     case MU_STDIN_FD:
43       flags |= MU_STREAM_READ;
44       break;
45 
46     case MU_STDOUT_FD:
47     case MU_STDERR_FD:
48       flags |= MU_STREAM_WRITE;
49     }
50 
51   need_cache = flags & MU_STREAM_SEEK;
52   if (need_cache && (flags & MU_STREAM_WRITE))
53     /* Write caches are not supported */
54     return EINVAL;
55 
56   if (flags & MU_STREAM_READ)
57     filename = "<stdin>";
58   else
59     filename = "<stdout>";
60 
61   /* Create transport stream. */
62   rc = _mu_file_stream_create (&fstr, sizeof (*fstr),
63 			       filename, fd, flags & ~MU_STREAM_SEEK);
64   if (rc)
65     return rc;
66   fstr->stream.flags |= _MU_STR_OPEN;
67   fstr->stream.open = NULL;
68   transport = (mu_stream_t) fstr;
69   mu_stream_set_buffer (transport, mu_buffer_line, 0);
70 
71   /* Wrap it in cache, if required */
72   if (need_cache)
73     {
74       mu_stream_t str;
75       rc = mu_rdcache_stream_create (&str, transport, flags);
76       mu_stream_unref (transport);
77       if (rc)
78 	return rc;
79       transport = str;
80     }
81 
82   *pstream = transport;
83   return 0;
84 }
85 
86