1 /* iobuf.c - File Handling for OpenPGP.
2 * Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2006, 2007, 2008,
3 * 2009, 2010, 2011 Free Software Foundation, Inc.
4 * Copyright (C) 2015, 2023 g10 Code GmbH
6 * This file is part of GnuPG.
8 * This file is free software; you can redistribute it and/or modify
9 * it under the terms of either
11 * - the GNU Lesser General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at
13 * your option) any later version.
17 * - the GNU General Public License as published by the Free
18 * Software Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * or both in parallel, as here.
23 * This file is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
28 * You should have received a copy of the GNU General Public License
29 * along with this program; if not, see <https://www.gnu.org/licenses/>.
30 * SPDX-License-Identifier: (LGPL-3.0-or-later OR GPL-2.0-or-later)
39 #include <sys/types.h>
43 #ifdef HAVE_W32_SYSTEM
44 # ifdef HAVE_WINSOCK2_H
45 # include <winsock2.h>
52 #endif /* __riscos__ */
60 /*-- Begin configurable part. --*/
62 /* The standard size of the internal buffers. */
63 #define DEFAULT_IOBUF_BUFFER_SIZE (64*1024)
65 /* To avoid a potential DoS with compression packets we better limit
66 the number of filters in a chain. */
67 #define MAX_NESTING_FILTER 64
69 /* The threshold for switching to use external buffers directly
70 instead of the internal buffers. */
71 #define IOBUF_ZEROCOPY_THRESHOLD_SIZE 1024
73 /*-- End configurable part. --*/
75 /* The size of the iobuffers. This can be changed using the
76 * iobuf_set_buffer_size function. */
77 static unsigned int iobuf_buffer_size = DEFAULT_IOBUF_BUFFER_SIZE;
80 #ifdef HAVE_W32_SYSTEM
81 # define FD_FOR_STDIN (GetStdHandle (STD_INPUT_HANDLE))
82 # define FD_FOR_STDOUT (GetStdHandle (STD_OUTPUT_HANDLE))
83 #else /*!HAVE_W32_SYSTEM*/
84 # define FD_FOR_STDIN (0)
85 # define FD_FOR_STDOUT (1)
86 #endif /*!HAVE_W32_SYSTEM*/
89 /* The context used by the file filter. */
92 gnupg_fd_t fp; /* Open file pointer or handle. */
97 int print_only_name; /* Flags indicating that fname is not a real file. */
98 char peeked[32]; /* Read ahead buffer. */
99 byte npeeked; /* Number of bytes valid in peeked. */
100 byte upeeked; /* Number of bytes used from peeked. */
101 char fname[1]; /* Name of the file. */
104 /* The context used by the estream filter. */
107 estream_t fp; /* Open estream handle. */
111 int use_readlimit; /* Take care of the readlimit. */
112 size_t readlimit; /* Number of bytes left to read. */
113 int print_only_name; /* Flags indicating that fname is not a real file. */
114 char fname[1]; /* Name of the file. */
115 } file_es_filter_ctx_t;
118 /* Object to control the "close cache". */
121 struct close_cache_s *next;
125 typedef struct close_cache_s *close_cache_t;
126 static close_cache_t close_cache;
128 int iobuf_debug_mode;
131 #ifdef HAVE_W32_SYSTEM
138 int print_only_name; /* Flag indicating that fname is not a real file. */
139 char fname[1]; /* Name of the file */
142 #endif /*HAVE_W32_SYSTEM*/
144 /* The first partial length header block must be of size 512 to make
145 * it easier (and more efficient) we use a min. block size of 512 for
146 * all chunks (but the last one) */
147 #define OP_MIN_PARTIAL_CHUNK 512
148 #define OP_MIN_PARTIAL_CHUNK_2POW 9
150 /* The context we use for the block filter (used to handle OpenPGP
151 length information header). */
157 int partial; /* 1 = partial header, 2 in last partial packet. */
158 char *buffer; /* Used for partial header. */
159 size_t buflen; /* Used size of buffer. */
160 int first_c; /* First character of a partial header (which is > 0). */
166 /* Local prototypes. */
167 static int underflow (iobuf_t a, int clear_pending_eof);
168 static int underflow_target (iobuf_t a, int clear_pending_eof, size_t target);
169 static int translate_file_handle (int fd, int for_write);
171 /* Sends any pending data to the filter's FILTER function. Note: this
172 works on the filter and not on the whole pipeline. That is,
173 iobuf_flush doesn't necessarily cause data to be written to any
174 underlying file; it just causes any data buffered at the filter A
175 to be sent to A's filter function.
177 If A is a IOBUF_OUTPUT_TEMP filter, then this also enlarges the
178 buffer by iobuf_buffer_size.
180 May only be called on an IOBUF_OUTPUT or IOBUF_OUTPUT_TEMP filters. */
181 static int filter_flush (iobuf_t a);
185 /* This is a replacement for strcmp. Under W32 it does not
186 distinguish between backslash and slash. */
188 fd_cache_strcmp (const char *a, const char *b)
190 #ifdef HAVE_DOSISH_SYSTEM
191 for (; *a && *b; a++, b++)
193 if (*a != *b && !((*a == '/' && *b == '\\')
194 || (*a == '\\' && *b == '/')) )
197 return *(const unsigned char *)a - *(const unsigned char *)b;
199 return strcmp (a, b);
205 * Invalidate (i.e. close) a cached iobuf
208 fd_cache_invalidate (const char *fname)
215 log_debug ("fd_cache_invalidate (%s)\n", fname);
217 for (cc = close_cache; cc; cc = cc->next)
219 if (cc->fp != GNUPG_INVALID_FD && !fd_cache_strcmp (cc->fname, fname))
222 log_debug (" did (%s)\n", cc->fname);
223 #ifdef HAVE_W32_SYSTEM
224 if (!CloseHandle (cc->fp))
229 cc->fp = GNUPG_INVALID_FD;
236 /* Try to sync changes to the disk. This is to avoid data loss during
237 a system crash in write/close/rename cycle on some file
240 fd_cache_synchronize (const char *fname)
248 log_debug ("fd_cache_synchronize (%s)\n", fname);
250 for (cc=close_cache; cc; cc = cc->next )
252 if (cc->fp != GNUPG_INVALID_FD && !fd_cache_strcmp (cc->fname, fname))
255 log_debug (" did (%s)\n", cc->fname);
257 err = fsync (cc->fp);
262 #endif /*HAVE_FSYNC*/
269 direct_open (const char *fname, const char *mode, int mode700)
271 #ifdef HAVE_W32_SYSTEM
272 unsigned long da, cd, sm;
276 /* Note, that we do not handle all mode combinations */
278 /* According to the ReactOS source it seems that open() of the
279 * standard MSW32 crt does open the file in shared mode which is
280 * something new for MS applications ;-)
282 if (strchr (mode, '+'))
284 if (fd_cache_invalidate (fname))
285 return GNUPG_INVALID_FD;
286 da = GENERIC_READ | GENERIC_WRITE;
288 sm = FILE_SHARE_READ | FILE_SHARE_WRITE;
290 else if (strchr (mode, 'w'))
292 if (fd_cache_invalidate (fname))
293 return GNUPG_INVALID_FD;
296 sm = FILE_SHARE_WRITE;
302 sm = FILE_SHARE_READ;
305 /* We always use the Unicode version because it supports file names
306 * longer than MAX_PATH. (requires gpgrt 1.45) */
309 wchar_t *wfname = gpgrt_fname_to_wchar (fname);
312 hfile = CreateFileW (wfname, da, sm, NULL, cd,
313 FILE_ATTRIBUTE_NORMAL, NULL);
314 if (hfile == INVALID_HANDLE_VALUE)
316 gnupg_w32_set_errno (-1);
318 log_debug ("iobuf:direct_open '%s' CreateFile failed: %s\n",
319 fname, gpg_strerror (gpg_error_from_syserror()));
324 hfile = INVALID_HANDLE_VALUE;
329 #else /*!HAVE_W32_SYSTEM*/
332 int cflag = S_IRUSR | S_IWUSR;
335 cflag |= S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
337 /* Note, that we do not handle all mode combinations */
338 if (strchr (mode, '+'))
340 if (fd_cache_invalidate (fname))
341 return GNUPG_INVALID_FD;
344 else if (strchr (mode, 'w'))
346 if (fd_cache_invalidate (fname))
347 return GNUPG_INVALID_FD;
348 oflag = O_WRONLY | O_CREAT | O_TRUNC;
355 if (strchr (mode, 'b'))
363 /* Don't allow iobufs on directories */
364 if (!stat (fname, &buf) && S_ISDIR (buf.st_mode) && !S_ISREG (buf.st_mode))
365 return __set_errno (EISDIR);
368 return open (fname, oflag, cflag);
370 #endif /*!HAVE_W32_SYSTEM*/
375 * Instead of closing an FD we keep it open and cache it for later reuse
376 * Note that this caching strategy only works if the process does not chdir.
379 fd_cache_close (const char *fname, gnupg_fd_t fp)
384 if (!fname || !*fname)
386 #ifdef HAVE_W32_SYSTEM
392 log_debug ("fd_cache_close (%d) real\n", (int)fp);
395 /* try to reuse a slot */
396 for (cc = close_cache; cc; cc = cc->next)
398 if (cc->fp == GNUPG_INVALID_FD && !fd_cache_strcmp (cc->fname, fname))
402 log_debug ("fd_cache_close (%s) used existing slot\n", fname);
408 log_debug ("fd_cache_close (%s) new slot created\n", fname);
409 cc = xcalloc (1, sizeof *cc + strlen (fname));
410 strcpy (cc->fname, fname);
412 cc->next = close_cache;
417 * Do a direct_open on FNAME but first try to reuse one from the fd_cache
420 fd_cache_open (const char *fname, const char *mode)
425 for (cc = close_cache; cc; cc = cc->next)
427 if (cc->fp != GNUPG_INVALID_FD && !fd_cache_strcmp (cc->fname, fname))
429 gnupg_fd_t fp = cc->fp;
430 cc->fp = GNUPG_INVALID_FD;
432 log_debug ("fd_cache_open (%s) using cached fp\n", fname);
433 #ifdef HAVE_W32_SYSTEM
434 if (SetFilePointer (fp, 0, NULL, FILE_BEGIN) == 0xffffffff)
436 int ec = (int) GetLastError ();
437 log_error ("rewind file failed on handle %p: ec=%d\n", fp, ec);
438 gnupg_w32_set_errno (ec);
439 fp = GNUPG_INVALID_FD;
442 if (lseek (fp, 0, SEEK_SET) == (off_t) - 1)
444 log_error ("can't rewind fd %d: %s\n", fp, strerror (errno));
445 fp = GNUPG_INVALID_FD;
452 log_debug ("fd_cache_open (%s) not cached\n", fname);
453 return direct_open (fname, mode, 0);
458 file_filter (void *opaque, int control, iobuf_t chain, byte * buf,
461 file_filter_ctx_t *a = opaque;
462 gnupg_fd_t f = a->fp;
463 size_t size = *ret_len;
467 (void)chain; /* Not used. */
469 if (control == IOBUFCTRL_UNDERFLOW)
471 log_assert (size); /* We need a buffer. */
472 if (a->npeeked > a->upeeked)
474 nbytes = a->npeeked - a->upeeked;
477 memcpy (buf, a->peeked + a->upeeked, nbytes);
478 a->upeeked += nbytes;
481 else if (a->eof_seen)
486 else if (a->delayed_rc)
496 #ifdef HAVE_W32_SYSTEM
500 if (!ReadFile (f, buf, size, &nread, NULL))
502 int ec = (int) GetLastError ();
503 if (ec != ERROR_BROKEN_PIPE)
505 rc = gpg_error_from_errno (ec);
506 log_error ("%s: read error: %s (ec=%d)\n",
507 a->fname, gpg_strerror (rc), ec);
528 n = read (f, buf + nbytes, size - nbytes);
530 while (n == -1 && errno == EINTR);
537 else if (!n) /* eof */
549 rc = gpg_error_from_syserror ();
550 if (gpg_err_code (rc) != GPG_ERR_EPIPE)
551 log_error ("%s: read error: %s\n", a->fname, gpg_strerror (rc));
562 else if (control == IOBUFCTRL_FLUSH)
566 #ifdef HAVE_W32_SYSTEM
573 if (size && !WriteFile (f, p, nbytes, &n, NULL))
575 int ec = gnupg_w32_set_errno (-1);
576 rc = gpg_error_from_syserror ();
577 log_error ("%s: write error: %s (ec=%d)\n",
578 a->fname, gpg_strerror (rc), ec);
595 n = write (f, p, nbytes);
597 while (n == -1 && errno == EINTR);
604 while (n != -1 && nbytes);
607 rc = gpg_error_from_syserror ();
608 log_error ("%s: write error: %s\n", a->fname, strerror (errno));
615 else if (control == IOBUFCTRL_INIT)
624 else if (control == IOBUFCTRL_PEEK)
626 /* Peek on the input. */
627 #ifdef HAVE_W32_SYSTEM
631 if (!ReadFile (f, a->peeked, sizeof a->peeked, &nread, NULL))
633 int ec = (int) GetLastError ();
634 if (ec != ERROR_BROKEN_PIPE)
636 rc = gpg_error_from_errno (ec);
637 log_error ("%s: read error: %s (ec=%d)\n",
638 a->fname, gpg_strerror (rc), ec);
659 n = read (f, a->peeked + a->npeeked, sizeof a->peeked - a->npeeked);
661 while (n == -1 && errno == EINTR);
665 if (a->npeeked < sizeof a->peeked)
668 else if (!n) /* eof */
677 rc = gpg_error_from_syserror ();
678 if (gpg_err_code (rc) != GPG_ERR_EPIPE)
679 log_error ("%s: read error: %s\n", a->fname, gpg_strerror (rc));
685 size = a->npeeked < size? a->npeeked : size;
686 memcpy (buf, a->peeked, size);
688 rc = 0; /* Return success - the user needs to check ret_len. */
690 else if (control == IOBUFCTRL_DESC)
692 mem2str (buf, "file_filter(fd)", *ret_len);
694 else if (control == IOBUFCTRL_FREE)
696 if (f != FD_FOR_STDIN && f != FD_FOR_STDOUT)
699 log_debug ("%s: close fd/handle %d\n", a->fname, FD2INT (f));
701 fd_cache_close (a->no_cache ? NULL : a->fname, f);
703 xfree (a); /* We can free our context now. */
710 /* Similar to file_filter but using the estream system. */
712 file_es_filter (void *opaque, int control, iobuf_t chain, byte * buf,
715 file_es_filter_ctx_t *a = opaque;
717 size_t size = *ret_len;
721 (void)chain; /* Not used. */
723 if (control == IOBUFCTRL_UNDERFLOW)
725 log_assert (size); /* We need a buffer. */
731 else if (a->use_readlimit)
741 if (size > a->readlimit)
743 rc = es_read (f, buf, size, &nbytes);
746 rc = gpg_error_from_syserror ();
747 log_error ("%s: read error: %s\n", a->fname,strerror (errno));
755 a->readlimit -= nbytes;
762 rc = es_read (f, buf, size, &nbytes);
765 rc = gpg_error_from_syserror ();
766 log_error ("%s: read error: %s\n", a->fname, strerror (errno));
776 else if (control == IOBUFCTRL_FLUSH)
787 if (es_write (f, p, nbytes, &nwritten))
789 rc = gpg_error_from_syserror ();
790 log_error ("%s: write error: %s\n",
791 a->fname, strerror (errno));
802 else if (control == IOBUFCTRL_INIT)
807 else if (control == IOBUFCTRL_DESC)
809 mem2str (buf, "estream_filter", *ret_len);
811 else if (control == IOBUFCTRL_FREE)
813 if (f != es_stdin && f != es_stdout)
816 log_debug ("%s: es_fclose %p\n", a->fname, f);
821 xfree (a); /* We can free our context now. */
828 #ifdef HAVE_W32_SYSTEM
829 /* Because network sockets are special objects under Lose32 we have to
830 use a dedicated filter for them. */
832 sock_filter (void *opaque, int control, iobuf_t chain, byte * buf,
835 sock_filter_ctx_t *a = opaque;
836 size_t size = *ret_len;
842 if (control == IOBUFCTRL_UNDERFLOW)
844 log_assert (size); /* need a buffer */
854 nread = recv (a->sock, buf, size, 0);
855 if (nread == SOCKET_ERROR)
857 int ec = (int) WSAGetLastError ();
858 rc = gpg_error_from_errno (ec);
859 log_error ("socket read error: ec=%d\n", ec);
873 else if (control == IOBUFCTRL_FLUSH)
883 n = send (a->sock, p, nbytes, 0);
884 if (n == SOCKET_ERROR)
886 int ec = (int) WSAGetLastError ();
887 gnupg_w32_set_errno (ec);
888 rc = gpg_error_from_syserror ();
889 log_error ("socket write error: ec=%d\n", ec);
900 else if (control == IOBUFCTRL_INIT)
906 else if (control == IOBUFCTRL_DESC)
908 mem2str (buf, "sock_filter", *ret_len);
910 else if (control == IOBUFCTRL_FREE)
913 closesocket (a->sock);
914 xfree (a); /* we can free our context now */
918 #endif /*HAVE_W32_SYSTEM*/
921 * This is used to implement the block write mode.
922 * Block reading is done on a byte by byte basis in readbyte(),
926 block_filter (void *opaque, int control, iobuf_t chain, byte * buffer,
929 block_filter_ctx_t *a = opaque;
930 char *buf = (char *)buffer;
931 size_t size = *ret_len;
932 int c, needed, rc = 0;
935 if (control == IOBUFCTRL_UNDERFLOW)
940 log_assert (size); /* need a buffer */
941 if (a->eof) /* don't read any further */
946 { /* get the length bytes */
956 /* These OpenPGP introduced huffman like encoded length
957 * bytes are really a mess :-( */
963 else if ((c = iobuf_get (chain)) == -1)
965 log_error ("block_filter: 1st length byte missing\n");
966 rc = GPG_ERR_BAD_DATA;
983 a->size = (c - 192) * 256;
984 if ((c = iobuf_get (chain)) == -1)
987 ("block_filter: 2nd length byte missing\n");
988 rc = GPG_ERR_BAD_DATA;
1006 for (i = 0; i < 4; i++)
1007 if ((c = iobuf_get (chain)) == -1)
1010 len = ((len << 8) | c);
1014 log_error ("block_filter: invalid 4 byte length\n");
1015 rc = GPG_ERR_BAD_DATA;
1029 { /* Next partial body length. */
1030 a->size = 1 << (c & 0x1f);
1032 /* log_debug("partial: ctx=%p c=%02x size=%u\n", a, c, a->size); */
1038 while (!rc && size && a->size)
1040 needed = size < a->size ? size : a->size;
1041 c = iobuf_read (chain, p, needed);
1047 ("block_filter %p: read error (size=%lu,a->size=%lu)\n",
1048 a, (ulong) size + c, (ulong) a->size + c);
1049 rc = GPG_ERR_BAD_DATA;
1062 else if (control == IOBUFCTRL_FLUSH)
1065 { /* the complicated openpgp scheme */
1066 size_t blen, n, nbytes = size + a->buflen;
1068 log_assert (a->buflen <= OP_MIN_PARTIAL_CHUNK);
1069 if (nbytes < OP_MIN_PARTIAL_CHUNK)
1071 /* not enough to write a partial block out; so we store it */
1073 a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK);
1074 memcpy (a->buffer + a->buflen, buf, size);
1078 { /* okay, we can write out something */
1079 /* do this in a loop to use the most efficient block lengths */
1083 /* find the best matching block length - this is limited
1084 * by the size of the internal buffering */
1085 for (blen = OP_MIN_PARTIAL_CHUNK * 2,
1086 c = OP_MIN_PARTIAL_CHUNK_2POW + 1; blen <= nbytes;
1091 /* write the partial length header */
1092 log_assert (c <= 0x1f); /*;-) */
1094 iobuf_put (chain, c);
1095 if ((n = a->buflen))
1096 { /* write stuff from the buffer */
1097 log_assert (n == OP_MIN_PARTIAL_CHUNK);
1098 if (iobuf_write (chain, a->buffer, n))
1099 rc = gpg_error_from_syserror ();
1103 if ((n = nbytes) > blen)
1105 if (n && iobuf_write (chain, p, n))
1106 rc = gpg_error_from_syserror ();
1110 while (!rc && nbytes >= OP_MIN_PARTIAL_CHUNK);
1111 /* store the rest in the buffer */
1114 log_assert (!a->buflen);
1115 log_assert (nbytes < OP_MIN_PARTIAL_CHUNK);
1117 a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK);
1118 memcpy (a->buffer, p, nbytes);
1126 else if (control == IOBUFCTRL_INIT)
1129 log_debug ("init block_filter %p\n", a);
1132 else if (a->use == IOBUF_INPUT)
1133 a->count = a->size = 0;
1135 a->count = a->size; /* force first length bytes */
1140 else if (control == IOBUFCTRL_DESC)
1142 mem2str (buf, "block_filter", *ret_len);
1144 else if (control == IOBUFCTRL_FREE)
1146 if (a->use == IOBUF_OUTPUT)
1147 { /* write the end markers */
1151 /* write out the remaining bytes without a partial header
1152 * the length of this header may be 0 - but if it is
1153 * the first block we are not allowed to use a partial header
1154 * and frankly we can't do so, because this length must be
1155 * a power of 2. This is _really_ complicated because we
1156 * have to check the possible length of a packet prior
1157 * to it's creation: a chain of filters becomes complicated
1158 * and we need a lot of code to handle compressed packets etc.
1161 /* construct header */
1163 /*log_debug("partial: remaining length=%u\n", len ); */
1165 rc = iobuf_put (chain, len);
1166 else if (len < 8384)
1168 if (!(rc = iobuf_put (chain, ((len - 192) / 256) + 192)))
1169 rc = iobuf_put (chain, ((len - 192) % 256));
1172 { /* use a 4 byte header */
1173 if (!(rc = iobuf_put (chain, 0xff)))
1174 if (!(rc = iobuf_put (chain, (len >> 24) & 0xff)))
1175 if (!(rc = iobuf_put (chain, (len >> 16) & 0xff)))
1176 if (!(rc = iobuf_put (chain, (len >> 8) & 0xff)))
1177 rc = iobuf_put (chain, len & 0xff);
1180 rc = iobuf_write (chain, a->buffer, len);
1183 log_error ("block_filter: write error: %s\n",
1185 rc = gpg_error_from_syserror ();
1196 log_error ("block_filter: pending bytes!\n");
1199 log_debug ("free block_filter %p\n", a);
1200 xfree (a); /* we can free our context now */
1207 /* Change the default size for all IOBUFs to KILOBYTE. This needs to
1208 * be called before any iobufs are used and can only be used once.
1209 * Returns the current value. Using 0 has no effect except for
1210 * returning the current value. */
1212 iobuf_set_buffer_size (unsigned int kilobyte)
1216 if (!used && kilobyte)
1220 else if (kilobyte > 16*1024)
1223 iobuf_buffer_size = kilobyte * 1024;
1226 return iobuf_buffer_size / 1024;
1230 #define MAX_IOBUF_DESC 32
1232 * Fill the buffer by the description of iobuf A.
1233 * The buffer size should be MAX_IOBUF_DESC (or larger).
1234 * Returns BUF as (const char *).
1237 iobuf_desc (iobuf_t a, byte *buf)
1239 size_t len = MAX_IOBUF_DESC;
1241 if (! a || ! a->filter)
1242 memcpy (buf, "?", 2);
1244 a->filter (a->filter_ov, IOBUFCTRL_DESC, NULL, buf, &len);
1250 print_chain (iobuf_t a)
1254 for (; a; a = a->chain)
1256 byte desc[MAX_IOBUF_DESC];
1258 log_debug ("iobuf chain: %d.%d '%s' filter_eof=%d start=%d len=%d\n",
1259 a->no, a->subno, iobuf_desc (a, desc), a->filter_eof,
1260 (int) a->d.start, (int) a->d.len);
1265 iobuf_print_chain (iobuf_t a)
1272 iobuf_alloc (int use, size_t bufsize)
1275 static int number = 0;
1277 log_assert (use == IOBUF_INPUT || use == IOBUF_INPUT_TEMP
1278 || use == IOBUF_OUTPUT || use == IOBUF_OUTPUT_TEMP);
1281 log_bug ("iobuf_alloc() passed a bufsize of 0!\n");
1282 bufsize = iobuf_buffer_size;
1285 a = xcalloc (1, sizeof *a);
1287 a->d.buf = xmalloc (bufsize);
1288 a->d.size = bufsize;
1292 a->e_d.preferred = 0;
1295 a->real_fname = NULL;
1300 iobuf_close (iobuf_t a)
1303 size_t dummy_len = 0;
1306 for (; a; a = a_chain)
1308 byte desc[MAX_IOBUF_DESC];
1313 if (a->use == IOBUF_OUTPUT && (rc = filter_flush (a)))
1314 log_error ("filter_flush failed on close: %s\n", gpg_strerror (rc));
1317 log_debug ("iobuf-%d.%d: close '%s'\n",
1318 a->no, a->subno, iobuf_desc (a, desc));
1320 if (a->filter && (rc2 = a->filter (a->filter_ov, IOBUFCTRL_FREE,
1321 a->chain, NULL, &dummy_len)))
1322 log_error ("IOBUFCTRL_FREE failed on close: %s\n", gpg_strerror (rc));
1324 /* Whoops! An error occurred. Save it in RC if we haven't
1325 already recorded an error. */
1328 xfree (a->real_fname);
1331 memset (a->d.buf, 0, a->d.size); /* erase the buffer */
1340 iobuf_cancel (iobuf_t a)
1345 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1346 char *remove_name = NULL;
1349 if (a && a->use == IOBUF_OUTPUT)
1351 s = iobuf_get_real_fname (a);
1354 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1355 remove_name = xstrdup (s);
1362 /* send a cancel message to all filters */
1363 for (a2 = a; a2; a2 = a2->chain)
1367 a2->filter (a2->filter_ov, IOBUFCTRL_CANCEL, a2->chain, NULL, &dummy);
1370 rc = iobuf_close (a);
1371 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1374 /* Argg, MSDOS does not allow removing open files. So
1375 * we have to do it here */
1376 gnupg_remove (remove_name);
1378 xfree (remove_name);
1388 return iobuf_alloc (IOBUF_OUTPUT_TEMP, iobuf_buffer_size);
1392 iobuf_temp_with_content (const char *buffer, size_t length)
1397 a = iobuf_alloc (IOBUF_INPUT_TEMP, length);
1398 log_assert (length == a->d.size);
1399 /* memcpy (a->d.buf, buffer, length); */
1400 for (i=0; i < length; i++)
1401 a->d.buf[i] = buffer[i];
1409 iobuf_is_pipe_filename (const char *fname)
1411 if (!fname || (*fname=='-' && !fname[1]) )
1413 return check_special_filename (fname, 0, 1) != -1;
1418 do_open (const char *fname, int special_filenames,
1419 int use, const char *opentype, int mode700)
1423 file_filter_ctx_t *fcx;
1427 byte desc[MAX_IOBUF_DESC];
1429 log_assert (use == IOBUF_INPUT || use == IOBUF_OUTPUT);
1431 if (special_filenames
1433 && (!fname || (*fname == '-' && !fname[1])))
1435 if (use == IOBUF_INPUT)
1449 else if (special_filenames
1450 && (fd = check_special_filename (fname, 0, 1)) != -1)
1451 return iobuf_fdopen (translate_file_handle (fd, use == IOBUF_INPUT ? 0 : 1),
1455 if (use == IOBUF_INPUT)
1456 fp = fd_cache_open (fname, opentype);
1458 fp = direct_open (fname, opentype, mode700);
1459 if (fp == GNUPG_INVALID_FD)
1463 a = iobuf_alloc (use, iobuf_buffer_size);
1464 fcx = xmalloc (sizeof *fcx + strlen (fname));
1466 fcx->print_only_name = print_only;
1467 strcpy (fcx->fname, fname);
1469 a->real_fname = xstrdup (fname);
1470 a->filter = file_filter;
1472 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1474 log_debug ("iobuf-%d.%d: open '%s' desc=%s fd=%d\n",
1475 a->no, a->subno, fname, iobuf_desc (a, desc), FD2INT (fcx->fp));
1481 iobuf_open (const char *fname)
1483 return do_open (fname, 1, IOBUF_INPUT, "rb", 0);
1487 iobuf_create (const char *fname, int mode700)
1489 return do_open (fname, 1, IOBUF_OUTPUT, "wb", mode700);
1493 iobuf_openrw (const char *fname)
1495 return do_open (fname, 0, IOBUF_OUTPUT, "r+b", 0);
1500 do_iobuf_fdopen (int fd, const char *mode, int keep_open)
1504 file_filter_ctx_t *fcx;
1509 a = iobuf_alloc (strchr (mode, 'w') ? IOBUF_OUTPUT : IOBUF_INPUT,
1511 fcx = xmalloc (sizeof *fcx + 20);
1513 fcx->print_only_name = 1;
1514 fcx->keep_open = keep_open;
1515 sprintf (fcx->fname, "[fd %d]", fd);
1516 a->filter = file_filter;
1518 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1520 log_debug ("iobuf-%d.%d: fdopen%s '%s'\n",
1521 a->no, a->subno, keep_open? "_nc":"", fcx->fname);
1522 iobuf_ioctl (a, IOBUF_IOCTL_NO_CACHE, 1, NULL);
1528 iobuf_fdopen (int fd, const char *mode)
1530 return do_iobuf_fdopen (fd, mode, 0);
1534 iobuf_fdopen_nc (int fd, const char *mode)
1536 return do_iobuf_fdopen (fd, mode, 1);
1541 iobuf_esopen (estream_t estream, const char *mode, int keep_open,
1545 file_es_filter_ctx_t *fcx;
1548 a = iobuf_alloc (strchr (mode, 'w') ? IOBUF_OUTPUT : IOBUF_INPUT,
1550 fcx = xtrymalloc (sizeof *fcx + 30);
1552 fcx->print_only_name = 1;
1553 fcx->keep_open = keep_open;
1554 fcx->readlimit = readlimit;
1555 fcx->use_readlimit = !!readlimit;
1556 snprintf (fcx->fname, 30, "[fd %p]", estream);
1557 a->filter = file_es_filter;
1559 file_es_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1561 log_debug ("iobuf-%d.%d: esopen%s '%s'\n",
1562 a->no, a->subno, keep_open? "_nc":"", fcx->fname);
1568 iobuf_sockopen (int fd, const char *mode)
1571 #ifdef HAVE_W32_SYSTEM
1572 sock_filter_ctx_t *scx;
1575 a = iobuf_alloc (strchr (mode, 'w') ? IOBUF_OUTPUT : IOBUF_INPUT,
1577 scx = xmalloc (sizeof *scx + 25);
1579 scx->print_only_name = 1;
1580 sprintf (scx->fname, "[sock %d]", fd);
1581 a->filter = sock_filter;
1583 sock_filter (scx, IOBUFCTRL_INIT, NULL, NULL, &len);
1585 log_debug ("iobuf-%d.%d: sockopen '%s'\n", a->no, a->subno, scx->fname);
1586 iobuf_ioctl (a, IOBUF_IOCTL_NO_CACHE, 1, NULL);
1588 a = iobuf_fdopen (fd, mode);
1594 iobuf_ioctl (iobuf_t a, iobuf_ioctl_t cmd, int intval, void *ptrval)
1596 byte desc[MAX_IOBUF_DESC];
1598 if (cmd == IOBUF_IOCTL_KEEP_OPEN)
1600 /* Keep system filepointer/descriptor open. This was used in
1601 the past by http.c; this ioctl is not directly used
1604 log_debug ("iobuf-%d.%d: ioctl '%s' keep_open=%d\n",
1605 a ? a->no : -1, a ? a->subno : -1, iobuf_desc (a, desc),
1607 for (; a; a = a->chain)
1608 if (!a->chain && a->filter == file_filter)
1610 file_filter_ctx_t *b = a->filter_ov;
1611 b->keep_open = intval;
1614 #ifdef HAVE_W32_SYSTEM
1615 else if (!a->chain && a->filter == sock_filter)
1617 sock_filter_ctx_t *b = a->filter_ov;
1618 b->keep_open = intval;
1623 else if (cmd == IOBUF_IOCTL_INVALIDATE_CACHE)
1626 log_debug ("iobuf-*.*: ioctl '%s' invalidate\n",
1627 ptrval ? (char *) ptrval : "?");
1628 if (!a && !intval && ptrval)
1630 if (fd_cache_invalidate (ptrval))
1635 else if (cmd == IOBUF_IOCTL_NO_CACHE)
1638 log_debug ("iobuf-%d.%d: ioctl '%s' no_cache=%d\n",
1639 a ? a->no : -1, a ? a->subno : -1, iobuf_desc (a, desc),
1641 for (; a; a = a->chain)
1642 if (!a->chain && a->filter == file_filter)
1644 file_filter_ctx_t *b = a->filter_ov;
1645 b->no_cache = intval;
1648 #ifdef HAVE_W32_SYSTEM
1649 else if (!a->chain && a->filter == sock_filter)
1651 sock_filter_ctx_t *b = a->filter_ov;
1652 b->no_cache = intval;
1657 else if (cmd == IOBUF_IOCTL_FSYNC)
1659 /* Do a fsync on the open fd and return any errors to the caller
1660 of iobuf_ioctl. Note that we work on a file name here. */
1662 log_debug ("iobuf-*.*: ioctl '%s' fsync\n",
1663 ptrval? (const char*)ptrval:"<null>");
1665 if (!a && !intval && ptrval)
1667 return fd_cache_synchronize (ptrval);
1670 else if (cmd == IOBUF_IOCTL_PEEK)
1672 /* Peek at a justed opened file. Use this only directly after a
1673 * file has been opened for reading. Don't use it after you did
1674 * a seek. This works only if just file filter has been
1675 * pushed. Expects a buffer wit size INTVAL at PTRVAL and returns
1676 * the number of bytes put into the buffer. */
1678 log_debug ("iobuf-%d.%d: ioctl '%s' peek\n",
1679 a ? a->no : -1, a ? a->subno : -1, iobuf_desc (a, desc));
1680 if (a->filter == file_filter && ptrval && intval)
1682 file_filter_ctx_t *fcx = a->filter_ov;
1683 size_t len = intval;
1685 if (!file_filter (fcx, IOBUFCTRL_PEEK, NULL, ptrval, &len))
1696 * Register an i/o filter.
1699 iobuf_push_filter (iobuf_t a,
1700 int (*f) (void *opaque, int control,
1701 iobuf_t chain, byte * buf, size_t * len),
1704 return iobuf_push_filter2 (a, f, ov, 0);
1708 iobuf_push_filter2 (iobuf_t a,
1709 int (*f) (void *opaque, int control,
1710 iobuf_t chain, byte * buf, size_t * len),
1711 void *ov, int rel_ov)
1714 size_t dummy_len = 0;
1717 if (a->use == IOBUF_OUTPUT && (rc = filter_flush (a)))
1720 if (a->subno >= MAX_NESTING_FILTER)
1722 log_error ("i/o filter too deeply nested - corrupted data?\n");
1723 return GPG_ERR_BAD_DATA;
1726 /* We want to create a new filter and put it in front of A. A
1727 simple implementation would do:
1729 b = iobuf_alloc (...);
1733 This is a bit problematic: A is the head of the pipeline and
1734 there are potentially many pointers to it. Requiring the caller
1735 to update all of these pointers is a burden.
1737 An alternative implementation would add a level of indirection.
1738 For instance, we could use a pipeline object, which contains a
1739 pointer to the first filter in the pipeline. This is not what we
1742 Instead, we allocate a new buffer (B) and copy the first filter's
1743 state into that and use the initial buffer (A) for the new
1744 filter. One limitation of this approach is that it is not
1745 practical to maintain a pointer to a specific filter's state.
1752 +----------+ +----------+
1753 | filter x |--------->| filter y |---->....
1754 +----------+ +----------+
1763 +----------+ +----------+
1764 | filter w | | filter y |---->....
1765 +----------+ +----------+
1767 Note: filter x's address changed from 0x100 to 0x300, but A still
1768 points to the head of the pipeline.
1771 b = xmalloc (sizeof *b);
1772 memcpy (b, a, sizeof *b);
1773 /* fixme: it is stupid to keep a copy of the name at every level
1774 * but we need the name somewhere because the name known by file_filter
1775 * may have been released when we need the name of the file */
1776 b->real_fname = a->real_fname ? xstrdup (a->real_fname) : NULL;
1777 /* remove the filter stuff from the new stream */
1779 a->filter_ov = NULL;
1780 a->filter_ov_owner = 0;
1782 if (a->use == IOBUF_OUTPUT_TEMP)
1783 /* A TEMP filter buffers any data sent to it; it does not forward
1784 any data down the pipeline. If we add a new filter to the
1785 pipeline, it shouldn't also buffer data. It should send it
1786 downstream to be buffered. Thus, the correct type for a filter
1787 added in front of an IOBUF_OUTPUT_TEMP filter is IOBUF_OUPUT, not
1788 IOBUF_OUTPUT_TEMP. */
1790 a->use = IOBUF_OUTPUT;
1792 /* When pipeline is written to, the temp buffer's size is
1793 increased accordingly. We don't need to allocate a 10 MB
1794 buffer for a non-terminal filter. Just use the default
1796 a->d.size = iobuf_buffer_size;
1798 else if (a->use == IOBUF_INPUT_TEMP)
1799 /* Same idea as above. */
1801 a->use = IOBUF_INPUT;
1802 a->d.size = iobuf_buffer_size;
1805 /* The new filter (A) gets a new buffer.
1807 If the pipeline is an output or temp pipeline, then giving the
1808 buffer to the new filter means that data that was written before
1809 the filter was pushed gets sent to the filter. That's clearly
1812 If the pipeline is an input pipeline, then giving the buffer to
1813 the new filter (A) means that data that has read from (B), but
1814 not yet read from the pipeline won't be processed by the new
1815 filter (A)! That's certainly not what we want. */
1816 a->d.buf = xmalloc (a->d.size);
1820 /* disable nlimit for the new stream */
1821 a->ntotal = b->ntotal + b->nbytes;
1822 a->nlimit = a->nbytes = 0;
1824 /* make a link from the new stream to the original stream */
1827 /* setup the function on the new stream */
1830 a->filter_ov_owner = rel_ov;
1832 a->subno = b->subno + 1;
1836 byte desc[MAX_IOBUF_DESC];
1837 log_debug ("iobuf-%d.%d: push '%s'\n",
1838 a->no, a->subno, iobuf_desc (a, desc));
1842 /* now we can initialize the new function if we have one */
1843 if (a->filter && (rc = a->filter (a->filter_ov, IOBUFCTRL_INIT, a->chain,
1845 log_error ("IOBUFCTRL_INIT failed: %s\n", gpg_strerror (rc));
1850 * Remove an i/o filter.
1853 iobuf_pop_filter (iobuf_t a, int (*f) (void *opaque, int control,
1854 iobuf_t chain, byte * buf, size_t * len),
1858 size_t dummy_len = 0;
1860 byte desc[MAX_IOBUF_DESC];
1863 log_debug ("iobuf-%d.%d: pop '%s'\n",
1864 a->no, a->subno, iobuf_desc (a, desc));
1865 if (a->use == IOBUF_INPUT_TEMP || a->use == IOBUF_OUTPUT_TEMP)
1867 /* This should be the last filter in the pipeline. */
1868 log_assert (! a->chain);
1872 { /* this is simple */
1876 xfree (a->real_fname);
1877 memcpy (a, b, sizeof *a);
1881 for (b = a; b; b = b->chain)
1882 if (b->filter == f && (!ov || b->filter_ov == ov))
1885 log_bug ("iobuf_pop_filter(): filter function not found\n");
1887 /* flush this stream if it is an output stream */
1888 if (a->use == IOBUF_OUTPUT && (rc = filter_flush (b)))
1890 log_error ("filter_flush failed in iobuf_pop_filter: %s\n",
1894 /* and tell the filter to free it self */
1895 if (b->filter && (rc = b->filter (b->filter_ov, IOBUFCTRL_FREE, b->chain,
1898 log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc));
1901 if (b->filter_ov && b->filter_ov_owner)
1903 xfree (b->filter_ov);
1904 b->filter_ov = NULL;
1908 /* and see how to remove it */
1909 if (a == b && !b->chain)
1910 log_bug ("can't remove the last filter from the chain\n");
1912 { /* remove the first iobuf from the chain */
1913 /* everything from b is copied to a. This is save because
1914 * a flush has been done on the to be removed entry
1918 xfree (a->real_fname);
1919 memcpy (a, b, sizeof *a);
1922 log_debug ("iobuf-%d.%d: popped filter\n", a->no, a->subno);
1925 { /* remove the last iobuf from the chain */
1926 log_bug ("Ohh jeee, trying to remove a head filter\n");
1929 { /* remove an intermediate iobuf from the chain */
1930 log_bug ("Ohh jeee, trying to remove an intermediate filter\n");
1938 * read underflow: read at least one byte into the buffer and return
1939 * the first byte or -1 on EOF.
1942 underflow (iobuf_t a, int clear_pending_eof)
1944 return underflow_target (a, clear_pending_eof, 1);
1949 * read underflow: read TARGET bytes into the buffer and return
1950 * the first byte or -1 on EOF.
1953 underflow_target (iobuf_t a, int clear_pending_eof, size_t target)
1959 log_debug ("iobuf-%d.%d: underflow: buffer size: %d; still buffered: %d => space for %d bytes\n",
1961 (int) a->d.size, (int) (a->d.len - a->d.start),
1962 (int) (a->d.size - (a->d.len - a->d.start)));
1964 if (a->use == IOBUF_INPUT_TEMP)
1965 /* By definition, there isn't more data to read into the
1969 log_assert (a->use == IOBUF_INPUT);
1973 /* If there is still some buffered data, then move it to the start
1974 of the buffer and try to fill the end of the buffer. (This is
1975 useful if we are called from iobuf_peek().) */
1976 log_assert (a->d.start <= a->d.len);
1977 a->d.len -= a->d.start;
1979 memmove (a->d.buf, &a->d.buf[a->d.start], a->d.len);
1982 if (a->d.len < target && a->filter_eof)
1983 /* The last time we tried to read from this filter, we got an EOF.
1984 We couldn't return the EOF, because there was buffered data.
1985 Since there is no longer any buffered data, return the
1989 log_debug ("iobuf-%d.%d: underflow: eof (pending eof)\n",
1991 if (! clear_pending_eof)
1995 /* A filter follows this one. Free this filter. */
1997 iobuf_t b = a->chain;
1999 log_debug ("iobuf-%d.%d: filter popped (pending EOF returned)\n",
2002 xfree (a->real_fname);
2003 memcpy (a, b, sizeof *a);
2008 a->filter_eof = 0; /* for the top level filter */
2009 return -1; /* return one(!) EOF */
2012 if (a->d.len == 0 && a->error)
2013 /* The last time we tried to read from this filter, we got an
2014 error. We couldn't return the error, because there was
2015 buffered data. Since there is no longer any buffered data,
2016 return the error. */
2019 log_debug ("iobuf-%d.%d: pending error (%s) returned\n",
2020 a->no, a->subno, gpg_strerror (a->error));
2024 if (a->filter && ! a->filter_eof && ! a->error)
2025 /* We have a filter function and the last time we tried to read we
2026 didn't get an EOF or an error. Try to fill the buffer. */
2028 /* Be careful to account for any buffered data. */
2029 len = a->d.size - a->d.len;
2031 if (a->e_d.preferred && a->d.len < IOBUF_ZEROCOPY_THRESHOLD_SIZE
2032 && (IOBUF_ZEROCOPY_THRESHOLD_SIZE - a->d.len) < len)
2035 log_debug ("iobuf-%d.%d: limit buffering as external drain is "
2036 "preferred\n", a->no, a->subno);
2037 len = IOBUF_ZEROCOPY_THRESHOLD_SIZE - a->d.len;
2041 /* There is no space for more data. Don't bother calling
2046 /* If no buffered data and drain buffer has been setup, and drain
2047 * buffer is largish, read data directly to drain buffer. */
2050 && a->e_d.len >= IOBUF_ZEROCOPY_THRESHOLD_SIZE)
2055 log_debug ("iobuf-%d.%d: underflow: A->FILTER (%lu bytes, to external drain)\n",
2056 a->no, a->subno, (ulong)len);
2058 rc = a->filter (a->filter_ov, IOBUFCTRL_UNDERFLOW, a->chain,
2066 log_debug ("iobuf-%d.%d: underflow: A->FILTER (%lu bytes)\n",
2067 a->no, a->subno, (ulong)len);
2069 rc = a->filter (a->filter_ov, IOBUFCTRL_UNDERFLOW, a->chain,
2070 &a->d.buf[a->d.len], &len);
2076 log_debug ("iobuf-%d.%d: A->FILTER() returned rc=%d (%s), read %lu bytes%s\n",
2078 rc, rc == 0 ? "ok" : rc == -1 ? "EOF" : gpg_strerror (rc),
2079 (ulong)(a->e_d.used ? a->e_d.used : len),
2080 a->e_d.used ? " (to external buffer)" : "");
2081 /* if( a->no == 1 ) */
2082 /* log_hexdump (" data:", a->d.buf, len); */
2087 size_t dummy_len = 0;
2089 /* Tell the filter to free itself */
2090 if ((rc = a->filter (a->filter_ov, IOBUFCTRL_FREE, a->chain,
2092 log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc));
2094 /* Free everything except for the internal buffer. */
2095 if (a->filter_ov && a->filter_ov_owner)
2096 xfree (a->filter_ov);
2097 a->filter_ov = NULL;
2101 if (clear_pending_eof && a->d.len == 0 && a->e_d.used == 0
2103 /* We don't need to keep this filter around at all:
2106 - we have no buffered data
2107 - a filter follows this one.
2109 Unlink this filter. */
2111 iobuf_t b = a->chain;
2113 log_debug ("iobuf-%d.%d: pop in underflow (nothing buffered, got EOF)\n",
2116 xfree (a->real_fname);
2117 memcpy (a, b, sizeof *a);
2124 else if (a->d.len == 0 && a->e_d.used == 0)
2125 /* We can't unlink this filter (it is the only one in the
2126 pipeline), but we can immediately return EOF. */
2130 /* Record the error. */
2134 if (a->d.len == 0 && a->e_d.used == 0)
2135 /* There is no buffered data. Immediately return EOF. */
2140 log_assert (a->d.start <= a->d.len);
2141 if (a->e_d.used > 0)
2143 if (a->d.start < a->d.len)
2144 return a->d.buf[a->d.start++];
2152 filter_flush (iobuf_t a)
2154 int external_used = 0;
2162 if (a->use == IOBUF_OUTPUT_TEMP)
2163 { /* increase the temp buffer */
2164 size_t newsize = a->d.size + iobuf_buffer_size;
2167 log_debug ("increasing temp iobuf from %lu to %lu\n",
2168 (ulong) a->d.size, (ulong) newsize);
2170 a->d.buf = xrealloc (a->d.buf, newsize);
2171 a->d.size = newsize;
2174 else if (a->use != IOBUF_OUTPUT)
2175 log_bug ("flush on non-output iobuf\n");
2176 else if (!a->filter)
2177 log_bug ("filter_flush: no filter\n");
2179 if (a->d.len == 0 && a->e_d.buf && a->e_d.len > 0)
2181 src_buf = a->e_d.buf;
2182 src_len = a->e_d.len;
2193 rc = a->filter (a->filter_ov, IOBUFCTRL_FLUSH, a->chain, src_buf, &len);
2194 if (!rc && len != src_len)
2196 log_info ("filter_flush did not write all!\n");
2197 rc = GPG_ERR_INTERNAL;
2210 iobuf_readbyte (iobuf_t a)
2214 if (a->use == IOBUF_OUTPUT || a->use == IOBUF_OUTPUT_TEMP)
2216 log_bug ("iobuf_readbyte called on a non-INPUT pipeline!\n");
2220 log_assert (a->d.start <= a->d.len);
2222 if (a->nlimit && a->nbytes >= a->nlimit)
2223 return -1; /* forced EOF */
2225 if (a->d.start < a->d.len)
2227 c = a->d.buf[a->d.start++];
2229 else if ((c = underflow (a, 1)) == -1)
2230 return -1; /* EOF */
2232 log_assert (a->d.start <= a->d.len);
2234 /* Note: if underflow doesn't return EOF, then it returns the first
2235 byte that was read and advances a->d.start appropriately. */
2243 iobuf_read (iobuf_t a, void *buffer, unsigned int buflen)
2245 unsigned char *buf = (unsigned char *)buffer;
2248 if (a->use == IOBUF_OUTPUT || a->use == IOBUF_OUTPUT_TEMP)
2250 log_bug ("iobuf_read called on a non-INPUT pipeline!\n");
2256 /* Handle special cases. */
2257 for (n = 0; n < buflen; n++)
2259 if ((c = iobuf_readbyte (a)) == -1)
2262 return -1; /* eof */
2278 /* Hint for how full to fill iobuf internal drain buffer. */
2279 a->e_d.preferred = (a->use != IOBUF_INPUT_TEMP)
2280 && (buf && buflen >= IOBUF_ZEROCOPY_THRESHOLD_SIZE);
2285 if (n < buflen && a->d.start < a->d.len)
2286 /* Drain the buffer. */
2288 unsigned size = a->d.len - a->d.start;
2289 if (size > buflen - n)
2292 memcpy (buf, a->d.buf + a->d.start, size);
2299 /* Draining the internal buffer didn't fill BUFFER. Call
2300 underflow to read more data into the filter's internal
2303 if (a->use != IOBUF_INPUT_TEMP && buf && n < buflen)
2305 /* Setup external drain buffer for faster moving of data
2306 * (avoid memcpy). */
2308 a->e_d.len = (buflen - n) / IOBUF_ZEROCOPY_THRESHOLD_SIZE
2309 * IOBUF_ZEROCOPY_THRESHOLD_SIZE;
2310 if (a->e_d.len == 0)
2312 if (a->e_d.buf && DBG_IOBUF)
2313 log_debug ("iobuf-%d.%d: reading to external buffer, %lu bytes\n",
2314 a->no, a->subno, (ulong)a->e_d.len);
2317 if ((c = underflow (a, 1)) == -1)
2318 /* EOF. If we managed to read something, don't return EOF
2324 return n ? n : -1 /*EOF*/;
2327 if (a->e_d.buf && a->e_d.used > 0)
2329 /* Drain buffer was used, 'c' only contains return code
2353 iobuf_peek (iobuf_t a, byte * buf, unsigned buflen)
2357 log_assert (buflen > 0);
2358 log_assert (a->use == IOBUF_INPUT || a->use == IOBUF_INPUT_TEMP);
2360 if (buflen > a->d.size)
2361 /* We can't peek more than we can buffer. */
2364 /* Try to fill the internal buffer with enough data to satisfy the
2366 while (buflen > a->d.len - a->d.start)
2368 if (underflow_target (a, 0, buflen) == -1)
2369 /* EOF. We can't read any more. */
2372 /* Underflow consumes the first character (it's the return
2373 value). unget() it by resetting the "file position". */
2374 log_assert (a->d.start == 1);
2378 n = a->d.len - a->d.start;
2386 memcpy (buf, &a->d.buf[a->d.start], n);
2395 iobuf_writebyte (iobuf_t a, unsigned int c)
2399 if (a->use == IOBUF_INPUT || a->use == IOBUF_INPUT_TEMP)
2401 log_bug ("iobuf_writebyte called on an input pipeline!\n");
2405 if (a->d.len == a->d.size)
2406 if ((rc=filter_flush (a)))
2409 log_assert (a->d.len < a->d.size);
2410 a->d.buf[a->d.len++] = c;
2416 iobuf_write (iobuf_t a, const void *buffer, unsigned int buflen)
2418 const unsigned char *buf = (const unsigned char *)buffer;
2421 if (a->use == IOBUF_INPUT || a->use == IOBUF_INPUT_TEMP)
2423 log_bug ("iobuf_write called on an input pipeline!\n");
2430 /* Hint for how full to fill iobuf internal drain buffer. */
2431 a->e_d.preferred = (a->use != IOBUF_OUTPUT_TEMP)
2432 && (buflen >= IOBUF_ZEROCOPY_THRESHOLD_SIZE);
2436 if ((a->use != IOBUF_OUTPUT_TEMP)
2437 && a->d.len == 0 && buflen >= IOBUF_ZEROCOPY_THRESHOLD_SIZE)
2439 /* Setup external drain buffer for faster moving of data
2440 * (avoid memcpy). */
2441 a->e_d.buf = (byte *)buf;
2442 a->e_d.len = buflen / IOBUF_ZEROCOPY_THRESHOLD_SIZE
2443 * IOBUF_ZEROCOPY_THRESHOLD_SIZE;
2444 if (a->e_d.len == 0)
2446 if (a->e_d.buf && DBG_IOBUF)
2447 log_debug ("iobuf-%d.%d: writing from external buffer, %lu bytes\n",
2448 a->no, a->subno, (ulong)a->e_d.len);
2451 if (a->e_d.buf == NULL && buflen && a->d.len < a->d.size)
2455 if (a->e_d.preferred && a->d.len < IOBUF_ZEROCOPY_THRESHOLD_SIZE)
2456 size = IOBUF_ZEROCOPY_THRESHOLD_SIZE - a->d.len;
2458 size = a->d.size - a->d.len;
2462 memcpy (a->d.buf + a->d.len, buf, size);
2470 rc = filter_flush (a);
2479 if (a->e_d.buf && a->e_d.used > 0)
2482 buflen -= a->e_d.used;
2494 iobuf_writestr (iobuf_t a, const char *buf)
2496 if (a->use == IOBUF_INPUT || a->use == IOBUF_INPUT_TEMP)
2498 log_bug ("iobuf_writestr called on an input pipeline!\n");
2502 return iobuf_write (a, buf, strlen (buf));
2508 iobuf_write_temp (iobuf_t dest, iobuf_t source)
2510 log_assert (source->use == IOBUF_OUTPUT || source->use == IOBUF_OUTPUT_TEMP);
2511 log_assert (dest->use == IOBUF_OUTPUT || dest->use == IOBUF_OUTPUT_TEMP);
2513 iobuf_flush_temp (source);
2514 return iobuf_write (dest, source->d.buf, source->d.len);
2518 iobuf_temp_to_buffer (iobuf_t a, byte * buffer, size_t buflen)
2520 byte desc[MAX_IOBUF_DESC];
2525 int rc = filter_flush (a);
2527 log_bug ("Flushing iobuf %d.%d (%s) from iobuf_temp_to_buffer failed. Ignoring.\n",
2528 a->no, a->subno, iobuf_desc (a, desc));
2537 memcpy (buffer, a->d.buf, n);
2541 /* Copies the data from the input iobuf SOURCE to the output iobuf
2542 DEST until either an error is encountered or EOF is reached.
2543 Returns the number of bytes copies or (size_t)(-1) on error. */
2545 iobuf_copy (iobuf_t dest, iobuf_t source)
2551 size_t max_read = 0;
2554 log_assert (source->use == IOBUF_INPUT || source->use == IOBUF_INPUT_TEMP);
2555 log_assert (dest->use == IOBUF_OUTPUT || source->use == IOBUF_OUTPUT_TEMP);
2557 if (iobuf_error (dest))
2558 return (size_t)(-1);
2560 /* Use iobuf buffer size for temporary buffer. */
2561 temp_size = iobuf_set_buffer_size(0) * 1024;
2563 temp = xmalloc (temp_size);
2566 nread = iobuf_read (source, temp, temp_size);
2571 if (nread > max_read)
2574 err = iobuf_write (dest, temp, nread);
2580 /* Burn the buffer. */
2582 wipememory (temp, max_read);
2590 iobuf_flush_temp (iobuf_t temp)
2592 if (temp->use == IOBUF_INPUT || temp->use == IOBUF_INPUT_TEMP)
2593 log_bug ("iobuf_flush_temp called on an input pipeline!\n");
2595 iobuf_pop_filter (temp, temp->filter, NULL);
2600 iobuf_set_limit (iobuf_t a, off_t nlimit)
2607 a->ntotal += a->nbytes;
2612 /* Return the length of the file behind A. If there is no file, return 0. */
2614 iobuf_get_filelength (iobuf_t a)
2616 /* Hmmm: file_filter may have already been removed */
2617 for ( ; a->chain; a = a->chain )
2620 if (a->filter != file_filter)
2624 file_filter_ctx_t *b = a->filter_ov;
2625 gnupg_fd_t fp = b->fp;
2627 #if defined(HAVE_W32_SYSTEM)
2628 LARGE_INTEGER exsize;
2630 if (GetFileSizeEx (fp, &exsize))
2631 return exsize.QuadPart;
2632 log_error ("GetFileSize for handle %p failed: %s\n",
2633 fp, w32_strerror (-1));
2634 #else /*!HAVE_W32_SYSTEM*/
2637 if ( !fstat (fp, &st) )
2639 log_error("fstat() failed: %s\n", strerror(errno) );
2640 #endif /*!HAVE_W32_SYSTEM*/
2648 iobuf_get_fd (iobuf_t a)
2650 for (; a->chain; a = a->chain)
2653 if (a->filter != file_filter)
2657 file_filter_ctx_t *b = a->filter_ov;
2658 gnupg_fd_t fp = b->fp;
2666 iobuf_tell (iobuf_t a)
2668 return a->ntotal + a->nbytes;
2672 #if !defined(HAVE_FSEEKO) && !defined(fseeko)
2674 #ifdef HAVE_LIMITS_H
2675 # include <limits.h>
2678 # define LONG_MAX ((long) ((unsigned long) -1 >> 1))
2681 # define LONG_MIN (-1 - LONG_MAX)
2685 * A substitute for fseeko, for hosts that don't have it.
2688 fseeko (FILE * stream, off_t newpos, int whence)
2690 while (newpos != (long) newpos)
2692 long pos = newpos < 0 ? LONG_MIN : LONG_MAX;
2693 if (fseek (stream, pos, whence) != 0)
2698 return fseek (stream, (long) newpos, whence);
2703 iobuf_seek (iobuf_t a, off_t newpos)
2705 file_filter_ctx_t *b = NULL;
2707 if (a->use == IOBUF_OUTPUT || a->use == IOBUF_INPUT)
2709 /* Find the last filter in the pipeline. */
2710 for (; a->chain; a = a->chain)
2713 if (a->filter != file_filter)
2718 #ifdef HAVE_W32_SYSTEM
2719 if (SetFilePointer (b->fp, newpos, NULL, FILE_BEGIN) == 0xffffffff)
2721 log_error ("SetFilePointer failed on handle %p: ec=%d\n",
2722 b->fp, (int) GetLastError ());
2726 if (lseek (b->fp, newpos, SEEK_SET) == (off_t) - 1)
2728 log_error ("can't lseek: %s\n", strerror (errno));
2732 /* Discard the buffer it is not a temp stream. */
2742 /* It is impossible for A->CHAIN to be non-NULL. If A is an INPUT
2743 or OUTPUT buffer, then we find the last filter, which is defined
2744 as A->CHAIN being NULL. If A is a TEMP filter, then A must be
2745 the only filter in the pipe: when iobuf_push_filter adds a filter
2746 to the front of a pipeline, it sets the new filter to be an
2747 OUTPUT filter if the pipeline is an OUTPUT or TEMP pipeline and
2748 to be an INPUT filter if the pipeline is an INPUT pipeline.
2749 Thus, only the last filter in a TEMP pipeline can be a */
2751 /* remove filters, but the last */
2753 log_debug ("iobuf_pop_filter called in iobuf_seek - please report\n");
2755 iobuf_pop_filter (a, a->filter, NULL);
2762 iobuf_get_real_fname (iobuf_t a)
2765 return a->real_fname;
2767 /* the old solution */
2768 for (; a; a = a->chain)
2769 if (!a->chain && a->filter == file_filter)
2771 file_filter_ctx_t *b = a->filter_ov;
2772 return b->print_only_name ? NULL : b->fname;
2779 iobuf_get_fname (iobuf_t a)
2781 for (; a; a = a->chain)
2782 if (!a->chain && a->filter == file_filter)
2784 file_filter_ctx_t *b = a->filter_ov;
2791 iobuf_get_fname_nonnull (iobuf_t a)
2795 fname = iobuf_get_fname (a);
2796 return fname? fname : "[?]";
2801 * Enable or disable partial body length mode (RFC 4880 4.2.2.4).
2803 * If LEN is 0, this disables partial block mode by popping the
2804 * partial body length filter, which must be the most recently
2807 * If LEN is non-zero, it pushes a partial body length filter. If
2808 * this is a read filter, LEN must be the length byte from the first
2809 * chunk and A should be position just after this first partial body
2813 iobuf_set_partial_body_length_mode (iobuf_t a, size_t len)
2816 /* Disable partial body length mode. */
2818 if (a->use == IOBUF_INPUT)
2819 log_debug ("iobuf_pop_filter called in set_partial_block_mode"
2820 " - please report\n");
2822 log_assert (a->filter == block_filter);
2823 iobuf_pop_filter (a, block_filter, NULL);
2826 /* Enabled partial body length mode. */
2828 block_filter_ctx_t *ctx = xcalloc (1, sizeof *ctx);
2833 iobuf_push_filter (a, block_filter, ctx);
2840 iobuf_read_line (iobuf_t a, byte ** addr_of_buffer,
2841 unsigned *length_of_buffer, unsigned *max_length)
2844 char *buffer = (char *)*addr_of_buffer;
2845 unsigned length = *length_of_buffer;
2846 unsigned nbytes = 0;
2847 unsigned maxlen = *max_length;
2850 /* The code assumes that we have space for at least a newline and a
2851 NUL character in the buffer. This requires at least 2 bytes. We
2852 don't complicate the code by handling the stupid corner case, but
2853 simply assert that it can't happen. */
2854 log_assert (!buffer || length >= 2 || maxlen >= 2);
2856 if (!buffer || length <= 1)
2857 /* must allocate a new buffer */
2859 length = 256 <= maxlen ? 256 : maxlen;
2860 buffer = xrealloc (buffer, length);
2861 *addr_of_buffer = (unsigned char *)buffer;
2862 *length_of_buffer = length;
2868 if (!a->nofast && a->d.start < a->d.len && nbytes < length - 1)
2869 /* Fast path for finding '\n' by using standard C library's optimized
2872 unsigned size = a->d.len - a->d.start;
2875 if (size > length - 1 - nbytes)
2876 size = length - 1 - nbytes;
2878 newline_pos = memchr (a->d.buf + a->d.start, '\n', size);
2881 /* Found newline, copy buffer and return. */
2882 size = (newline_pos - (a->d.buf + a->d.start)) + 1;
2883 memcpy (p, a->d.buf + a->d.start, size);
2892 /* No newline, copy buffer and continue. */
2893 memcpy (p, a->d.buf + a->d.start, size);
2902 c = iobuf_readbyte (a);
2911 if (nbytes == length - 1)
2912 /* We don't have enough space to add a \n and a \0. Increase
2915 if (length == maxlen)
2916 /* We reached the buffer's size limit! */
2918 /* Skip the rest of the line. */
2919 while ((c = iobuf_get (a)) != -1 && c != '\n')
2922 /* p is pointing at the last byte in the buffer. We
2923 always terminate the line with "\n\0" so overwrite
2924 the previous byte with a \n. */
2925 log_assert (p > buffer);
2928 /* Indicate truncation. */
2933 length += length < 1024 ? 256 : 1024;
2934 if (length > maxlen)
2937 buffer = xrealloc (buffer, length);
2938 *addr_of_buffer = (unsigned char *)buffer;
2939 *length_of_buffer = length;
2940 p = buffer + nbytes;
2943 /* Add the terminating NUL. */
2946 /* Return the number of characters written to the buffer including
2947 the newline, but not including the terminating NUL. */
2952 translate_file_handle (int fd, int for_write)
2954 #if defined(HAVE_W32_SYSTEM)
2961 x = (int) GetStdHandle (STD_INPUT_HANDLE);
2963 x = (int) GetStdHandle (STD_OUTPUT_HANDLE);
2965 x = (int) GetStdHandle (STD_ERROR_HANDLE);
2970 log_debug ("GetStdHandle(%d) failed: ec=%d\n",
2971 fd, (int) GetLastError ());
2983 iobuf_skip_rest (iobuf_t a, unsigned long n, int partial)
2989 if (a->nofast || a->d.start >= a->d.len)
2991 if (iobuf_readbyte (a) == -1)
2998 unsigned long count = a->d.len - a->d.start;
3000 a->d.start = a->d.len;
3006 unsigned long remaining = n;
3007 while (remaining > 0)
3009 if (a->nofast || a->d.start >= a->d.len)
3011 if (iobuf_readbyte (a) == -1)
3019 unsigned long count = a->d.len - a->d.start;
3020 if (count > remaining)
3025 a->d.start += count;