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
38 #endif /* __riscos__ */
44 /*-- Begin configurable part. --*/
46 /* The size of the internal buffers.
47 NOTE: If you change this value you MUST also adjust the regression
48 test "armored_key_8192" in armor.test! */
49 #define IOBUF_BUFFER_SIZE 8192
51 /* We don't want to use the STDIO based backend. If you change this
52 be aware that there is no fsync support for the stdio backend. */
53 #undef FILE_FILTER_USES_STDIO
55 /*-- End configurable part. --*/
58 /* Under W32 the default is to use the setmode call. Define a macro
59 which allows us to enable this call. */
60 #ifdef HAVE_W32_SYSTEM
61 # define USE_SETMODE 1
62 #endif /*HAVE_W32_SYSTEM*/
65 /* Definition of constants and macros used by our file filter
66 implementation. What we define here are 3 macros to make the
70 Is expanded to fileno(a) if using a stdion backend and to a if we
71 are using the low-level backend.
74 Is defined to fopen for the stdio backend and to direct_open if
75 we are using the low-evel backend.
78 Is defined to fopen for the stdio backend and to fd_cache_open if
79 we are using the low-evel backend.
82 Is the type we use for the backend stream or file descriptor.
84 INVALID_FP, FILEP_OR_FD_FOR_STDIN, FILEP_OR_FD_FOR_STDOUT
85 Are macros defined depending on the used backend.
88 #ifdef FILE_FILTER_USES_STDIO
89 # define my_fileno(a) fileno ((a))
90 # define my_fopen_ro(a,b) fopen ((a),(b))
91 # define my_fopen(a,b) fopen ((a),(b))
92 typedef FILE *fp_or_fd_t
;
93 # define INVALID_FP NULL
94 # define FILEP_OR_FD_FOR_STDIN (stdin)
95 # define FILEP_OR_FD_FOR_STDOUT (stdout)
96 #else /*!FILE_FILTER_USES_STDIO*/
97 # define my_fopen_ro(a,b) fd_cache_open ((a),(b))
98 # define my_fopen(a,b) direct_open ((a),(b))
99 # ifdef HAVE_W32_SYSTEM
100 /* (We assume that a HANDLE first into an int.) */
101 # define my_fileno(a) ((int)(a))
102 typedef HANDLE fp_or_fd_t
;
103 # define INVALID_FP ((HANDLE)-1)
104 # define FILEP_OR_FD_FOR_STDIN (GetStdHandle (STD_INPUT_HANDLE))
105 # define FILEP_OR_FD_FOR_STDOUT (GetStdHandle (STD_OUTPUT_HANDLE))
107 # else /*!HAVE_W32_SYSTEM*/
108 # define my_fileno(a) (a)
109 typedef int fp_or_fd_t
;
110 # define INVALID_FP (-1)
111 # define FILEP_OR_FD_FOR_STDIN (0)
112 # define FILEP_OR_FD_FOR_STDOUT (1)
113 # endif /*!HAVE_W32_SYSTEM*/
114 #endif /*!FILE_FILTER_USES_STDIO*/
116 /* The context used by the file filter. */
119 fp_or_fd_t fp
; /* Open file pointer or handle. */
123 int print_only_name
; /* Flags indicating that fname is not a real file. */
124 char fname
[1]; /* Name of the file. */
129 /* If we are not using stdio as the backend we make use of a "close
131 #ifndef FILE_FILTER_USES_STDIO
134 struct close_cache_s
*next
;
138 typedef struct close_cache_s
*close_cache_t
;
139 static close_cache_t close_cache
;
140 #endif /*!FILE_FILTER_USES_STDIO*/
144 #ifdef HAVE_W32_SYSTEM
151 int print_only_name
; /* Flag indicating that fname is not a real file. */
152 char fname
[1]; /* Name of the file */
155 #endif /*HAVE_W32_SYSTEM*/
157 /* The first partial length header block must be of size 512
158 * to make it easier (and efficienter) we use a min. block size of 512
159 * for all chunks (but the last one) */
160 #define OP_MIN_PARTIAL_CHUNK 512
161 #define OP_MIN_PARTIAL_CHUNK_2POW 9
163 /* The context we use for the block filter (used to handle OpenPGP
164 length information header). */
170 int partial
; /* 1 = partial header, 2 in last partial packet. */
171 char *buffer
; /* Used for partial header. */
172 size_t buflen
; /* Used size of buffer. */
173 int first_c
; /* First character of a partial header (which is > 0). */
179 /* Global flag to tell whether special file names are enabled. See
180 gpg.c for an explanation of these file names. FIXME: it does not
181 belong into the iobuf subsystem. */
182 static int special_names_enabled
;
184 /* Local prototypes. */
185 static int underflow (iobuf_t a
);
186 static int translate_file_handle (int fd
, int for_write
);
190 #ifndef FILE_FILTER_USES_STDIO
191 /* This is a replacement for strcmp. Under W32 it does not
192 distinguish between backslash and slash. */
194 fd_cache_strcmp (const char *a
, const char *b
)
196 #ifdef HAVE_DOSISH_SYSTEM
197 for (; *a
&& *b
; a
++, b
++)
199 if (*a
!= *b
&& !((*a
== '/' && *b
== '\\')
200 || (*a
== '\\' && *b
== '/')) )
203 return *(const unsigned char *)a
- *(const unsigned char *)b
;
205 return strcmp (a
, b
);
210 * Invalidate (i.e. close) a cached iobuf
213 fd_cache_invalidate (const char *fname
)
220 log_debug ("fd_cache_invalidate (%s)\n", fname
);
222 for (cc
= close_cache
; cc
; cc
= cc
->next
)
224 if (cc
->fp
!= INVALID_FP
&& !fd_cache_strcmp (cc
->fname
, fname
))
227 log_debug (" did (%s)\n", cc
->fname
);
228 #ifdef HAVE_W32_SYSTEM
229 if (!CloseHandle (cc
->fp
))
241 /* Try to sync changes to the disk. This is to avoid data loss during
242 a system crash in write/close/rename cycle on some file
245 fd_cache_synchronize (const char *fname
)
253 log_debug ("fd_cache_synchronize (%s)\n", fname
);
255 for (cc
=close_cache
; cc
; cc
= cc
->next
)
257 if (cc
->fp
!= INVALID_FP
&& !fd_cache_strcmp (cc
->fname
, fname
))
260 log_debug (" did (%s)\n", cc
->fname
);
262 err
= fsync (cc
->fp
);
267 #endif /*HAVE_FSYNC*/
274 direct_open (const char *fname
, const char *mode
)
276 #ifdef HAVE_W32_SYSTEM
277 unsigned long da
, cd
, sm
;
280 /* Note, that we do not handle all mode combinations */
282 /* According to the ReactOS source it seems that open() of the
283 * standard MSW32 crt does open the file in shared mode which is
284 * something new for MS applications ;-)
286 if (strchr (mode
, '+'))
288 if (fd_cache_invalidate (fname
))
290 da
= GENERIC_READ
| GENERIC_WRITE
;
292 sm
= FILE_SHARE_READ
| FILE_SHARE_WRITE
;
294 else if (strchr (mode
, 'w'))
296 if (fd_cache_invalidate (fname
))
300 sm
= FILE_SHARE_WRITE
;
306 sm
= FILE_SHARE_READ
;
309 hfile
= CreateFile (fname
, da
, sm
, NULL
, cd
, FILE_ATTRIBUTE_NORMAL
, NULL
);
311 #else /*!HAVE_W32_SYSTEM*/
313 int cflag
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
;
315 /* Note, that we do not handle all mode combinations */
316 if (strchr (mode
, '+'))
318 if (fd_cache_invalidate (fname
))
322 else if (strchr (mode
, 'w'))
324 if (fd_cache_invalidate (fname
))
326 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
333 if (strchr (mode
, 'b'))
336 /* No we need to distinguish between POSIX and RISC OS. */
338 return open (fname
, oflag
, cflag
);
342 int rc
= stat (fname
, &buf
);
344 /* Don't allow iobufs on directories */
345 if (!rc
&& S_ISDIR (buf
.st_mode
) && !S_ISREG (buf
.st_mode
))
346 return __set_errno (EISDIR
);
348 return open (fname
, oflag
, cflag
);
351 #endif /*!HAVE_W32_SYSTEM*/
356 * Instead of closing an FD we keep it open and cache it for later reuse
357 * Note that this caching strategy only works if the process does not chdir.
360 fd_cache_close (const char *fname
, fp_or_fd_t fp
)
365 if (!fname
|| !*fname
)
367 #ifdef HAVE_W32_SYSTEM
373 log_debug ("fd_cache_close (%d) real\n", (int)fp
);
376 /* try to reuse a slot */
377 for (cc
= close_cache
; cc
; cc
= cc
->next
)
379 if (cc
->fp
== INVALID_FP
&& !fd_cache_strcmp (cc
->fname
, fname
))
383 log_debug ("fd_cache_close (%s) used existing slot\n", fname
);
389 log_debug ("fd_cache_close (%s) new slot created\n", fname
);
390 cc
= xcalloc (1, sizeof *cc
+ strlen (fname
));
391 strcpy (cc
->fname
, fname
);
393 cc
->next
= close_cache
;
398 * Do an direct_open on FNAME but first try to reuse one from the fd_cache
401 fd_cache_open (const char *fname
, const char *mode
)
406 for (cc
= close_cache
; cc
; cc
= cc
->next
)
408 if (cc
->fp
!= INVALID_FP
&& !fd_cache_strcmp (cc
->fname
, fname
))
410 fp_or_fd_t fp
= cc
->fp
;
413 log_debug ("fd_cache_open (%s) using cached fp\n", fname
);
414 #ifdef HAVE_W32_SYSTEM
415 if (SetFilePointer (fp
, 0, NULL
, FILE_BEGIN
) == 0xffffffff)
417 log_error ("rewind file failed on handle %p: ec=%d\n",
418 fp
, (int) GetLastError ());
422 if (lseek (fp
, 0, SEEK_SET
) == (off_t
) - 1)
424 log_error ("can't rewind fd %d: %s\n", fp
, strerror (errno
));
432 log_debug ("fd_cache_open (%s) not cached\n", fname
);
433 return direct_open (fname
, mode
);
436 #endif /*FILE_FILTER_USES_STDIO */
440 * Read data from a file into buf which has an allocated length of *LEN.
441 * return the number of read bytes in *LEN. OPAQUE is the FILE * of
442 * the stream. A is not used.
444 * IOBUFCTRL_INIT: called just before the function is linked into the
445 * list of function. This can be used to prepare internal
446 * data structures of the function.
447 * IOBUFCTRL_FREE: called just before the function is removed from the
448 * list of functions and can be used to release internal
449 * data structures or close a file etc.
450 * IOBUFCTRL_UNDERFLOW: called by iobuf_underflow to fill the buffer
451 * with new stuff. *RET_LEN is the available size of the
452 * buffer, and should be set to the number of bytes
453 * which were put into the buffer. The function
454 * returns 0 to indicate success, -1 on EOF and
455 * GPG_ERR_xxxxx for other errors.
457 * IOBUFCTRL_FLUSH: called by iobuf_flush() to write out the collected stuff.
458 * *RET_LAN is the number of bytes in BUF.
460 * IOBUFCTRL_CANCEL: send to all filters on behalf of iobuf_cancel. The
461 * filter may take appropriate action on this message.
464 file_filter (void *opaque
, int control
, iobuf_t chain
, byte
* buf
,
467 file_filter_ctx_t
*a
= opaque
;
468 fp_or_fd_t f
= a
->fp
;
469 size_t size
= *ret_len
;
473 (void)chain
; /* Not used. */
475 #ifdef FILE_FILTER_USES_STDIO
476 if (control
== IOBUFCTRL_UNDERFLOW
)
478 assert (size
); /* We need a buffer. */
481 /* On terminals you could easily read as many EOFs as you
482 call fread() or fgetc() repeatly. Every call will block
483 until you press CTRL-D. So we catch this case before we
484 call fread() again. */
491 nbytes
= fread (buf
, 1, size
, f
);
492 if (feof (f
) && !nbytes
)
494 rc
= -1; /* Okay: we can return EOF now. */
496 else if (ferror (f
) && errno
!= EPIPE
)
498 rc
= gpg_error_from_syserror ();
499 log_error ("%s: read error: %s\n", a
->fname
, strerror (errno
));
504 else if (control
== IOBUFCTRL_FLUSH
)
509 nbytes
= fwrite (buf
, 1, size
, f
);
512 rc
= gpg_error_from_syserror ();
513 log_error ("%s: write error: %s\n", a
->fname
, strerror (errno
));
518 else if (control
== IOBUFCTRL_INIT
)
520 a
->keep_open
= a
->no_cache
= 0;
522 else if (control
== IOBUFCTRL_DESC
)
524 *(char **) buf
= "file_filter";
526 else if (control
== IOBUFCTRL_FREE
)
528 if (f
!= stdin
&& f
!= stdout
)
531 log_debug ("%s: close fd %d\n", a
->fname
, fileno (f
));
536 xfree (a
); /* We can free our context now. */
538 #else /* !stdio implementation */
540 if (control
== IOBUFCTRL_UNDERFLOW
)
542 assert (size
); /* We need a buffer. */
550 #ifdef HAVE_W32_SYSTEM
554 if (!ReadFile (f
, buf
, size
, &nread
, NULL
))
556 int ec
= (int) GetLastError ();
557 if (ec
!= ERROR_BROKEN_PIPE
)
559 rc
= gpg_error_from_errno (ec
);
560 log_error ("%s: read error: ec=%d\n", a
->fname
, ec
);
580 n
= read (f
, buf
, size
);
582 while (n
== -1 && errno
== EINTR
);
587 rc
= gpg_error_from_syserror ();
588 log_error ("%s: read error: %s\n",
589 a
->fname
, strerror (errno
));
605 else if (control
== IOBUFCTRL_FLUSH
)
609 #ifdef HAVE_W32_SYSTEM
616 if (size
&& !WriteFile (f
, p
, nbytes
, &n
, NULL
))
618 int ec
= (int) GetLastError ();
619 rc
= gpg_error_from_errno (ec
);
620 log_error ("%s: write error: ec=%d\n", a
->fname
, ec
);
637 n
= write (f
, p
, nbytes
);
639 while (n
== -1 && errno
== EINTR
);
646 while (n
!= -1 && nbytes
);
649 rc
= gpg_error_from_syserror ();
650 log_error ("%s: write error: %s\n", a
->fname
, strerror (errno
));
657 else if (control
== IOBUFCTRL_INIT
)
663 else if (control
== IOBUFCTRL_DESC
)
665 *(char **) buf
= "file_filter(fd)";
667 else if (control
== IOBUFCTRL_FREE
)
669 #ifdef HAVE_W32_SYSTEM
670 if (f
!= FILEP_OR_FD_FOR_STDIN
&& f
!= FILEP_OR_FD_FOR_STDOUT
)
673 log_debug ("%s: close handle %p\n", a
->fname
, f
);
675 fd_cache_close (a
->no_cache
? NULL
: a
->fname
, f
);
678 if ((int) f
!= 0 && (int) f
!= 1)
681 log_debug ("%s: close fd %d\n", a
->fname
, f
);
683 fd_cache_close (a
->no_cache
? NULL
: a
->fname
, f
);
687 xfree (a
); /* We can free our context now. */
689 #endif /* !stdio implementation. */
694 #ifdef HAVE_W32_SYSTEM
695 /* Because network sockets are special objects under Lose32 we have to
696 use a dedicated filter for them. */
698 sock_filter (void *opaque
, int control
, iobuf_t chain
, byte
* buf
,
701 sock_filter_ctx_t
*a
= opaque
;
702 size_t size
= *ret_len
;
708 if (control
== IOBUFCTRL_UNDERFLOW
)
710 assert (size
); /* need a buffer */
720 nread
= recv (a
->sock
, buf
, size
, 0);
721 if (nread
== SOCKET_ERROR
)
723 int ec
= (int) WSAGetLastError ();
724 rc
= gpg_error_from_errno (ec
);
725 log_error ("socket read error: ec=%d\n", ec
);
739 else if (control
== IOBUFCTRL_FLUSH
)
749 n
= send (a
->sock
, p
, nbytes
, 0);
750 if (n
== SOCKET_ERROR
)
752 int ec
= (int) WSAGetLastError ();
753 rc
= gpg_error_from_errno (ec
);
754 log_error ("socket write error: ec=%d\n", ec
);
765 else if (control
== IOBUFCTRL_INIT
)
771 else if (control
== IOBUFCTRL_DESC
)
773 *(char **) buf
= "sock_filter";
775 else if (control
== IOBUFCTRL_FREE
)
778 closesocket (a
->sock
);
779 xfree (a
); /* we can free our context now */
783 #endif /*HAVE_W32_SYSTEM*/
786 * This is used to implement the block write mode.
787 * Block reading is done on a byte by byte basis in readbyte(),
791 block_filter (void *opaque
, int control
, iobuf_t chain
, byte
* buffer
,
794 block_filter_ctx_t
*a
= opaque
;
795 char *buf
= (char *)buffer
;
796 size_t size
= *ret_len
;
797 int c
, needed
, rc
= 0;
800 if (control
== IOBUFCTRL_UNDERFLOW
)
805 assert (size
); /* need a buffer */
806 if (a
->eof
) /* don't read any further */
811 { /* get the length bytes */
821 /* These OpenPGP introduced huffman like encoded length
822 * bytes are really a mess :-( */
828 else if ((c
= iobuf_get (chain
)) == -1)
830 log_error ("block_filter: 1st length byte missing\n");
831 rc
= GPG_ERR_BAD_DATA
;
848 a
->size
= (c
- 192) * 256;
849 if ((c
= iobuf_get (chain
)) == -1)
852 ("block_filter: 2nd length byte missing\n");
853 rc
= GPG_ERR_BAD_DATA
;
868 a
->size
= iobuf_get (chain
) << 24;
869 a
->size
|= iobuf_get (chain
) << 16;
870 a
->size
|= iobuf_get (chain
) << 8;
871 if ((c
= iobuf_get (chain
)) == -1)
873 log_error ("block_filter: invalid 4 byte length\n");
874 rc
= GPG_ERR_BAD_DATA
;
888 { /* Next partial body length. */
889 a
->size
= 1 << (c
& 0x1f);
891 /* log_debug("partial: ctx=%p c=%02x size=%u\n", a, c, a->size); */
897 while (!rc
&& size
&& a
->size
)
899 needed
= size
< a
->size
? size
: a
->size
;
900 c
= iobuf_read (chain
, p
, needed
);
906 ("block_filter %p: read error (size=%lu,a->size=%lu)\n",
907 a
, (ulong
) size
+ c
, (ulong
) a
->size
+ c
);
908 rc
= GPG_ERR_BAD_DATA
;
921 else if (control
== IOBUFCTRL_FLUSH
)
924 { /* the complicated openpgp scheme */
925 size_t blen
, n
, nbytes
= size
+ a
->buflen
;
927 assert (a
->buflen
<= OP_MIN_PARTIAL_CHUNK
);
928 if (nbytes
< OP_MIN_PARTIAL_CHUNK
)
930 /* not enough to write a partial block out; so we store it */
932 a
->buffer
= xmalloc (OP_MIN_PARTIAL_CHUNK
);
933 memcpy (a
->buffer
+ a
->buflen
, buf
, size
);
937 { /* okay, we can write out something */
938 /* do this in a loop to use the most efficient block lengths */
942 /* find the best matching block length - this is limited
943 * by the size of the internal buffering */
944 for (blen
= OP_MIN_PARTIAL_CHUNK
* 2,
945 c
= OP_MIN_PARTIAL_CHUNK_2POW
+ 1; blen
<= nbytes
;
950 /* write the partial length header */
951 assert (c
<= 0x1f); /*;-) */
953 iobuf_put (chain
, c
);
955 { /* write stuff from the buffer */
956 assert (n
== OP_MIN_PARTIAL_CHUNK
);
957 if (iobuf_write (chain
, a
->buffer
, n
))
958 rc
= gpg_error_from_syserror ();
962 if ((n
= nbytes
) > blen
)
964 if (n
&& iobuf_write (chain
, p
, n
))
965 rc
= gpg_error_from_syserror ();
969 while (!rc
&& nbytes
>= OP_MIN_PARTIAL_CHUNK
);
970 /* store the rest in the buffer */
974 assert (nbytes
< OP_MIN_PARTIAL_CHUNK
);
976 a
->buffer
= xmalloc (OP_MIN_PARTIAL_CHUNK
);
977 memcpy (a
->buffer
, p
, nbytes
);
985 else if (control
== IOBUFCTRL_INIT
)
988 log_debug ("init block_filter %p\n", a
);
991 else if (a
->use
== 1)
992 a
->count
= a
->size
= 0;
994 a
->count
= a
->size
; /* force first length bytes */
999 else if (control
== IOBUFCTRL_DESC
)
1001 *(char **) buf
= "block_filter";
1003 else if (control
== IOBUFCTRL_FREE
)
1006 { /* write the end markers */
1010 /* write out the remaining bytes without a partial header
1011 * the length of this header may be 0 - but if it is
1012 * the first block we are not allowed to use a partial header
1013 * and frankly we can't do so, because this length must be
1014 * a power of 2. This is _really_ complicated because we
1015 * have to check the possible length of a packet prior
1016 * to it's creation: a chain of filters becomes complicated
1017 * and we need a lot of code to handle compressed packets etc.
1020 /* construct header */
1022 /*log_debug("partial: remaining length=%u\n", len ); */
1024 rc
= iobuf_put (chain
, len
);
1025 else if (len
< 8384)
1027 if (!(rc
= iobuf_put (chain
, ((len
- 192) / 256) + 192)))
1028 rc
= iobuf_put (chain
, ((len
- 192) % 256));
1031 { /* use a 4 byte header */
1032 if (!(rc
= iobuf_put (chain
, 0xff)))
1033 if (!(rc
= iobuf_put (chain
, (len
>> 24) & 0xff)))
1034 if (!(rc
= iobuf_put (chain
, (len
>> 16) & 0xff)))
1035 if (!(rc
= iobuf_put (chain
, (len
>> 8) & 0xff)))
1036 rc
= iobuf_put (chain
, len
& 0xff);
1039 rc
= iobuf_write (chain
, a
->buffer
, len
);
1042 log_error ("block_filter: write error: %s\n",
1044 rc
= gpg_error_from_syserror ();
1055 log_error ("block_filter: pending bytes!\n");
1058 log_debug ("free block_filter %p\n", a
);
1059 xfree (a
); /* we can free our context now */
1067 print_chain (iobuf_t a
)
1071 for (; a
; a
= a
->chain
)
1073 size_t dummy_len
= 0;
1074 const char *desc
= "[none]";
1077 a
->filter (a
->filter_ov
, IOBUFCTRL_DESC
, NULL
,
1078 (byte
*) & desc
, &dummy_len
);
1080 log_debug ("iobuf chain: %d.%d `%s' filter_eof=%d start=%d len=%d\n",
1081 a
->no
, a
->subno
, desc
?desc
:"?", a
->filter_eof
,
1082 (int) a
->d
.start
, (int) a
->d
.len
);
1087 iobuf_print_chain (iobuf_t a
)
1094 * Allocate a new io buffer, with no function assigned.
1095 * Use is the desired usage: 1 for input, 2 for output, 3 for temp buffer
1096 * BUFSIZE is a suggested buffer size.
1099 iobuf_alloc (int use
, size_t bufsize
)
1102 static int number
= 0;
1104 a
= xcalloc (1, sizeof *a
);
1106 a
->d
.buf
= xmalloc (bufsize
);
1107 a
->d
.size
= bufsize
;
1111 a
->real_fname
= NULL
;
1116 iobuf_close (iobuf_t a
)
1119 size_t dummy_len
= 0;
1122 if (a
&& a
->directfp
)
1124 fclose (a
->directfp
);
1125 xfree (a
->real_fname
);
1127 log_debug ("iobuf_close -> %p\n", a
->directfp
);
1131 for (; a
&& !rc
; a
= a2
)
1134 if (a
->use
== 2 && (rc
= iobuf_flush (a
)))
1135 log_error ("iobuf_flush failed on close: %s\n", gpg_strerror (rc
));
1138 log_debug ("iobuf-%d.%d: close `%s'\n", a
->no
, a
->subno
,
1139 a
->desc
?a
->desc
:"?");
1140 if (a
->filter
&& (rc
= a
->filter (a
->filter_ov
, IOBUFCTRL_FREE
,
1141 a
->chain
, NULL
, &dummy_len
)))
1142 log_error ("IOBUFCTRL_FREE failed on close: %s\n", gpg_strerror (rc
));
1143 xfree (a
->real_fname
);
1146 memset (a
->d
.buf
, 0, a
->d
.size
); /* erase the buffer */
1155 iobuf_cancel (iobuf_t a
)
1160 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1161 char *remove_name
= NULL
;
1164 if (a
&& a
->use
== 2)
1166 s
= iobuf_get_real_fname (a
);
1169 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1170 remove_name
= xstrdup (s
);
1177 /* send a cancel message to all filters */
1178 for (a2
= a
; a2
; a2
= a2
->chain
)
1182 a2
->filter (a2
->filter_ov
, IOBUFCTRL_CANCEL
, a2
->chain
, NULL
, &dummy
);
1185 rc
= iobuf_close (a
);
1186 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1189 /* Argg, MSDOS does not allow to remove open files. So
1190 * we have to do it here */
1191 remove (remove_name
);
1192 xfree (remove_name
);
1200 * create a temporary iobuf, which can be used to collect stuff
1201 * in an iobuf and later be written by iobuf_write_temp() to another
1209 a
= iobuf_alloc (3, IOBUF_BUFFER_SIZE
);
1215 iobuf_temp_with_content (const char *buffer
, size_t length
)
1219 a
= iobuf_alloc (3, length
);
1220 memcpy (a
->d
.buf
, buffer
, length
);
1227 iobuf_enable_special_filenames (int yes
)
1229 special_names_enabled
= yes
;
1233 /* See whether the filename has the form "-&nnnn", where n is a
1234 non-zero number. Returns this number or -1 if it is not the
1237 check_special_filename (const char *fname
)
1239 if (special_names_enabled
&& fname
&& *fname
== '-' && fname
[1] == '&')
1244 for (i
= 0; digitp (fname
+i
); i
++)
1247 return atoi (fname
);
1253 /* This fucntion returns true if FNAME indicates a PIPE (stdout or
1254 stderr) or a special file name if those are enabled. */
1256 iobuf_is_pipe_filename (const char *fname
)
1258 if (!fname
|| (*fname
=='-' && !fname
[1]) )
1260 return check_special_filename (fname
) != -1;
1264 /* Either open the file specified by the file descriptor FD or - if FD
1265 is -1, the file with name FNAME. As of now MODE is assumed to be
1266 "rb" if FNAME is used. In contrast to iobuf_fdopen the file
1267 descriptor FD will not be closed during an iobuf_close. */
1269 iobuf_open_fd_or_name (int fd
, const char *fname
, const char *mode
)
1274 a
= iobuf_open (fname
);
1283 a
= iobuf_fdopen (fd2
, mode
);
1290 * Create a head iobuf for reading from a file
1291 * returns: NULL if an error occures and sets errno
1294 iobuf_open (const char *fname
)
1298 file_filter_ctx_t
*fcx
;
1303 if (!fname
|| (*fname
== '-' && !fname
[1]))
1305 fp
= FILEP_OR_FD_FOR_STDIN
;
1307 setmode (my_fileno (fp
), O_BINARY
);
1312 else if ((fd
= check_special_filename (fname
)) != -1)
1313 return iobuf_fdopen (translate_file_handle (fd
, 0), "rb");
1314 else if ((fp
= my_fopen_ro (fname
, "rb")) == INVALID_FP
)
1316 a
= iobuf_alloc (1, IOBUF_BUFFER_SIZE
);
1317 fcx
= xmalloc (sizeof *fcx
+ strlen (fname
));
1319 fcx
->print_only_name
= print_only
;
1320 strcpy (fcx
->fname
, fname
);
1322 a
->real_fname
= xstrdup (fname
);
1323 a
->filter
= file_filter
;
1325 file_filter (fcx
, IOBUFCTRL_DESC
, NULL
, (byte
*) & a
->desc
, &len
);
1326 file_filter (fcx
, IOBUFCTRL_INIT
, NULL
, NULL
, &len
);
1328 log_debug ("iobuf-%d.%d: open `%s' fd=%d\n",
1329 a
->no
, a
->subno
, fname
, (int) my_fileno (fcx
->fp
));
1335 * Create a head iobuf for reading or writing from/to a file
1336 * Returns: NULL if an error occures and sets ERRNO.
1339 iobuf_fdopen (int fd
, const char *mode
)
1343 file_filter_ctx_t
*fcx
;
1346 #ifdef FILE_FILTER_USES_STDIO
1347 if (!(fp
= fdopen (fd
, mode
)))
1350 fp
= (fp_or_fd_t
) fd
;
1352 a
= iobuf_alloc (strchr (mode
, 'w') ? 2 : 1, IOBUF_BUFFER_SIZE
);
1353 fcx
= xmalloc (sizeof *fcx
+ 20);
1355 fcx
->print_only_name
= 1;
1356 sprintf (fcx
->fname
, "[fd %d]", fd
);
1357 a
->filter
= file_filter
;
1359 file_filter (fcx
, IOBUFCTRL_DESC
, NULL
, (byte
*) & a
->desc
, &len
);
1360 file_filter (fcx
, IOBUFCTRL_INIT
, NULL
, NULL
, &len
);
1362 log_debug ("iobuf-%d.%d: fdopen `%s'\n", a
->no
, a
->subno
, fcx
->fname
);
1363 iobuf_ioctl (a
, 3, 1, NULL
); /* disable fd caching */
1369 iobuf_sockopen (int fd
, const char *mode
)
1372 #ifdef HAVE_W32_SYSTEM
1373 sock_filter_ctx_t
*scx
;
1376 a
= iobuf_alloc (strchr (mode
, 'w') ? 2 : 1, IOBUF_BUFFER_SIZE
);
1377 scx
= xmalloc (sizeof *scx
+ 25);
1379 scx
->print_only_name
= 1;
1380 sprintf (scx
->fname
, "[sock %d]", fd
);
1381 a
->filter
= sock_filter
;
1383 sock_filter (scx
, IOBUFCTRL_DESC
, NULL
, (byte
*) & a
->desc
, &len
);
1384 sock_filter (scx
, IOBUFCTRL_INIT
, NULL
, NULL
, &len
);
1386 log_debug ("iobuf-%d.%d: sockopen `%s'\n", a
->no
, a
->subno
, scx
->fname
);
1387 iobuf_ioctl (a
, 3, 1, NULL
); /* disable fd caching */
1389 a
= iobuf_fdopen (fd
, mode
);
1395 * create an iobuf for writing to a file; the file will be created.
1398 iobuf_create (const char *fname
)
1402 file_filter_ctx_t
*fcx
;
1407 if (!fname
|| (*fname
== '-' && !fname
[1]))
1409 fp
= FILEP_OR_FD_FOR_STDOUT
;
1411 setmode (my_fileno (fp
), O_BINARY
);
1416 else if ((fd
= check_special_filename (fname
)) != -1)
1417 return iobuf_fdopen (translate_file_handle (fd
, 1), "wb");
1418 else if ((fp
= my_fopen (fname
, "wb")) == INVALID_FP
)
1420 a
= iobuf_alloc (2, IOBUF_BUFFER_SIZE
);
1421 fcx
= xmalloc (sizeof *fcx
+ strlen (fname
));
1423 fcx
->print_only_name
= print_only
;
1424 strcpy (fcx
->fname
, fname
);
1426 a
->real_fname
= xstrdup (fname
);
1427 a
->filter
= file_filter
;
1429 file_filter (fcx
, IOBUFCTRL_DESC
, NULL
, (byte
*) & a
->desc
, &len
);
1430 file_filter (fcx
, IOBUFCTRL_INIT
, NULL
, NULL
, &len
);
1432 log_debug ("iobuf-%d.%d: create `%s'\n", a
->no
, a
->subno
,
1433 a
->desc
?a
->desc
:"?");
1439 * append to an iobuf; if the file does not exist, create it.
1440 * cannot be used for stdout.
1441 * Note: This is not used.
1443 #if 0 /* not used */
1445 iobuf_append (const char *fname
)
1449 file_filter_ctx_t
*fcx
;
1454 else if (!(fp
= my_fopen (fname
, "ab")))
1456 a
= iobuf_alloc (2, IOBUF_BUFFER_SIZE
);
1457 fcx
= m_alloc (sizeof *fcx
+ strlen (fname
));
1459 strcpy (fcx
->fname
, fname
);
1460 a
->real_fname
= m_strdup (fname
);
1461 a
->filter
= file_filter
;
1463 file_filter (fcx
, IOBUFCTRL_DESC
, NULL
, (byte
*) & a
->desc
, &len
);
1464 file_filter (fcx
, IOBUFCTRL_INIT
, NULL
, NULL
, &len
);
1466 log_debug ("iobuf-%d.%d: append `%s'\n", a
->no
, a
->subno
,
1467 a
->desc
?a
->desc
:"?");
1474 iobuf_openrw (const char *fname
)
1478 file_filter_ctx_t
*fcx
;
1483 else if ((fp
= my_fopen (fname
, "r+b")) == INVALID_FP
)
1485 a
= iobuf_alloc (2, IOBUF_BUFFER_SIZE
);
1486 fcx
= xmalloc (sizeof *fcx
+ strlen (fname
));
1488 strcpy (fcx
->fname
, fname
);
1489 a
->real_fname
= xstrdup (fname
);
1490 a
->filter
= file_filter
;
1492 file_filter (fcx
, IOBUFCTRL_DESC
, NULL
, (byte
*) & a
->desc
, &len
);
1493 file_filter (fcx
, IOBUFCTRL_INIT
, NULL
, NULL
, &len
);
1495 log_debug ("iobuf-%d.%d: openrw `%s'\n", a
->no
, a
->subno
,
1496 a
->desc
?a
->desc
:"?");
1503 iobuf_ioctl (iobuf_t a
, int cmd
, int intval
, void *ptrval
)
1506 { /* keep system filepointer/descriptor open */
1508 log_debug ("iobuf-%d.%d: ioctl `%s' keep=%d\n",
1509 a
? a
->no
: -1, a
? a
->subno
: -1,
1510 a
&& a
->desc
? a
->desc
: "?",
1512 for (; a
; a
= a
->chain
)
1513 if (!a
->chain
&& a
->filter
== file_filter
)
1515 file_filter_ctx_t
*b
= a
->filter_ov
;
1516 b
->keep_open
= intval
;
1519 #ifdef HAVE_W32_SYSTEM
1520 else if (!a
->chain
&& a
->filter
== sock_filter
)
1522 sock_filter_ctx_t
*b
= a
->filter_ov
;
1523 b
->keep_open
= intval
;
1529 { /* invalidate cache */
1531 log_debug ("iobuf-*.*: ioctl `%s' invalidate\n",
1532 ptrval
? (char *) ptrval
: "?");
1533 if (!a
&& !intval
&& ptrval
)
1535 #ifndef FILE_FILTER_USES_STDIO
1536 if (fd_cache_invalidate (ptrval
))
1543 { /* disallow/allow caching */
1545 log_debug ("iobuf-%d.%d: ioctl `%s' no_cache=%d\n",
1546 a
? a
->no
: -1, a
? a
->subno
: -1,
1547 a
&& a
->desc
? a
->desc
: "?",
1549 for (; a
; a
= a
->chain
)
1550 if (!a
->chain
&& a
->filter
== file_filter
)
1552 file_filter_ctx_t
*b
= a
->filter_ov
;
1553 b
->no_cache
= intval
;
1556 #ifdef HAVE_W32_SYSTEM
1557 else if (!a
->chain
&& a
->filter
== sock_filter
)
1559 sock_filter_ctx_t
*b
= a
->filter_ov
;
1560 b
->no_cache
= intval
;
1567 /* Do a fsync on the open fd and return any errors to the caller
1568 of iobuf_ioctl. Note that we work on a file name here. */
1570 log_debug ("iobuf-*.*: ioctl `%s' fsync\n",
1571 ptrval
? (const char*)ptrval
:"<null>");
1573 if (!a
&& !intval
&& ptrval
)
1575 #ifndef FILE_FILTER_USES_STDIO
1576 return fd_cache_synchronize (ptrval
);
1589 * Register an i/o filter.
1592 iobuf_push_filter (iobuf_t a
,
1593 int (*f
) (void *opaque
, int control
,
1594 iobuf_t chain
, byte
* buf
, size_t * len
),
1597 return iobuf_push_filter2 (a
, f
, ov
, 0);
1601 iobuf_push_filter2 (iobuf_t a
,
1602 int (*f
) (void *opaque
, int control
,
1603 iobuf_t chain
, byte
* buf
, size_t * len
),
1604 void *ov
, int rel_ov
)
1607 size_t dummy_len
= 0;
1613 if (a
->use
== 2 && (rc
= iobuf_flush (a
)))
1615 /* make a copy of the current stream, so that
1616 * A is the new stream and B the original one.
1617 * The contents of the buffers are transferred to the
1620 b
= xmalloc (sizeof *b
);
1621 memcpy (b
, a
, sizeof *b
);
1622 /* fixme: it is stupid to keep a copy of the name at every level
1623 * but we need the name somewhere because the name known by file_filter
1624 * may have been released when we need the name of the file */
1625 b
->real_fname
= a
->real_fname
? xstrdup (a
->real_fname
) : NULL
;
1626 /* remove the filter stuff from the new stream */
1628 a
->filter_ov
= NULL
;
1629 a
->filter_ov_owner
= 0;
1632 a
->use
= 2; /* make a write stream from a temp stream */
1635 { /* allocate a fresh buffer for the
1637 b
->d
.buf
= xmalloc (a
->d
.size
);
1642 { /* allocate a fresh buffer for the new
1644 a
->d
.buf
= xmalloc (a
->d
.size
);
1648 /* disable nlimit for the new stream */
1649 a
->ntotal
= b
->ntotal
+ b
->nbytes
;
1650 a
->nlimit
= a
->nbytes
= 0;
1652 /* make a link from the new stream to the original stream */
1654 a
->opaque
= b
->opaque
;
1656 /* setup the function on the new stream */
1659 a
->filter_ov_owner
= rel_ov
;
1661 a
->subno
= b
->subno
+ 1;
1662 f (ov
, IOBUFCTRL_DESC
, NULL
, (byte
*) & a
->desc
, &dummy_len
);
1666 log_debug ("iobuf-%d.%d: push `%s'\n", a
->no
, a
->subno
,
1667 a
->desc
?a
->desc
:"?");
1671 /* now we can initialize the new function if we have one */
1672 if (a
->filter
&& (rc
= a
->filter (a
->filter_ov
, IOBUFCTRL_INIT
, a
->chain
,
1674 log_error ("IOBUFCTRL_INIT failed: %s\n", gpg_strerror (rc
));
1679 * Remove an i/o filter.
1682 pop_filter (iobuf_t a
, int (*f
) (void *opaque
, int control
,
1683 iobuf_t chain
, byte
* buf
, size_t * len
),
1687 size_t dummy_len
= 0;
1694 log_debug ("iobuf-%d.%d: pop `%s'\n", a
->no
, a
->subno
,
1695 a
->desc
?a
->desc
:"?");
1697 { /* this is simple */
1701 xfree (a
->real_fname
);
1702 memcpy (a
, b
, sizeof *a
);
1706 for (b
= a
; b
; b
= b
->chain
)
1707 if (b
->filter
== f
&& (!ov
|| b
->filter_ov
== ov
))
1710 log_bug ("pop_filter(): filter function not found\n");
1712 /* flush this stream if it is an output stream */
1713 if (a
->use
== 2 && (rc
= iobuf_flush (b
)))
1715 log_error ("iobuf_flush failed in pop_filter: %s\n", gpg_strerror (rc
));
1718 /* and tell the filter to free it self */
1719 if (b
->filter
&& (rc
= b
->filter (b
->filter_ov
, IOBUFCTRL_FREE
, b
->chain
,
1722 log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc
));
1725 if (b
->filter_ov
&& b
->filter_ov_owner
)
1727 xfree (b
->filter_ov
);
1728 b
->filter_ov
= NULL
;
1732 /* and see how to remove it */
1733 if (a
== b
&& !b
->chain
)
1734 log_bug ("can't remove the last filter from the chain\n");
1736 { /* remove the first iobuf from the chain */
1737 /* everything from b is copied to a. This is save because
1738 * a flush has been done on the to be removed entry
1742 xfree (a
->real_fname
);
1743 memcpy (a
, b
, sizeof *a
);
1746 log_debug ("iobuf-%d.%d: popped filter\n", a
->no
, a
->subno
);
1749 { /* remove the last iobuf from the chain */
1750 log_bug ("Ohh jeee, trying to remove a head filter\n");
1753 { /* remove an intermediate iobuf from the chain */
1754 log_bug ("Ohh jeee, trying to remove an intermediate filter\n");
1762 * read underflow: read more bytes into the buffer and return
1763 * the first byte or -1 on EOF.
1766 underflow (iobuf_t a
)
1771 assert (a
->d
.start
== a
->d
.len
);
1773 return -1; /* EOF because a temp buffer can't do an underflow */
1779 iobuf_t b
= a
->chain
;
1781 log_debug ("iobuf-%d.%d: pop `%s' in underflow\n",
1782 a
->no
, a
->subno
, a
->desc
?a
->desc
:"?");
1784 xfree (a
->real_fname
);
1785 memcpy (a
, b
, sizeof *a
);
1790 a
->filter_eof
= 0; /* for the top level filter */
1792 log_debug ("iobuf-%d.%d: underflow: eof (due to filter eof)\n",
1794 return -1; /* return one(!) EOF */
1799 log_debug ("iobuf-%d.%d: error\n", a
->no
, a
->subno
);
1805 FILE *fp
= a
->directfp
;
1807 len
= fread (a
->d
.buf
, 1, a
->d
.size
, fp
);
1808 if (len
< a
->d
.size
)
1811 a
->error
= gpg_error_from_syserror ();
1815 return len
? a
->d
.buf
[a
->d
.start
++] : -1;
1823 log_debug ("iobuf-%d.%d: underflow: req=%lu\n",
1824 a
->no
, a
->subno
, (ulong
) len
);
1825 rc
= a
->filter (a
->filter_ov
, IOBUFCTRL_UNDERFLOW
, a
->chain
,
1829 log_debug ("iobuf-%d.%d: underflow: got=%lu rc=%d\n",
1830 a
->no
, a
->subno
, (ulong
) len
, rc
);
1831 /* if( a->no == 1 ) */
1832 /* log_hexdump (" data:", a->d.buf, len); */
1834 if (a
->use
== 1 && rc
== -1)
1835 { /* EOF: we can remove the filter */
1836 size_t dummy_len
= 0;
1838 /* and tell the filter to free itself */
1839 if ((rc
= a
->filter (a
->filter_ov
, IOBUFCTRL_FREE
, a
->chain
,
1841 log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc
));
1842 if (a
->filter_ov
&& a
->filter_ov_owner
)
1844 xfree (a
->filter_ov
);
1845 a
->filter_ov
= NULL
;
1849 a
->filter_ov
= NULL
;
1851 if (!len
&& a
->chain
)
1853 iobuf_t b
= a
->chain
;
1855 log_debug ("iobuf-%d.%d: pop in underflow (!len)\n",
1858 xfree (a
->real_fname
);
1859 memcpy (a
, b
, sizeof *a
);
1870 log_debug ("iobuf-%d.%d: underflow: eof\n", a
->no
, a
->subno
);
1875 return a
->d
.buf
[a
->d
.start
++];
1880 log_debug ("iobuf-%d.%d: underflow: eof (no filter)\n",
1882 return -1; /* no filter; return EOF */
1888 iobuf_flush (iobuf_t a
)
1897 { /* increase the temp buffer */
1898 unsigned char *newbuf
;
1899 size_t newsize
= a
->d
.size
+ IOBUF_BUFFER_SIZE
;
1902 log_debug ("increasing temp iobuf from %lu to %lu\n",
1903 (ulong
) a
->d
.size
, (ulong
) newsize
);
1904 newbuf
= xmalloc (newsize
);
1905 memcpy (newbuf
, a
->d
.buf
, a
->d
.len
);
1908 a
->d
.size
= newsize
;
1911 else if (a
->use
!= 2)
1912 log_bug ("flush on non-output iobuf\n");
1913 else if (!a
->filter
)
1914 log_bug ("iobuf_flush: no filter\n");
1916 rc
= a
->filter (a
->filter_ov
, IOBUFCTRL_FLUSH
, a
->chain
, a
->d
.buf
, &len
);
1917 if (!rc
&& len
!= a
->d
.len
)
1919 log_info ("iobuf_flush did not write all!\n");
1920 rc
= GPG_ERR_INTERNAL
;
1931 * Read a byte from the iobuf; returns -1 on EOF
1934 iobuf_readbyte (iobuf_t a
)
1938 if (a
->nlimit
&& a
->nbytes
>= a
->nlimit
)
1939 return -1; /* forced EOF */
1941 if (a
->d
.start
< a
->d
.len
)
1943 c
= a
->d
.buf
[a
->d
.start
++];
1945 else if ((c
= underflow (a
)) == -1)
1946 return -1; /* EOF */
1954 iobuf_read (iobuf_t a
, void *buffer
, unsigned int buflen
)
1956 unsigned char *buf
= (unsigned char *)buffer
;
1961 /* Handle special cases. */
1962 for (n
= 0; n
< buflen
; n
++)
1964 if ((c
= iobuf_readbyte (a
)) == -1)
1967 return -1; /* eof */
1981 if (n
< buflen
&& a
->d
.start
< a
->d
.len
)
1983 unsigned size
= a
->d
.len
- a
->d
.start
;
1984 if (size
> buflen
- n
)
1987 memcpy (buf
, a
->d
.buf
+ a
->d
.start
, size
);
1995 if ((c
= underflow (a
)) == -1)
1998 return n
? n
: -1 /*EOF*/;
2013 * Have a look at the iobuf.
2014 * NOTE: This only works in special cases.
2017 iobuf_peek (iobuf_t a
, byte
* buf
, unsigned buflen
)
2024 if (!(a
->d
.start
< a
->d
.len
))
2026 if (underflow (a
) == -1)
2028 /* And unget this character. */
2029 assert (a
->d
.start
== 1);
2033 for (n
= 0; n
< buflen
&& (a
->d
.start
+ n
) < a
->d
.len
; n
++, buf
++)
2042 iobuf_writebyte (iobuf_t a
, unsigned int c
)
2049 if (a
->d
.len
== a
->d
.size
)
2050 if ((rc
=iobuf_flush (a
)))
2053 assert (a
->d
.len
< a
->d
.size
);
2054 a
->d
.buf
[a
->d
.len
++] = c
;
2060 iobuf_write (iobuf_t a
, const void *buffer
, unsigned int buflen
)
2062 const unsigned char *buf
= (const unsigned char *)buffer
;
2070 if (buflen
&& a
->d
.len
< a
->d
.size
)
2072 unsigned size
= a
->d
.size
- a
->d
.len
;
2075 memcpy (a
->d
.buf
+ a
->d
.len
, buf
, size
);
2082 rc
= iobuf_flush (a
);
2093 iobuf_writestr (iobuf_t a
, const char *buf
)
2098 if ((rc
=iobuf_writebyte (a
, *buf
)))
2106 * copy the contents of TEMP to A.
2109 iobuf_write_temp (iobuf_t a
, iobuf_t temp
)
2112 pop_filter (temp
, temp
->filter
, NULL
);
2113 return iobuf_write (a
, temp
->d
.buf
, temp
->d
.len
);
2117 * copy the contents of the temp io stream to BUFFER.
2120 iobuf_temp_to_buffer (iobuf_t a
, byte
* buffer
, size_t buflen
)
2122 size_t n
= a
->d
.len
;
2126 memcpy (buffer
, a
->d
.buf
, n
);
2132 * Call this function to terminate processing of the temp stream
2133 * without closing it. This removes all filters from the stream
2134 * makes sure that iobuf_get_temp_{buffer,length}() returns correct
2138 iobuf_flush_temp (iobuf_t temp
)
2141 pop_filter (temp
, temp
->filter
, NULL
);
2146 * Set a limit on how many bytes may be read from the input stream A.
2147 * Setting the limit to 0 disables this feature.
2150 iobuf_set_limit (iobuf_t a
, off_t nlimit
)
2157 a
->ntotal
+= a
->nbytes
;
2163 /* Return the length of an open file A. IF OVERFLOW is not NULL it
2164 will be set to true if the file is larger than what off_t can cope
2165 with. The function return 0 on error or on overflow condition. */
2167 iobuf_get_filelength (iobuf_t a
, int *overflow
)
2176 FILE *fp
= a
->directfp
;
2178 if ( !fstat(fileno(fp
), &st
) )
2180 log_error("fstat() failed: %s\n", strerror(errno
) );
2184 /* Hmmm: file_filter may have already been removed */
2185 for ( ; a
; a
= a
->chain
)
2186 if ( !a
->chain
&& a
->filter
== file_filter
)
2188 file_filter_ctx_t
*b
= a
->filter_ov
;
2189 fp_or_fd_t fp
= b
->fp
;
2191 #if defined(HAVE_W32_SYSTEM) && !defined(FILE_FILTER_USES_STDIO)
2193 static int (* __stdcall get_file_size_ex
) (void *handle
,
2194 LARGE_INTEGER
*r_size
);
2195 static int get_file_size_ex_initialized
;
2197 if (!get_file_size_ex_initialized
)
2201 handle
= dlopen ("kernel32.dll", RTLD_LAZY
);
2204 get_file_size_ex
= dlsym (handle
, "GetFileSizeEx");
2205 if (!get_file_size_ex
)
2208 get_file_size_ex_initialized
= 1;
2211 if (get_file_size_ex
)
2213 /* This is a newer system with GetFileSizeEx; we use this
2214 then because it seem that GetFileSize won't return a
2215 proper error in case a file is larger than 4GB. */
2216 LARGE_INTEGER exsize
;
2218 if (get_file_size_ex (fp
, &exsize
))
2220 if (!exsize
.u
.HighPart
)
2221 return exsize
.u
.LowPart
;
2229 if ((size
=GetFileSize (fp
, NULL
)) != 0xffffffff)
2232 log_error ("GetFileSize for handle %p failed: %s\n",
2233 fp
, w32_strerror (0));
2235 if ( !fstat(my_fileno(fp
), &st
) )
2237 log_error("fstat() failed: %s\n", strerror(errno
) );
2239 break/*the for loop*/;
2246 /* Return the file descriptor of the underlying file or -1 if it is
2249 iobuf_get_fd (iobuf_t a
)
2252 return fileno ( (FILE*)a
->directfp
);
2254 for ( ; a
; a
= a
->chain
)
2255 if (!a
->chain
&& a
->filter
== file_filter
)
2257 file_filter_ctx_t
*b
= a
->filter_ov
;
2258 fp_or_fd_t fp
= b
->fp
;
2260 return my_fileno (fp
);
2269 * Tell the file position, where the next read will take place
2272 iobuf_tell (iobuf_t a
)
2274 return a
->ntotal
+ a
->nbytes
;
2278 #if !defined(HAVE_FSEEKO) && !defined(fseeko)
2280 #ifdef HAVE_LIMITS_H
2281 # include <limits.h>
2284 # define LONG_MAX ((long) ((unsigned long) -1 >> 1))
2287 # define LONG_MIN (-1 - LONG_MAX)
2291 * A substitute for fseeko, for hosts that don't have it.
2294 fseeko (FILE * stream
, off_t newpos
, int whence
)
2296 while (newpos
!= (long) newpos
)
2298 long pos
= newpos
< 0 ? LONG_MIN
: LONG_MAX
;
2299 if (fseek (stream
, pos
, whence
) != 0)
2304 return fseek (stream
, (long) newpos
, whence
);
2309 * This is a very limited implementation. It simply discards all internal
2310 * buffering and removes all filters but the first one.
2313 iobuf_seek (iobuf_t a
, off_t newpos
)
2315 file_filter_ctx_t
*b
= NULL
;
2319 FILE *fp
= a
->directfp
;
2320 if (fseeko (fp
, newpos
, SEEK_SET
))
2322 log_error ("can't seek: %s\n", strerror (errno
));
2329 for (; a
; a
= a
->chain
)
2331 if (!a
->chain
&& a
->filter
== file_filter
)
2339 #ifdef FILE_FILTER_USES_STDIO
2340 if (fseeko (b
->fp
, newpos
, SEEK_SET
))
2342 log_error ("can't fseek: %s\n", strerror (errno
));
2346 #ifdef HAVE_W32_SYSTEM
2347 if (SetFilePointer (b
->fp
, newpos
, NULL
, FILE_BEGIN
) == 0xffffffff)
2349 log_error ("SetFilePointer failed on handle %p: ec=%d\n",
2350 b
->fp
, (int) GetLastError ());
2354 if (lseek (b
->fp
, newpos
, SEEK_SET
) == (off_t
) - 1)
2356 log_error ("can't lseek: %s\n", strerror (errno
));
2362 a
->d
.len
= 0; /* discard buffer */
2369 /* remove filters, but the last */
2371 log_debug ("pop_filter called in iobuf_seek - please report\n");
2373 pop_filter (a
, a
->filter
, NULL
);
2384 * Retrieve the real filename. This is the filename actually used on
2385 * disk and not a made up one. Returns NULL if no real filename is
2389 iobuf_get_real_fname (iobuf_t a
)
2392 return a
->real_fname
;
2394 /* the old solution */
2395 for (; a
; a
= a
->chain
)
2396 if (!a
->chain
&& a
->filter
== file_filter
)
2398 file_filter_ctx_t
*b
= a
->filter_ov
;
2399 return b
->print_only_name
? NULL
: b
->fname
;
2407 * Retrieve the filename. This name should only be used in diagnostics.
2410 iobuf_get_fname (iobuf_t a
)
2412 for (; a
; a
= a
->chain
)
2413 if (!a
->chain
&& a
->filter
== file_filter
)
2415 file_filter_ctx_t
*b
= a
->filter_ov
;
2421 /* Same as iobuf_get_fname but never returns NULL. */
2423 iobuf_get_fname_nonnull (iobuf_t a
)
2427 fname
= iobuf_get_fname (a
);
2428 return fname
? fname
: "[?]";
2433 * enable partial block mode as described in the OpenPGP draft.
2434 * LEN is the first length byte on read, but ignored on writes.
2437 iobuf_set_partial_block_mode (iobuf_t a
, size_t len
)
2439 block_filter_ctx_t
*ctx
= xcalloc (1, sizeof *ctx
);
2441 assert (a
->use
== 1 || a
->use
== 2);
2446 log_debug ("pop_filter called in set_partial_block_mode"
2447 " - please report\n");
2448 pop_filter (a
, block_filter
, NULL
);
2455 iobuf_push_filter (a
, block_filter
, ctx
);
2462 * Same as fgets() but if the buffer is too short a larger one will
2463 * be allocated up to some limit *max_length.
2464 * A line is considered a byte stream ending in a LF.
2465 * Returns the length of the line. EOF is indicated by a line of
2466 * length zero. The last LF may be missing due to an EOF.
2467 * is max_length is zero on return, the line has been truncated.
2469 * Note: The buffer is allocated with enough space to append a CR,LF,EOL
2472 iobuf_read_line (iobuf_t a
, byte
** addr_of_buffer
,
2473 unsigned *length_of_buffer
, unsigned *max_length
)
2476 char *buffer
= (char *)*addr_of_buffer
;
2477 unsigned length
= *length_of_buffer
;
2478 unsigned nbytes
= 0;
2479 unsigned maxlen
= *max_length
;
2483 { /* must allocate a new buffer */
2485 buffer
= xmalloc (length
);
2486 *addr_of_buffer
= (unsigned char *)buffer
;
2487 *length_of_buffer
= length
;
2490 length
-= 3; /* reserve 3 bytes (cr,lf,eol) */
2492 while ((c
= iobuf_get (a
)) != -1)
2494 if (nbytes
== length
)
2495 { /* increase the buffer */
2496 if (length
> maxlen
)
2497 { /* this is out limit */
2498 /* skip the rest of the line */
2499 while (c
!= '\n' && (c
= iobuf_get (a
)) != -1)
2501 *p
++ = '\n'; /* always append a LF (we have reserved space) */
2503 *max_length
= 0; /* indicate truncation */
2506 length
+= 3; /* correct for the reserved byte */
2507 length
+= length
< 1024 ? 256 : 1024;
2508 buffer
= xrealloc (buffer
, length
);
2509 *addr_of_buffer
= (unsigned char *)buffer
;
2510 *length_of_buffer
= length
;
2511 length
-= 3; /* and reserve again */
2512 p
= buffer
+ nbytes
;
2519 *p
= 0; /* make sure the line is a string */
2525 translate_file_handle (int fd
, int for_write
)
2527 #ifdef HAVE_W32_SYSTEM
2528 # ifdef FILE_FILTER_USES_STDIO
2529 fd
= translate_sys2libc_fd (fd
, for_write
);
2537 x
= (int) GetStdHandle (STD_INPUT_HANDLE
);
2539 x
= (int) GetStdHandle (STD_OUTPUT_HANDLE
);
2541 x
= (int) GetStdHandle (STD_ERROR_HANDLE
);
2546 log_debug ("GetStdHandle(%d) failed: ec=%d\n",
2547 fd
, (int) GetLastError ());
2560 iobuf_skip_rest (iobuf_t a
, unsigned long n
, int partial
)
2566 if (a
->nofast
|| a
->d
.start
>= a
->d
.len
)
2568 if (iobuf_readbyte (a
) == -1)
2575 unsigned long count
= a
->d
.len
- a
->d
.start
;
2577 a
->d
.start
= a
->d
.len
;
2583 unsigned long remaining
= n
;
2584 while (remaining
> 0)
2586 if (a
->nofast
|| a
->d
.start
>= a
->d
.len
)
2588 if (iobuf_readbyte (a
) == -1)
2596 unsigned long count
= a
->d
.len
- a
->d
.start
;
2597 if (count
> remaining
)
2602 a
->d
.start
+= count
;