1 /* iobuf.c - File Handling for OpenPGP.
2 * Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2006,
3 * 2007, 2008, 2009 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
28 #include <sys/types.h>
32 #ifdef HAVE_W32_SYSTEM
33 # ifdef HAVE_WINSOCK2_H
34 # include <winsock2.h>
41 #endif /* __riscos__ */
47 /*-- Begin configurable part. --*/
49 /* The size of the internal buffers.
50 NOTE: If you change this value you MUST also adjust the regression
51 test "armored_key_8192" in armor.test! */
52 #define IOBUF_BUFFER_SIZE 8192
54 /* We don't want to use the STDIO based backend. If you change this
55 be aware that there is no fsync support for the stdio backend. */
56 #undef FILE_FILTER_USES_STDIO
58 /* To avoid a potential DoS with compression packets we better limit
59 the number of filters in a chain. */
60 #define MAX_NESTING_FILTER 64
62 /*-- End configurable part. --*/
65 /* Under W32 the default is to use the setmode call. Define a macro
66 which allows us to enable this call. */
67 #ifdef HAVE_W32_SYSTEM
68 # define USE_SETMODE 1
69 #endif /*HAVE_W32_SYSTEM*/
72 /* Definition of constants and macros used by our file filter
73 implementation. What we define here are 3 macros to make the
77 Is expanded to fileno(a) if using a stdion backend and to a if we
78 are using the low-level backend.
81 Is defined to fopen for the stdio backend and to direct_open if
82 we are using the low-evel backend.
85 Is defined to fopen for the stdio backend and to fd_cache_open if
86 we are using the low-evel backend.
89 Is the type we use for the backend stream or file descriptor.
91 INVALID_FP, FILEP_OR_FD_FOR_STDIN, FILEP_OR_FD_FOR_STDOUT
92 Are macros defined depending on the used backend.
95 #ifdef FILE_FILTER_USES_STDIO
96 # define my_fileno(a) fileno ((a))
97 # define my_fopen_ro(a,b) fopen ((a),(b))
98 # define my_fopen(a,b) fopen ((a),(b))
99 typedef FILE *fp_or_fd_t;
100 # define INVALID_FP NULL
101 # define FILEP_OR_FD_FOR_STDIN (stdin)
102 # define FILEP_OR_FD_FOR_STDOUT (stdout)
103 #else /*!FILE_FILTER_USES_STDIO*/
104 # define my_fopen_ro(a,b) fd_cache_open ((a),(b))
105 # define my_fopen(a,b) direct_open ((a),(b))
106 # ifdef HAVE_W32_SYSTEM
107 /* (We assume that a HANDLE first into an int.) */
108 # define my_fileno(a) ((int)(a))
109 typedef HANDLE fp_or_fd_t;
110 # define INVALID_FP ((HANDLE)-1)
111 # define FILEP_OR_FD_FOR_STDIN (GetStdHandle (STD_INPUT_HANDLE))
112 # define FILEP_OR_FD_FOR_STDOUT (GetStdHandle (STD_OUTPUT_HANDLE))
114 # else /*!HAVE_W32_SYSTEM*/
115 # define my_fileno(a) (a)
116 typedef int fp_or_fd_t;
117 # define INVALID_FP (-1)
118 # define FILEP_OR_FD_FOR_STDIN (0)
119 # define FILEP_OR_FD_FOR_STDOUT (1)
120 # endif /*!HAVE_W32_SYSTEM*/
121 #endif /*!FILE_FILTER_USES_STDIO*/
123 /* The context used by the file filter. */
126 fp_or_fd_t fp; /* Open file pointer or handle. */
130 int print_only_name; /* Flags indicating that fname is not a real file. */
131 char fname[1]; /* Name of the file. */
136 /* If we are not using stdio as the backend we make use of a "close
138 #ifndef FILE_FILTER_USES_STDIO
141 struct close_cache_s *next;
145 typedef struct close_cache_s *close_cache_t;
146 static close_cache_t close_cache;
147 #endif /*!FILE_FILTER_USES_STDIO*/
151 #ifdef HAVE_W32_SYSTEM
158 int print_only_name; /* Flag indicating that fname is not a real file. */
159 char fname[1]; /* Name of the file */
162 #endif /*HAVE_W32_SYSTEM*/
164 /* The first partial length header block must be of size 512
165 * to make it easier (and efficienter) we use a min. block size of 512
166 * for all chunks (but the last one) */
167 #define OP_MIN_PARTIAL_CHUNK 512
168 #define OP_MIN_PARTIAL_CHUNK_2POW 9
170 /* The context we use for the block filter (used to handle OpenPGP
171 length information header). */
177 int partial; /* 1 = partial header, 2 in last partial packet. */
178 char *buffer; /* Used for partial header. */
179 size_t buflen; /* Used size of buffer. */
180 int first_c; /* First character of a partial header (which is > 0). */
186 /* Global flag to tell whether special file names are enabled. See
187 gpg.c for an explanation of these file names. FIXME: it does not
188 belong into the iobuf subsystem. */
189 static int special_names_enabled;
191 /* Local prototypes. */
192 static int underflow (iobuf_t a);
193 static int translate_file_handle (int fd, int for_write);
197 #ifndef FILE_FILTER_USES_STDIO
198 /* This is a replacement for strcmp. Under W32 it does not
199 distinguish between backslash and slash. */
201 fd_cache_strcmp (const char *a, const char *b)
203 #ifdef HAVE_DOSISH_SYSTEM
204 for (; *a && *b; a++, b++)
206 if (*a != *b && !((*a == '/' && *b == '\\')
207 || (*a == '\\' && *b == '/')) )
210 return *(const unsigned char *)a - *(const unsigned char *)b;
212 return strcmp (a, b);
217 * Invalidate (i.e. close) a cached iobuf
220 fd_cache_invalidate (const char *fname)
227 log_debug ("fd_cache_invalidate (%s)\n", fname);
229 for (cc = close_cache; cc; cc = cc->next)
231 if (cc->fp != INVALID_FP && !fd_cache_strcmp (cc->fname, fname))
234 log_debug (" did (%s)\n", cc->fname);
235 #ifdef HAVE_W32_SYSTEM
236 if (!CloseHandle (cc->fp))
248 /* Try to sync changes to the disk. This is to avoid data loss during
249 a system crash in write/close/rename cycle on some file
252 fd_cache_synchronize (const char *fname)
260 log_debug ("fd_cache_synchronize (%s)\n", fname);
262 for (cc=close_cache; cc; cc = cc->next )
264 if (cc->fp != INVALID_FP && !fd_cache_strcmp (cc->fname, fname))
267 log_debug (" did (%s)\n", cc->fname);
269 err = fsync (cc->fp);
274 #endif /*HAVE_FSYNC*/
281 direct_open (const char *fname, const char *mode)
283 #ifdef HAVE_W32_SYSTEM
284 unsigned long da, cd, sm;
287 /* Note, that we do not handle all mode combinations */
289 /* According to the ReactOS source it seems that open() of the
290 * standard MSW32 crt does open the file in shared mode which is
291 * something new for MS applications ;-)
293 if (strchr (mode, '+'))
295 if (fd_cache_invalidate (fname))
297 da = GENERIC_READ | GENERIC_WRITE;
299 sm = FILE_SHARE_READ | FILE_SHARE_WRITE;
301 else if (strchr (mode, 'w'))
303 if (fd_cache_invalidate (fname))
307 sm = FILE_SHARE_WRITE;
313 sm = FILE_SHARE_READ;
316 hfile = CreateFile (fname, da, sm, NULL, cd, FILE_ATTRIBUTE_NORMAL, NULL);
318 #else /*!HAVE_W32_SYSTEM*/
320 int cflag = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
322 /* Note, that we do not handle all mode combinations */
323 if (strchr (mode, '+'))
325 if (fd_cache_invalidate (fname))
329 else if (strchr (mode, 'w'))
331 if (fd_cache_invalidate (fname))
333 oflag = O_WRONLY | O_CREAT | O_TRUNC;
340 if (strchr (mode, 'b'))
343 /* No we need to distinguish between POSIX and RISC OS. */
345 return open (fname, oflag, cflag);
349 int rc = stat (fname, &buf);
351 /* Don't allow iobufs on directories */
352 if (!rc && S_ISDIR (buf.st_mode) && !S_ISREG (buf.st_mode))
353 return __set_errno (EISDIR);
355 return open (fname, oflag, cflag);
358 #endif /*!HAVE_W32_SYSTEM*/
363 * Instead of closing an FD we keep it open and cache it for later reuse
364 * Note that this caching strategy only works if the process does not chdir.
367 fd_cache_close (const char *fname, fp_or_fd_t fp)
372 if (!fname || !*fname)
374 #ifdef HAVE_W32_SYSTEM
380 log_debug ("fd_cache_close (%d) real\n", (int)fp);
383 /* try to reuse a slot */
384 for (cc = close_cache; cc; cc = cc->next)
386 if (cc->fp == INVALID_FP && !fd_cache_strcmp (cc->fname, fname))
390 log_debug ("fd_cache_close (%s) used existing slot\n", fname);
396 log_debug ("fd_cache_close (%s) new slot created\n", fname);
397 cc = xcalloc (1, sizeof *cc + strlen (fname));
398 strcpy (cc->fname, fname);
400 cc->next = close_cache;
405 * Do an direct_open on FNAME but first try to reuse one from the fd_cache
408 fd_cache_open (const char *fname, const char *mode)
413 for (cc = close_cache; cc; cc = cc->next)
415 if (cc->fp != INVALID_FP && !fd_cache_strcmp (cc->fname, fname))
417 fp_or_fd_t fp = cc->fp;
420 log_debug ("fd_cache_open (%s) using cached fp\n", fname);
421 #ifdef HAVE_W32_SYSTEM
422 if (SetFilePointer (fp, 0, NULL, FILE_BEGIN) == 0xffffffff)
424 log_error ("rewind file failed on handle %p: ec=%d\n",
425 fp, (int) GetLastError ());
429 if (lseek (fp, 0, SEEK_SET) == (off_t) - 1)
431 log_error ("can't rewind fd %d: %s\n", fp, strerror (errno));
439 log_debug ("fd_cache_open (%s) not cached\n", fname);
440 return direct_open (fname, mode);
443 #endif /*FILE_FILTER_USES_STDIO */
447 * Read data from a file into buf which has an allocated length of *LEN.
448 * return the number of read bytes in *LEN. OPAQUE is the FILE * of
449 * the stream. A is not used.
451 * IOBUFCTRL_INIT: called just before the function is linked into the
452 * list of function. This can be used to prepare internal
453 * data structures of the function.
454 * IOBUFCTRL_FREE: called just before the function is removed from the
455 * list of functions and can be used to release internal
456 * data structures or close a file etc.
457 * IOBUFCTRL_UNDERFLOW: called by iobuf_underflow to fill the buffer
458 * with new stuff. *RET_LEN is the available size of the
459 * buffer, and should be set to the number of bytes
460 * which were put into the buffer. The function
461 * returns 0 to indicate success, -1 on EOF and
462 * GPG_ERR_xxxxx for other errors.
464 * IOBUFCTRL_FLUSH: called by iobuf_flush() to write out the collected stuff.
465 * *RET_LAN is the number of bytes in BUF.
467 * IOBUFCTRL_CANCEL: send to all filters on behalf of iobuf_cancel. The
468 * filter may take appropriate action on this message.
471 file_filter (void *opaque, int control, iobuf_t chain, byte * buf,
474 file_filter_ctx_t *a = opaque;
475 fp_or_fd_t f = a->fp;
476 size_t size = *ret_len;
480 (void)chain; /* Not used. */
482 #ifdef FILE_FILTER_USES_STDIO
483 if (control == IOBUFCTRL_UNDERFLOW)
485 assert (size); /* We need a buffer. */
488 /* On terminals you could easily read as many EOFs as you
489 call fread() or fgetc() repeatly. Every call will block
490 until you press CTRL-D. So we catch this case before we
491 call fread() again. */
498 nbytes = fread (buf, 1, size, f);
499 if (feof (f) && !nbytes)
501 rc = -1; /* Okay: we can return EOF now. */
503 else if (ferror (f) && errno != EPIPE)
505 rc = gpg_error_from_syserror ();
506 log_error ("%s: read error: %s\n", a->fname, strerror (errno));
511 else if (control == IOBUFCTRL_FLUSH)
516 nbytes = fwrite (buf, 1, size, f);
519 rc = gpg_error_from_syserror ();
520 log_error ("%s: write error: %s\n", a->fname, strerror (errno));
525 else if (control == IOBUFCTRL_INIT)
527 a->keep_open = a->no_cache = 0;
529 else if (control == IOBUFCTRL_DESC)
531 *(char **) buf = "file_filter";
533 else if (control == IOBUFCTRL_FREE)
535 if (f != stdin && f != stdout)
538 log_debug ("%s: close fd %d\n", a->fname, fileno (f));
543 xfree (a); /* We can free our context now. */
545 #else /* !stdio implementation */
547 if (control == IOBUFCTRL_UNDERFLOW)
549 assert (size); /* We need a buffer. */
557 #ifdef HAVE_W32_SYSTEM
561 if (!ReadFile (f, buf, size, &nread, NULL))
563 int ec = (int) GetLastError ();
564 if (ec != ERROR_BROKEN_PIPE)
566 rc = gpg_error_from_errno (ec);
567 log_error ("%s: read error: ec=%d\n", a->fname, ec);
587 n = read (f, buf, size);
589 while (n == -1 && errno == EINTR);
594 rc = gpg_error_from_syserror ();
595 log_error ("%s: read error: %s\n",
596 a->fname, strerror (errno));
612 else if (control == IOBUFCTRL_FLUSH)
616 #ifdef HAVE_W32_SYSTEM
623 if (size && !WriteFile (f, p, nbytes, &n, NULL))
625 int ec = (int) GetLastError ();
626 rc = gpg_error_from_errno (ec);
627 log_error ("%s: write error: ec=%d\n", a->fname, ec);
644 n = write (f, p, nbytes);
646 while (n == -1 && errno == EINTR);
653 while (n != -1 && nbytes);
656 rc = gpg_error_from_syserror ();
657 log_error ("%s: write error: %s\n", a->fname, strerror (errno));
664 else if (control == IOBUFCTRL_INIT)
670 else if (control == IOBUFCTRL_DESC)
672 *(char **) buf = "file_filter(fd)";
674 else if (control == IOBUFCTRL_FREE)
676 #ifdef HAVE_W32_SYSTEM
677 if (f != FILEP_OR_FD_FOR_STDIN && f != FILEP_OR_FD_FOR_STDOUT)
680 log_debug ("%s: close handle %p\n", a->fname, f);
682 fd_cache_close (a->no_cache ? NULL : a->fname, f);
685 if ((int) f != 0 && (int) f != 1)
688 log_debug ("%s: close fd %d\n", a->fname, f);
690 fd_cache_close (a->no_cache ? NULL : a->fname, f);
694 xfree (a); /* We can free our context now. */
696 #endif /* !stdio implementation. */
701 #ifdef HAVE_W32_SYSTEM
702 /* Because network sockets are special objects under Lose32 we have to
703 use a dedicated filter for them. */
705 sock_filter (void *opaque, int control, iobuf_t chain, byte * buf,
708 sock_filter_ctx_t *a = opaque;
709 size_t size = *ret_len;
715 if (control == IOBUFCTRL_UNDERFLOW)
717 assert (size); /* need a buffer */
727 nread = recv (a->sock, buf, size, 0);
728 if (nread == SOCKET_ERROR)
730 int ec = (int) WSAGetLastError ();
731 rc = gpg_error_from_errno (ec);
732 log_error ("socket read error: ec=%d\n", ec);
746 else if (control == IOBUFCTRL_FLUSH)
756 n = send (a->sock, p, nbytes, 0);
757 if (n == SOCKET_ERROR)
759 int ec = (int) WSAGetLastError ();
760 rc = gpg_error_from_errno (ec);
761 log_error ("socket write error: ec=%d\n", ec);
772 else if (control == IOBUFCTRL_INIT)
778 else if (control == IOBUFCTRL_DESC)
780 *(char **) buf = "sock_filter";
782 else if (control == IOBUFCTRL_FREE)
785 closesocket (a->sock);
786 xfree (a); /* we can free our context now */
790 #endif /*HAVE_W32_SYSTEM*/
793 * This is used to implement the block write mode.
794 * Block reading is done on a byte by byte basis in readbyte(),
798 block_filter (void *opaque, int control, iobuf_t chain, byte * buffer,
801 block_filter_ctx_t *a = opaque;
802 char *buf = (char *)buffer;
803 size_t size = *ret_len;
804 int c, needed, rc = 0;
807 if (control == IOBUFCTRL_UNDERFLOW)
812 assert (size); /* need a buffer */
813 if (a->eof) /* don't read any further */
818 { /* get the length bytes */
828 /* These OpenPGP introduced huffman like encoded length
829 * bytes are really a mess :-( */
835 else if ((c = iobuf_get (chain)) == -1)
837 log_error ("block_filter: 1st length byte missing\n");
838 rc = GPG_ERR_BAD_DATA;
855 a->size = (c - 192) * 256;
856 if ((c = iobuf_get (chain)) == -1)
859 ("block_filter: 2nd length byte missing\n");
860 rc = GPG_ERR_BAD_DATA;
875 a->size = iobuf_get (chain) << 24;
876 a->size |= iobuf_get (chain) << 16;
877 a->size |= iobuf_get (chain) << 8;
878 if ((c = iobuf_get (chain)) == -1)
880 log_error ("block_filter: invalid 4 byte length\n");
881 rc = GPG_ERR_BAD_DATA;
895 { /* Next partial body length. */
896 a->size = 1 << (c & 0x1f);
898 /* log_debug("partial: ctx=%p c=%02x size=%u\n", a, c, a->size); */
904 while (!rc && size && a->size)
906 needed = size < a->size ? size : a->size;
907 c = iobuf_read (chain, p, needed);
913 ("block_filter %p: read error (size=%lu,a->size=%lu)\n",
914 a, (ulong) size + c, (ulong) a->size + c);
915 rc = GPG_ERR_BAD_DATA;
928 else if (control == IOBUFCTRL_FLUSH)
931 { /* the complicated openpgp scheme */
932 size_t blen, n, nbytes = size + a->buflen;
934 assert (a->buflen <= OP_MIN_PARTIAL_CHUNK);
935 if (nbytes < OP_MIN_PARTIAL_CHUNK)
937 /* not enough to write a partial block out; so we store it */
939 a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK);
940 memcpy (a->buffer + a->buflen, buf, size);
944 { /* okay, we can write out something */
945 /* do this in a loop to use the most efficient block lengths */
949 /* find the best matching block length - this is limited
950 * by the size of the internal buffering */
951 for (blen = OP_MIN_PARTIAL_CHUNK * 2,
952 c = OP_MIN_PARTIAL_CHUNK_2POW + 1; blen <= nbytes;
957 /* write the partial length header */
958 assert (c <= 0x1f); /*;-) */
960 iobuf_put (chain, c);
962 { /* write stuff from the buffer */
963 assert (n == OP_MIN_PARTIAL_CHUNK);
964 if (iobuf_write (chain, a->buffer, n))
965 rc = gpg_error_from_syserror ();
969 if ((n = nbytes) > blen)
971 if (n && iobuf_write (chain, p, n))
972 rc = gpg_error_from_syserror ();
976 while (!rc && nbytes >= OP_MIN_PARTIAL_CHUNK);
977 /* store the rest in the buffer */
981 assert (nbytes < OP_MIN_PARTIAL_CHUNK);
983 a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK);
984 memcpy (a->buffer, p, nbytes);
992 else if (control == IOBUFCTRL_INIT)
995 log_debug ("init block_filter %p\n", a);
998 else if (a->use == 1)
999 a->count = a->size = 0;
1001 a->count = a->size; /* force first length bytes */
1006 else if (control == IOBUFCTRL_DESC)
1008 *(char **) buf = "block_filter";
1010 else if (control == IOBUFCTRL_FREE)
1013 { /* write the end markers */
1017 /* write out the remaining bytes without a partial header
1018 * the length of this header may be 0 - but if it is
1019 * the first block we are not allowed to use a partial header
1020 * and frankly we can't do so, because this length must be
1021 * a power of 2. This is _really_ complicated because we
1022 * have to check the possible length of a packet prior
1023 * to it's creation: a chain of filters becomes complicated
1024 * and we need a lot of code to handle compressed packets etc.
1027 /* construct header */
1029 /*log_debug("partial: remaining length=%u\n", len ); */
1031 rc = iobuf_put (chain, len);
1032 else if (len < 8384)
1034 if (!(rc = iobuf_put (chain, ((len - 192) / 256) + 192)))
1035 rc = iobuf_put (chain, ((len - 192) % 256));
1038 { /* use a 4 byte header */
1039 if (!(rc = iobuf_put (chain, 0xff)))
1040 if (!(rc = iobuf_put (chain, (len >> 24) & 0xff)))
1041 if (!(rc = iobuf_put (chain, (len >> 16) & 0xff)))
1042 if (!(rc = iobuf_put (chain, (len >> 8) & 0xff)))
1043 rc = iobuf_put (chain, len & 0xff);
1046 rc = iobuf_write (chain, a->buffer, len);
1049 log_error ("block_filter: write error: %s\n",
1051 rc = gpg_error_from_syserror ();
1062 log_error ("block_filter: pending bytes!\n");
1065 log_debug ("free block_filter %p\n", a);
1066 xfree (a); /* we can free our context now */
1074 print_chain (iobuf_t a)
1078 for (; a; a = a->chain)
1080 size_t dummy_len = 0;
1081 const char *desc = "[none]";
1084 a->filter (a->filter_ov, IOBUFCTRL_DESC, NULL,
1085 (byte *) & desc, &dummy_len);
1087 log_debug ("iobuf chain: %d.%d `%s' filter_eof=%d start=%d len=%d\n",
1088 a->no, a->subno, desc?desc:"?", a->filter_eof,
1089 (int) a->d.start, (int) a->d.len);
1094 iobuf_print_chain (iobuf_t a)
1101 * Allocate a new io buffer, with no function assigned.
1102 * Use is the desired usage: 1 for input, 2 for output, 3 for temp buffer
1103 * BUFSIZE is a suggested buffer size.
1106 iobuf_alloc (int use, size_t bufsize)
1109 static int number = 0;
1111 a = xcalloc (1, sizeof *a);
1113 a->d.buf = xmalloc (bufsize);
1114 a->d.size = bufsize;
1118 a->real_fname = NULL;
1123 iobuf_close (iobuf_t a)
1126 size_t dummy_len = 0;
1129 if (a && a->directfp)
1131 fclose (a->directfp);
1132 xfree (a->real_fname);
1134 log_debug ("iobuf_close -> %p\n", a->directfp);
1138 for (; a && !rc; a = a2)
1141 if (a->use == 2 && (rc = iobuf_flush (a)))
1142 log_error ("iobuf_flush failed on close: %s\n", gpg_strerror (rc));
1145 log_debug ("iobuf-%d.%d: close `%s'\n", a->no, a->subno,
1146 a->desc?a->desc:"?");
1147 if (a->filter && (rc = a->filter (a->filter_ov, IOBUFCTRL_FREE,
1148 a->chain, NULL, &dummy_len)))
1149 log_error ("IOBUFCTRL_FREE failed on close: %s\n", gpg_strerror (rc));
1150 xfree (a->real_fname);
1153 memset (a->d.buf, 0, a->d.size); /* erase the buffer */
1162 iobuf_cancel (iobuf_t a)
1167 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1168 char *remove_name = NULL;
1171 if (a && a->use == 2)
1173 s = iobuf_get_real_fname (a);
1176 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1177 remove_name = xstrdup (s);
1184 /* send a cancel message to all filters */
1185 for (a2 = a; a2; a2 = a2->chain)
1189 a2->filter (a2->filter_ov, IOBUFCTRL_CANCEL, a2->chain, NULL, &dummy);
1192 rc = iobuf_close (a);
1193 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1196 /* Argg, MSDOS does not allow to remove open files. So
1197 * we have to do it here */
1198 remove (remove_name);
1199 xfree (remove_name);
1207 * create a temporary iobuf, which can be used to collect stuff
1208 * in an iobuf and later be written by iobuf_write_temp() to another
1216 a = iobuf_alloc (3, IOBUF_BUFFER_SIZE);
1222 iobuf_temp_with_content (const char *buffer, size_t length)
1226 a = iobuf_alloc (3, length);
1227 memcpy (a->d.buf, buffer, length);
1234 iobuf_enable_special_filenames (int yes)
1236 special_names_enabled = yes;
1240 /* See whether the filename has the form "-&nnnn", where n is a
1241 non-zero number. Returns this number or -1 if it is not the
1244 check_special_filename (const char *fname)
1246 if (special_names_enabled && fname && *fname == '-' && fname[1] == '&')
1251 for (i = 0; digitp (fname+i); i++)
1254 return atoi (fname);
1260 /* This fucntion returns true if FNAME indicates a PIPE (stdout or
1261 stderr) or a special file name if those are enabled. */
1263 iobuf_is_pipe_filename (const char *fname)
1265 if (!fname || (*fname=='-' && !fname[1]) )
1267 return check_special_filename (fname) != -1;
1271 /* Either open the file specified by the file descriptor FD or - if FD
1272 is -1, the file with name FNAME. As of now MODE is assumed to be
1273 "rb" if FNAME is used. In contrast to iobuf_fdopen the file
1274 descriptor FD will not be closed during an iobuf_close. */
1276 iobuf_open_fd_or_name (gnupg_fd_t fd, const char *fname, const char *mode)
1281 a = iobuf_open (fname);
1290 a = iobuf_fdopen (fd2, mode);
1297 * Create a head iobuf for reading from a file
1298 * returns: NULL if an error occures and sets errno
1301 iobuf_open (const char *fname)
1305 file_filter_ctx_t *fcx;
1310 if (!fname || (*fname == '-' && !fname[1]))
1312 fp = FILEP_OR_FD_FOR_STDIN;
1314 setmode (my_fileno (fp), O_BINARY);
1319 else if ((fd = check_special_filename (fname)) != -1)
1320 return iobuf_fdopen (translate_file_handle (fd, 0), "rb");
1321 else if ((fp = my_fopen_ro (fname, "rb")) == INVALID_FP)
1323 a = iobuf_alloc (1, IOBUF_BUFFER_SIZE);
1324 fcx = xmalloc (sizeof *fcx + strlen (fname));
1326 fcx->print_only_name = print_only;
1327 strcpy (fcx->fname, fname);
1329 a->real_fname = xstrdup (fname);
1330 a->filter = file_filter;
1332 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1333 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1335 log_debug ("iobuf-%d.%d: open `%s' fd=%d\n",
1336 a->no, a->subno, fname, (int) my_fileno (fcx->fp));
1342 * Create a head iobuf for reading from a file
1343 * returns: NULL if an error occures and sets errno
1346 iobuf_fdopen (int fd, const char *mode)
1350 file_filter_ctx_t *fcx;
1353 #ifdef FILE_FILTER_USES_STDIO
1354 if (!(fp = fdopen (fd, mode)))
1357 fp = (fp_or_fd_t) fd;
1359 a = iobuf_alloc (strchr (mode, 'w') ? 2 : 1, IOBUF_BUFFER_SIZE);
1360 fcx = xmalloc (sizeof *fcx + 20);
1362 fcx->print_only_name = 1;
1363 sprintf (fcx->fname, "[fd %d]", fd);
1364 a->filter = file_filter;
1366 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1367 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1369 log_debug ("iobuf-%d.%d: fdopen `%s'\n", a->no, a->subno, fcx->fname);
1370 iobuf_ioctl (a, 3, 1, NULL); /* disable fd caching */
1376 iobuf_sockopen (int fd, const char *mode)
1379 #ifdef HAVE_W32_SYSTEM
1380 sock_filter_ctx_t *scx;
1383 a = iobuf_alloc (strchr (mode, 'w') ? 2 : 1, IOBUF_BUFFER_SIZE);
1384 scx = xmalloc (sizeof *scx + 25);
1386 scx->print_only_name = 1;
1387 sprintf (scx->fname, "[sock %d]", fd);
1388 a->filter = sock_filter;
1390 sock_filter (scx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1391 sock_filter (scx, IOBUFCTRL_INIT, NULL, NULL, &len);
1393 log_debug ("iobuf-%d.%d: sockopen `%s'\n", a->no, a->subno, scx->fname);
1394 iobuf_ioctl (a, 3, 1, NULL); /* disable fd caching */
1396 a = iobuf_fdopen (fd, mode);
1402 * create an iobuf for writing to a file; the file will be created.
1405 iobuf_create (const char *fname)
1409 file_filter_ctx_t *fcx;
1414 if (!fname || (*fname == '-' && !fname[1]))
1416 fp = FILEP_OR_FD_FOR_STDOUT;
1418 setmode (my_fileno (fp), O_BINARY);
1423 else if ((fd = check_special_filename (fname)) != -1)
1424 return iobuf_fdopen (translate_file_handle (fd, 1), "wb");
1425 else if ((fp = my_fopen (fname, "wb")) == INVALID_FP)
1427 a = iobuf_alloc (2, IOBUF_BUFFER_SIZE);
1428 fcx = xmalloc (sizeof *fcx + strlen (fname));
1430 fcx->print_only_name = print_only;
1431 strcpy (fcx->fname, fname);
1433 a->real_fname = xstrdup (fname);
1434 a->filter = file_filter;
1436 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1437 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1439 log_debug ("iobuf-%d.%d: create `%s'\n", a->no, a->subno,
1440 a->desc?a->desc:"?");
1446 * append to an iobuf; if the file does not exist, create it.
1447 * cannot be used for stdout.
1448 * Note: This is not used.
1450 #if 0 /* not used */
1452 iobuf_append (const char *fname)
1456 file_filter_ctx_t *fcx;
1461 else if (!(fp = my_fopen (fname, "ab")))
1463 a = iobuf_alloc (2, IOBUF_BUFFER_SIZE);
1464 fcx = m_alloc (sizeof *fcx + strlen (fname));
1466 strcpy (fcx->fname, fname);
1467 a->real_fname = m_strdup (fname);
1468 a->filter = file_filter;
1470 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1471 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1473 log_debug ("iobuf-%d.%d: append `%s'\n", a->no, a->subno,
1474 a->desc?a->desc:"?");
1481 iobuf_openrw (const char *fname)
1485 file_filter_ctx_t *fcx;
1490 else if ((fp = my_fopen (fname, "r+b")) == INVALID_FP)
1492 a = iobuf_alloc (2, IOBUF_BUFFER_SIZE);
1493 fcx = xmalloc (sizeof *fcx + strlen (fname));
1495 strcpy (fcx->fname, fname);
1496 a->real_fname = xstrdup (fname);
1497 a->filter = file_filter;
1499 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1500 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1502 log_debug ("iobuf-%d.%d: openrw `%s'\n", a->no, a->subno,
1503 a->desc?a->desc:"?");
1510 iobuf_ioctl (iobuf_t a, int cmd, int intval, void *ptrval)
1513 { /* keep system filepointer/descriptor open */
1515 log_debug ("iobuf-%d.%d: ioctl `%s' keep=%d\n",
1516 a ? a->no : -1, a ? a->subno : -1,
1517 a && a->desc ? a->desc : "?",
1519 for (; a; a = a->chain)
1520 if (!a->chain && a->filter == file_filter)
1522 file_filter_ctx_t *b = a->filter_ov;
1523 b->keep_open = intval;
1526 #ifdef HAVE_W32_SYSTEM
1527 else if (!a->chain && a->filter == sock_filter)
1529 sock_filter_ctx_t *b = a->filter_ov;
1530 b->keep_open = intval;
1536 { /* invalidate cache */
1538 log_debug ("iobuf-*.*: ioctl `%s' invalidate\n",
1539 ptrval ? (char *) ptrval : "?");
1540 if (!a && !intval && ptrval)
1542 #ifndef FILE_FILTER_USES_STDIO
1543 if (fd_cache_invalidate (ptrval))
1550 { /* disallow/allow caching */
1552 log_debug ("iobuf-%d.%d: ioctl `%s' no_cache=%d\n",
1553 a ? a->no : -1, a ? a->subno : -1,
1554 a && a->desc? a->desc : "?",
1556 for (; a; a = a->chain)
1557 if (!a->chain && a->filter == file_filter)
1559 file_filter_ctx_t *b = a->filter_ov;
1560 b->no_cache = intval;
1563 #ifdef HAVE_W32_SYSTEM
1564 else if (!a->chain && a->filter == sock_filter)
1566 sock_filter_ctx_t *b = a->filter_ov;
1567 b->no_cache = intval;
1574 /* Do a fsync on the open fd and return any errors to the caller
1575 of iobuf_ioctl. Note that we work on a file name here. */
1577 log_debug ("iobuf-*.*: ioctl `%s' fsync\n",
1578 ptrval? (const char*)ptrval:"<null>");
1580 if (!a && !intval && ptrval)
1582 #ifndef FILE_FILTER_USES_STDIO
1583 return fd_cache_synchronize (ptrval);
1596 * Register an i/o filter.
1599 iobuf_push_filter (iobuf_t a,
1600 int (*f) (void *opaque, int control,
1601 iobuf_t chain, byte * buf, size_t * len),
1604 return iobuf_push_filter2 (a, f, ov, 0);
1608 iobuf_push_filter2 (iobuf_t a,
1609 int (*f) (void *opaque, int control,
1610 iobuf_t chain, byte * buf, size_t * len),
1611 void *ov, int rel_ov)
1614 size_t dummy_len = 0;
1620 if (a->use == 2 && (rc = iobuf_flush (a)))
1623 if (a->subno >= MAX_NESTING_FILTER)
1625 log_error ("i/o filter too deeply nested - corrupted data?\n");
1626 return GPG_ERR_BAD_DATA;
1629 /* make a copy of the current stream, so that
1630 * A is the new stream and B the original one.
1631 * The contents of the buffers are transferred to the
1634 b = xmalloc (sizeof *b);
1635 memcpy (b, a, sizeof *b);
1636 /* fixme: it is stupid to keep a copy of the name at every level
1637 * but we need the name somewhere because the name known by file_filter
1638 * may have been released when we need the name of the file */
1639 b->real_fname = a->real_fname ? xstrdup (a->real_fname) : NULL;
1640 /* remove the filter stuff from the new stream */
1642 a->filter_ov = NULL;
1643 a->filter_ov_owner = 0;
1646 a->use = 2; /* make a write stream from a temp stream */
1649 { /* allocate a fresh buffer for the
1651 b->d.buf = xmalloc (a->d.size);
1656 { /* allocate a fresh buffer for the new
1658 a->d.buf = xmalloc (a->d.size);
1662 /* disable nlimit for the new stream */
1663 a->ntotal = b->ntotal + b->nbytes;
1664 a->nlimit = a->nbytes = 0;
1666 /* make a link from the new stream to the original stream */
1668 a->opaque = b->opaque;
1670 /* setup the function on the new stream */
1673 a->filter_ov_owner = rel_ov;
1675 a->subno = b->subno + 1;
1676 f (ov, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &dummy_len);
1680 log_debug ("iobuf-%d.%d: push `%s'\n", a->no, a->subno,
1681 a->desc?a->desc:"?");
1685 /* now we can initialize the new function if we have one */
1686 if (a->filter && (rc = a->filter (a->filter_ov, IOBUFCTRL_INIT, a->chain,
1688 log_error ("IOBUFCTRL_INIT failed: %s\n", gpg_strerror (rc));
1693 * Remove an i/o filter.
1696 pop_filter (iobuf_t a, int (*f) (void *opaque, int control,
1697 iobuf_t chain, byte * buf, size_t * len),
1701 size_t dummy_len = 0;
1708 log_debug ("iobuf-%d.%d: pop `%s'\n", a->no, a->subno,
1709 a->desc?a->desc:"?");
1711 { /* this is simple */
1715 xfree (a->real_fname);
1716 memcpy (a, b, sizeof *a);
1720 for (b = a; b; b = b->chain)
1721 if (b->filter == f && (!ov || b->filter_ov == ov))
1724 log_bug ("pop_filter(): filter function not found\n");
1726 /* flush this stream if it is an output stream */
1727 if (a->use == 2 && (rc = iobuf_flush (b)))
1729 log_error ("iobuf_flush failed in pop_filter: %s\n", gpg_strerror (rc));
1732 /* and tell the filter to free it self */
1733 if (b->filter && (rc = b->filter (b->filter_ov, IOBUFCTRL_FREE, b->chain,
1736 log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc));
1739 if (b->filter_ov && b->filter_ov_owner)
1741 xfree (b->filter_ov);
1742 b->filter_ov = NULL;
1746 /* and see how to remove it */
1747 if (a == b && !b->chain)
1748 log_bug ("can't remove the last filter from the chain\n");
1750 { /* remove the first iobuf from the chain */
1751 /* everything from b is copied to a. This is save because
1752 * a flush has been done on the to be removed entry
1756 xfree (a->real_fname);
1757 memcpy (a, b, sizeof *a);
1760 log_debug ("iobuf-%d.%d: popped filter\n", a->no, a->subno);
1763 { /* remove the last iobuf from the chain */
1764 log_bug ("Ohh jeee, trying to remove a head filter\n");
1767 { /* remove an intermediate iobuf from the chain */
1768 log_bug ("Ohh jeee, trying to remove an intermediate filter\n");
1776 * read underflow: read more bytes into the buffer and return
1777 * the first byte or -1 on EOF.
1780 underflow (iobuf_t a)
1785 assert (a->d.start == a->d.len);
1787 return -1; /* EOF because a temp buffer can't do an underflow */
1793 iobuf_t b = a->chain;
1795 log_debug ("iobuf-%d.%d: pop `%s' in underflow\n",
1796 a->no, a->subno, a->desc?a->desc:"?");
1798 xfree (a->real_fname);
1799 memcpy (a, b, sizeof *a);
1804 a->filter_eof = 0; /* for the top level filter */
1806 log_debug ("iobuf-%d.%d: underflow: eof (due to filter eof)\n",
1808 return -1; /* return one(!) EOF */
1813 log_debug ("iobuf-%d.%d: error\n", a->no, a->subno);
1819 FILE *fp = a->directfp;
1821 len = fread (a->d.buf, 1, a->d.size, fp);
1822 if (len < a->d.size)
1825 a->error = gpg_error_from_syserror ();
1829 return len ? a->d.buf[a->d.start++] : -1;
1837 log_debug ("iobuf-%d.%d: underflow: req=%lu\n",
1838 a->no, a->subno, (ulong) len);
1839 rc = a->filter (a->filter_ov, IOBUFCTRL_UNDERFLOW, a->chain,
1843 log_debug ("iobuf-%d.%d: underflow: got=%lu rc=%d\n",
1844 a->no, a->subno, (ulong) len, rc);
1845 /* if( a->no == 1 ) */
1846 /* log_hexdump (" data:", a->d.buf, len); */
1848 if (a->use == 1 && rc == -1)
1849 { /* EOF: we can remove the filter */
1850 size_t dummy_len = 0;
1852 /* and tell the filter to free itself */
1853 if ((rc = a->filter (a->filter_ov, IOBUFCTRL_FREE, a->chain,
1855 log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc));
1856 if (a->filter_ov && a->filter_ov_owner)
1858 xfree (a->filter_ov);
1859 a->filter_ov = NULL;
1863 a->filter_ov = NULL;
1865 if (!len && a->chain)
1867 iobuf_t b = a->chain;
1869 log_debug ("iobuf-%d.%d: pop in underflow (!len)\n",
1872 xfree (a->real_fname);
1873 memcpy (a, b, sizeof *a);
1884 log_debug ("iobuf-%d.%d: underflow: eof\n", a->no, a->subno);
1889 return a->d.buf[a->d.start++];
1894 log_debug ("iobuf-%d.%d: underflow: eof (no filter)\n",
1896 return -1; /* no filter; return EOF */
1902 iobuf_flush (iobuf_t a)
1911 { /* increase the temp buffer */
1912 unsigned char *newbuf;
1913 size_t newsize = a->d.size + IOBUF_BUFFER_SIZE;
1916 log_debug ("increasing temp iobuf from %lu to %lu\n",
1917 (ulong) a->d.size, (ulong) newsize);
1918 newbuf = xmalloc (newsize);
1919 memcpy (newbuf, a->d.buf, a->d.len);
1922 a->d.size = newsize;
1925 else if (a->use != 2)
1926 log_bug ("flush on non-output iobuf\n");
1927 else if (!a->filter)
1928 log_bug ("iobuf_flush: no filter\n");
1930 rc = a->filter (a->filter_ov, IOBUFCTRL_FLUSH, a->chain, a->d.buf, &len);
1931 if (!rc && len != a->d.len)
1933 log_info ("iobuf_flush did not write all!\n");
1934 rc = GPG_ERR_INTERNAL;
1945 * Read a byte from the iobuf; returns -1 on EOF
1948 iobuf_readbyte (iobuf_t a)
1952 if (a->nlimit && a->nbytes >= a->nlimit)
1953 return -1; /* forced EOF */
1955 if (a->d.start < a->d.len)
1957 c = a->d.buf[a->d.start++];
1959 else if ((c = underflow (a)) == -1)
1960 return -1; /* EOF */
1968 iobuf_read (iobuf_t a, void *buffer, unsigned int buflen)
1970 unsigned char *buf = (unsigned char *)buffer;
1975 /* Handle special cases. */
1976 for (n = 0; n < buflen; n++)
1978 if ((c = iobuf_readbyte (a)) == -1)
1981 return -1; /* eof */
1995 if (n < buflen && a->d.start < a->d.len)
1997 unsigned size = a->d.len - a->d.start;
1998 if (size > buflen - n)
2001 memcpy (buf, a->d.buf + a->d.start, size);
2009 if ((c = underflow (a)) == -1)
2012 return n ? n : -1 /*EOF*/;
2027 * Have a look at the iobuf.
2028 * NOTE: This only works in special cases.
2031 iobuf_peek (iobuf_t a, byte * buf, unsigned buflen)
2038 if (!(a->d.start < a->d.len))
2040 if (underflow (a) == -1)
2042 /* And unget this character. */
2043 assert (a->d.start == 1);
2047 for (n = 0; n < buflen && (a->d.start + n) < a->d.len; n++, buf++)
2056 iobuf_writebyte (iobuf_t a, unsigned int c)
2063 if (a->d.len == a->d.size)
2064 if ((rc=iobuf_flush (a)))
2067 assert (a->d.len < a->d.size);
2068 a->d.buf[a->d.len++] = c;
2074 iobuf_write (iobuf_t a, const void *buffer, unsigned int buflen)
2076 const unsigned char *buf = (const unsigned char *)buffer;
2084 if (buflen && a->d.len < a->d.size)
2086 unsigned size = a->d.size - a->d.len;
2089 memcpy (a->d.buf + a->d.len, buf, size);
2096 rc = iobuf_flush (a);
2107 iobuf_writestr (iobuf_t a, const char *buf)
2112 if ((rc=iobuf_writebyte (a, *buf)))
2120 * copy the contents of TEMP to A.
2123 iobuf_write_temp (iobuf_t a, iobuf_t temp)
2126 pop_filter (temp, temp->filter, NULL);
2127 return iobuf_write (a, temp->d.buf, temp->d.len);
2131 * copy the contents of the temp io stream to BUFFER.
2134 iobuf_temp_to_buffer (iobuf_t a, byte * buffer, size_t buflen)
2136 size_t n = a->d.len;
2140 memcpy (buffer, a->d.buf, n);
2146 * Call this function to terminate processing of the temp stream
2147 * without closing it. This removes all filters from the stream
2148 * makes sure that iobuf_get_temp_{buffer,length}() returns correct
2152 iobuf_flush_temp (iobuf_t temp)
2155 pop_filter (temp, temp->filter, NULL);
2160 * Set a limit on how many bytes may be read from the input stream A.
2161 * Setting the limit to 0 disables this feature.
2164 iobuf_set_limit (iobuf_t a, off_t nlimit)
2171 a->ntotal += a->nbytes;
2177 /* Return the length of an open file A. IF OVERFLOW is not NULL it
2178 will be set to true if the file is larger than what off_t can cope
2179 with. The function return 0 on error or on overflow condition. */
2181 iobuf_get_filelength (iobuf_t a, int *overflow)
2190 FILE *fp = a->directfp;
2192 if ( !fstat(fileno(fp), &st) )
2194 log_error("fstat() failed: %s\n", strerror(errno) );
2198 /* Hmmm: file_filter may have already been removed */
2199 for ( ; a; a = a->chain )
2200 if ( !a->chain && a->filter == file_filter )
2202 file_filter_ctx_t *b = a->filter_ov;
2203 fp_or_fd_t fp = b->fp;
2205 #if defined(HAVE_W32_SYSTEM) && !defined(FILE_FILTER_USES_STDIO)
2207 static int (* __stdcall get_file_size_ex) (void *handle,
2208 LARGE_INTEGER *r_size);
2209 static int get_file_size_ex_initialized;
2211 if (!get_file_size_ex_initialized)
2215 handle = dlopen ("kernel32.dll", RTLD_LAZY);
2218 get_file_size_ex = dlsym (handle, "GetFileSizeEx");
2219 if (!get_file_size_ex)
2222 get_file_size_ex_initialized = 1;
2225 if (get_file_size_ex)
2227 /* This is a newer system with GetFileSizeEx; we use this
2228 then because it seem that GetFileSize won't return a
2229 proper error in case a file is larger than 4GB. */
2230 LARGE_INTEGER exsize;
2232 if (get_file_size_ex (fp, &exsize))
2234 if (!exsize.u.HighPart)
2235 return exsize.u.LowPart;
2243 if ((size=GetFileSize (fp, NULL)) != 0xffffffff)
2246 log_error ("GetFileSize for handle %p failed: %s\n",
2247 fp, w32_strerror (0));
2249 if ( !fstat(my_fileno(fp), &st) )
2251 log_error("fstat() failed: %s\n", strerror(errno) );
2253 break/*the for loop*/;
2260 /* Return the file descriptor of the underlying file or -1 if it is
2263 iobuf_get_fd (iobuf_t a)
2266 return fileno ( (FILE*)a->directfp );
2268 for ( ; a; a = a->chain )
2269 if (!a->chain && a->filter == file_filter)
2271 file_filter_ctx_t *b = a->filter_ov;
2272 fp_or_fd_t fp = b->fp;
2274 return my_fileno (fp);
2283 * Tell the file position, where the next read will take place
2286 iobuf_tell (iobuf_t a)
2288 return a->ntotal + a->nbytes;
2292 #if !defined(HAVE_FSEEKO) && !defined(fseeko)
2294 #ifdef HAVE_LIMITS_H
2295 # include <limits.h>
2298 # define LONG_MAX ((long) ((unsigned long) -1 >> 1))
2301 # define LONG_MIN (-1 - LONG_MAX)
2305 * A substitute for fseeko, for hosts that don't have it.
2308 fseeko (FILE * stream, off_t newpos, int whence)
2310 while (newpos != (long) newpos)
2312 long pos = newpos < 0 ? LONG_MIN : LONG_MAX;
2313 if (fseek (stream, pos, whence) != 0)
2318 return fseek (stream, (long) newpos, whence);
2323 * This is a very limited implementation. It simply discards all internal
2324 * buffering and removes all filters but the first one.
2327 iobuf_seek (iobuf_t a, off_t newpos)
2329 file_filter_ctx_t *b = NULL;
2333 FILE *fp = a->directfp;
2334 if (fseeko (fp, newpos, SEEK_SET))
2336 log_error ("can't seek: %s\n", strerror (errno));
2343 for (; a; a = a->chain)
2345 if (!a->chain && a->filter == file_filter)
2353 #ifdef FILE_FILTER_USES_STDIO
2354 if (fseeko (b->fp, newpos, SEEK_SET))
2356 log_error ("can't fseek: %s\n", strerror (errno));
2360 #ifdef HAVE_W32_SYSTEM
2361 if (SetFilePointer (b->fp, newpos, NULL, FILE_BEGIN) == 0xffffffff)
2363 log_error ("SetFilePointer failed on handle %p: ec=%d\n",
2364 b->fp, (int) GetLastError ());
2368 if (lseek (b->fp, newpos, SEEK_SET) == (off_t) - 1)
2370 log_error ("can't lseek: %s\n", strerror (errno));
2376 a->d.len = 0; /* discard buffer */
2383 /* remove filters, but the last */
2385 log_debug ("pop_filter called in iobuf_seek - please report\n");
2387 pop_filter (a, a->filter, NULL);
2398 * Retrieve the real filename
2401 iobuf_get_real_fname (iobuf_t a)
2404 return a->real_fname;
2406 /* the old solution */
2407 for (; a; a = a->chain)
2408 if (!a->chain && a->filter == file_filter)
2410 file_filter_ctx_t *b = a->filter_ov;
2411 return b->print_only_name ? NULL : b->fname;
2419 * Retrieve the filename
2422 iobuf_get_fname (iobuf_t a)
2424 for (; a; a = a->chain)
2425 if (!a->chain && a->filter == file_filter)
2427 file_filter_ctx_t *b = a->filter_ov;
2435 * enable partial block mode as described in the OpenPGP draft.
2436 * LEN is the first length byte on read, but ignored on writes.
2439 iobuf_set_partial_block_mode (iobuf_t a, size_t len)
2441 block_filter_ctx_t *ctx = xcalloc (1, sizeof *ctx);
2443 assert (a->use == 1 || a->use == 2);
2448 log_debug ("pop_filter called in set_partial_block_mode"
2449 " - please report\n");
2450 pop_filter (a, block_filter, NULL);
2457 iobuf_push_filter (a, block_filter, ctx);
2464 * Same as fgets() but if the buffer is too short a larger one will
2465 * be allocated up to some limit *max_length.
2466 * A line is considered a byte stream ending in a LF.
2467 * Returns the length of the line. EOF is indicated by a line of
2468 * length zero. The last LF may be missing due to an EOF.
2469 * is max_length is zero on return, the line has been truncated.
2471 * Note: The buffer is allocated with enough space to append a CR,LF,EOL
2474 iobuf_read_line (iobuf_t a, byte ** addr_of_buffer,
2475 unsigned *length_of_buffer, unsigned *max_length)
2478 char *buffer = (char *)*addr_of_buffer;
2479 unsigned length = *length_of_buffer;
2480 unsigned nbytes = 0;
2481 unsigned maxlen = *max_length;
2485 { /* must allocate a new buffer */
2487 buffer = xmalloc (length);
2488 *addr_of_buffer = (unsigned char *)buffer;
2489 *length_of_buffer = length;
2492 length -= 3; /* reserve 3 bytes (cr,lf,eol) */
2494 while ((c = iobuf_get (a)) != -1)
2496 if (nbytes == length)
2497 { /* increase the buffer */
2498 if (length > maxlen)
2499 { /* this is out limit */
2500 /* skip the rest of the line */
2501 while (c != '\n' && (c = iobuf_get (a)) != -1)
2503 *p++ = '\n'; /* always append a LF (we have reserved space) */
2505 *max_length = 0; /* indicate truncation */
2508 length += 3; /* correct for the reserved byte */
2509 length += length < 1024 ? 256 : 1024;
2510 buffer = xrealloc (buffer, length);
2511 *addr_of_buffer = (unsigned char *)buffer;
2512 *length_of_buffer = length;
2513 length -= 3; /* and reserve again */
2514 p = buffer + nbytes;
2521 *p = 0; /* make sure the line is a string */
2527 translate_file_handle (int fd, int for_write)
2529 #ifdef HAVE_W32_SYSTEM
2530 # ifdef FILE_FILTER_USES_STDIO
2531 fd = translate_sys2libc_fd (fd, for_write);
2539 x = (int) GetStdHandle (STD_INPUT_HANDLE);
2541 x = (int) GetStdHandle (STD_OUTPUT_HANDLE);
2543 x = (int) GetStdHandle (STD_ERROR_HANDLE);
2548 log_debug ("GetStdHandle(%d) failed: ec=%d\n",
2549 fd, (int) GetLastError ());
2562 iobuf_skip_rest (iobuf_t a, unsigned long n, int partial)
2568 if (a->nofast || a->d.start >= a->d.len)
2570 if (iobuf_readbyte (a) == -1)
2577 unsigned long count = a->d.len - a->d.start;
2579 a->d.start = a->d.len;
2585 unsigned long remaining = n;
2586 while (remaining > 0)
2588 if (a->nofast || a->d.start >= a->d.len)
2590 if (iobuf_readbyte (a) == -1)
2598 unsigned long count = a->d.len - a->d.start;
2599 if (count > remaining)
2604 a->d.start += count;