Move password repetition from gpg to gpg-agent.
[gnupg.git] / common / iobuf.c
blob6c493b51219c27fcb07bd0ef1ef3c0196d7cd2c2
1 /* iobuf.c - File Handling for OpenPGP.
2 * Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2006,
3 * 2007, 2008 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/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <ctype.h>
27 #include <assert.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #include <unistd.h>
32 #ifdef HAVE_W32_SYSTEM
33 # include <windows.h>
34 #endif
35 #ifdef __riscos__
36 # include <kernel.h>
37 # include <swis.h>
38 #endif /* __riscos__ */
40 #include "util.h"
41 #include "sysutils.h"
42 #include "iobuf.h"
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. */
52 #undef FILE_FILTER_USES_STDIO
54 /*-- End configurable part. --*/
57 /* Under W32 the default is to use the setmode call. Define a macro
58 which allows us to enable this call. */
59 #ifdef HAVE_W32_SYSTEM
60 # define USE_SETMODE 1
61 #endif /*HAVE_W32_SYSTEM*/
64 /* Definition of constants and macros used by our file filter
65 implementation. What we define here are 3 macros to make the
66 appropriate calls:
68 my_fileno
69 Is expanded to fileno(a) if using a stdion backend and to a if we
70 are using the low-level backend.
72 my_fopen
73 Is defined to fopen for the stdio backend and to direct_open if
74 we are using the low-evel backend.
76 my_fopen_ro
77 Is defined to fopen for the stdio backend and to fd_cache_open if
78 we are using the low-evel backend.
80 fp_or_fd_t
81 Is the type we use for the backend stream or file descriptor.
83 INVALID_FP, FILEP_OR_FD_FOR_STDIN, FILEP_OR_FD_FOR_STDOUT
84 Are macros defined depending on the used backend.
87 #ifdef FILE_FILTER_USES_STDIO
88 # define my_fileno(a) fileno ((a))
89 # define my_fopen_ro(a,b) fopen ((a),(b))
90 # define my_fopen(a,b) fopen ((a),(b))
91 typedef FILE *fp_or_fd_t;
92 # define INVALID_FP NULL
93 # define FILEP_OR_FD_FOR_STDIN (stdin)
94 # define FILEP_OR_FD_FOR_STDOUT (stdout)
95 #else /*!FILE_FILTER_USES_STDIO*/
96 # define my_fopen_ro(a,b) fd_cache_open ((a),(b))
97 # define my_fopen(a,b) direct_open ((a),(b))
98 # ifdef HAVE_W32_SYSTEM
99 /* (We assume that a HANDLE first into an int.) */
100 # define my_fileno(a) ((int)(a))
101 typedef HANDLE fp_or_fd_t;
102 # define INVALID_FP ((HANDLE)-1)
103 # define FILEP_OR_FD_FOR_STDIN (GetStdHandle (STD_INPUT_HANDLE))
104 # define FILEP_OR_FD_FOR_STDOUT (GetStdHandle (STD_OUTPUT_HANDLE))
105 # undef USE_SETMODE
106 # else /*!HAVE_W32_SYSTEM*/
107 # define my_fileno(a) (a)
108 typedef int fp_or_fd_t;
109 # define INVALID_FP (-1)
110 # define FILEP_OR_FD_FOR_STDIN (0)
111 # define FILEP_OR_FD_FOR_STDOUT (1)
112 # endif /*!HAVE_W32_SYSTEM*/
113 #endif /*!FILE_FILTER_USES_STDIO*/
115 /* The context used by the file filter. */
116 typedef struct
118 fp_or_fd_t fp; /* Open file pointer or handle. */
119 int keep_open;
120 int no_cache;
121 int eof_seen;
122 int print_only_name; /* Flags indicating that fname is not a real file. */
123 char fname[1]; /* Name of the file. */
125 file_filter_ctx_t;
128 /* If we are not using stdio as the backend we make use of a "close
129 cache". */
130 #ifndef FILE_FILTER_USES_STDIO
131 struct close_cache_s
133 struct close_cache_s *next;
134 fp_or_fd_t fp;
135 char fname[1];
137 typedef struct close_cache_s *close_cache_t;
138 static close_cache_t close_cache;
139 #endif /*!FILE_FILTER_USES_STDIO*/
143 #ifdef HAVE_W32_SYSTEM
144 typedef struct
146 int sock;
147 int keep_open;
148 int no_cache;
149 int eof_seen;
150 int print_only_name; /* Flag indicating that fname is not a real file. */
151 char fname[1]; /* Name of the file */
153 sock_filter_ctx_t;
154 #endif /*HAVE_W32_SYSTEM*/
156 /* The first partial length header block must be of size 512
157 * to make it easier (and efficienter) we use a min. block size of 512
158 * for all chunks (but the last one) */
159 #define OP_MIN_PARTIAL_CHUNK 512
160 #define OP_MIN_PARTIAL_CHUNK_2POW 9
162 /* The context we use for the block filter (used to handle OpenPGP
163 length information header). */
164 typedef struct
166 int use;
167 size_t size;
168 size_t count;
169 int partial; /* 1 = partial header, 2 in last partial packet. */
170 char *buffer; /* Used for partial header. */
171 size_t buflen; /* Used size of buffer. */
172 int first_c; /* First character of a partial header (which is > 0). */
173 int eof;
175 block_filter_ctx_t;
178 /* Global flag to tell whether special file names are enabled. See
179 gpg.c for an explanation of these file names. FIXME: it does not
180 belong into the iobuf subsystem. */
181 static int special_names_enabled;
183 /* Local prototypes. */
184 static int underflow (iobuf_t a);
185 static int translate_file_handle (int fd, int for_write);
189 #ifndef FILE_FILTER_USES_STDIO
191 * Invalidate (i.e. close) a cached iobuf
193 static void
194 fd_cache_invalidate (const char *fname)
196 close_cache_t cc;
198 assert (fname);
199 if (DBG_IOBUF)
200 log_debug ("fd_cache_invalidate (%s)\n", fname);
202 for (cc = close_cache; cc; cc = cc->next)
204 if (cc->fp != INVALID_FP && !strcmp (cc->fname, fname))
206 if (DBG_IOBUF)
207 log_debug (" did (%s)\n", cc->fname);
208 #ifdef HAVE_W32_SYSTEM
209 CloseHandle (cc->fp);
210 #else
211 close (cc->fp);
212 #endif
213 cc->fp = INVALID_FP;
219 static fp_or_fd_t
220 direct_open (const char *fname, const char *mode)
222 #ifdef HAVE_W32_SYSTEM
223 unsigned long da, cd, sm;
224 HANDLE hfile;
226 /* Note, that we do not handle all mode combinations */
228 /* According to the ReactOS source it seems that open() of the
229 * standard MSW32 crt does open the file in share mode which is
230 * something new for MS applications ;-)
232 if (strchr (mode, '+'))
234 fd_cache_invalidate (fname);
235 da = GENERIC_READ | GENERIC_WRITE;
236 cd = OPEN_EXISTING;
237 sm = FILE_SHARE_READ | FILE_SHARE_WRITE;
239 else if (strchr (mode, 'w'))
241 fd_cache_invalidate (fname);
242 da = GENERIC_WRITE;
243 cd = CREATE_ALWAYS;
244 sm = FILE_SHARE_WRITE;
246 else
248 da = GENERIC_READ;
249 cd = OPEN_EXISTING;
250 sm = FILE_SHARE_READ;
253 hfile = CreateFile (fname, da, sm, NULL, cd, FILE_ATTRIBUTE_NORMAL, NULL);
254 return hfile;
255 #else /*!HAVE_W32_SYSTEM*/
256 int oflag;
257 int cflag = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
259 /* Note, that we do not handle all mode combinations */
260 if (strchr (mode, '+'))
262 fd_cache_invalidate (fname);
263 oflag = O_RDWR;
265 else if (strchr (mode, 'w'))
267 fd_cache_invalidate (fname);
268 oflag = O_WRONLY | O_CREAT | O_TRUNC;
270 else
272 oflag = O_RDONLY;
274 #ifdef O_BINARY
275 if (strchr (mode, 'b'))
276 oflag |= O_BINARY;
277 #endif
278 /* No we need to distinguish between POSIX and RISC OS. */
279 #ifndef __riscos__
280 return open (fname, oflag, cflag);
281 #else
283 struct stat buf;
284 int rc = stat (fname, &buf);
286 /* Don't allow iobufs on directories */
287 if (!rc && S_ISDIR (buf.st_mode) && !S_ISREG (buf.st_mode))
288 return __set_errno (EISDIR);
289 else
290 return open (fname, oflag, cflag);
292 #endif
293 #endif /*!HAVE_W32_SYSTEM*/
298 * Instead of closing an FD we keep it open and cache it for later reuse
299 * Note that this caching strategy only works if the process does not chdir.
301 static void
302 fd_cache_close (const char *fname, fp_or_fd_t fp)
304 close_cache_t cc;
306 assert (fp);
307 if (!fname || !*fname)
309 #ifdef HAVE_W32_SYSTEM
310 CloseHandle (fp);
311 #else
312 close (fp);
313 #endif
314 if (DBG_IOBUF)
315 log_debug ("fd_cache_close (%d) real\n", (int)fp);
316 return;
318 /* try to reuse a slot */
319 for (cc = close_cache; cc; cc = cc->next)
321 if (cc->fp == INVALID_FP && !strcmp (cc->fname, fname))
323 cc->fp = fp;
324 if (DBG_IOBUF)
325 log_debug ("fd_cache_close (%s) used existing slot\n", fname);
326 return;
329 /* add a new one */
330 if (DBG_IOBUF)
331 log_debug ("fd_cache_close (%s) new slot created\n", fname);
332 cc = xcalloc (1, sizeof *cc + strlen (fname));
333 strcpy (cc->fname, fname);
334 cc->fp = fp;
335 cc->next = close_cache;
336 close_cache = cc;
340 * Do an direct_open on FNAME but first try to reuse one from the fd_cache
342 static fp_or_fd_t
343 fd_cache_open (const char *fname, const char *mode)
345 close_cache_t cc;
347 assert (fname);
348 for (cc = close_cache; cc; cc = cc->next)
350 if (cc->fp != INVALID_FP && !strcmp (cc->fname, fname))
352 fp_or_fd_t fp = cc->fp;
353 cc->fp = INVALID_FP;
354 if (DBG_IOBUF)
355 log_debug ("fd_cache_open (%s) using cached fp\n", fname);
356 #ifdef HAVE_W32_SYSTEM
357 if (SetFilePointer (fp, 0, NULL, FILE_BEGIN) == 0xffffffff)
359 log_error ("rewind file failed on handle %p: ec=%d\n",
360 fp, (int) GetLastError ());
361 fp = INVALID_FP;
363 #else
364 if (lseek (fp, 0, SEEK_SET) == (off_t) - 1)
366 log_error ("can't rewind fd %d: %s\n", fp, strerror (errno));
367 fp = INVALID_FP;
369 #endif
370 return fp;
373 if (DBG_IOBUF)
374 log_debug ("fd_cache_open (%s) not cached\n", fname);
375 return direct_open (fname, mode);
378 #endif /*FILE_FILTER_USES_STDIO */
381 /****************
382 * Read data from a file into buf which has an allocated length of *LEN.
383 * return the number of read bytes in *LEN. OPAQUE is the FILE * of
384 * the stream. A is not used.
385 * control may be:
386 * IOBUFCTRL_INIT: called just before the function is linked into the
387 * list of function. This can be used to prepare internal
388 * data structures of the function.
389 * IOBUFCTRL_FREE: called just before the function is removed from the
390 * list of functions and can be used to release internal
391 * data structures or close a file etc.
392 * IOBUFCTRL_UNDERFLOW: called by iobuf_underflow to fill the buffer
393 * with new stuff. *RET_LEN is the available size of the
394 * buffer, and should be set to the number of bytes
395 * which were put into the buffer. The function
396 * returns 0 to indicate success, -1 on EOF and
397 * GPG_ERR_xxxxx for other errors.
399 * IOBUFCTRL_FLUSH: called by iobuf_flush() to write out the collected stuff.
400 * *RET_LAN is the number of bytes in BUF.
402 * IOBUFCTRL_CANCEL: send to all filters on behalf of iobuf_cancel. The
403 * filter may take appropriate action on this message.
405 static int
406 file_filter (void *opaque, int control, iobuf_t chain, byte * buf,
407 size_t * ret_len)
409 file_filter_ctx_t *a = opaque;
410 fp_or_fd_t f = a->fp;
411 size_t size = *ret_len;
412 size_t nbytes = 0;
413 int rc = 0;
415 (void)chain; /* Not used. */
417 #ifdef FILE_FILTER_USES_STDIO
418 if (control == IOBUFCTRL_UNDERFLOW)
420 assert (size); /* We need a buffer. */
421 if (feof (f))
423 /* On terminals you could easily read as many EOFs as you
424 call fread() or fgetc() repeatly. Every call will block
425 until you press CTRL-D. So we catch this case before we
426 call fread() again. */
427 rc = -1;
428 *ret_len = 0;
430 else
432 clearerr (f);
433 nbytes = fread (buf, 1, size, f);
434 if (feof (f) && !nbytes)
436 rc = -1; /* Okay: we can return EOF now. */
438 else if (ferror (f) && errno != EPIPE)
440 rc = gpg_error_from_syserror ();
441 log_error ("%s: read error: %s\n", a->fname, strerror (errno));
443 *ret_len = nbytes;
446 else if (control == IOBUFCTRL_FLUSH)
448 if (size)
450 clearerr (f);
451 nbytes = fwrite (buf, 1, size, f);
452 if (ferror (f))
454 rc = gpg_error_from_syserror ();
455 log_error ("%s: write error: %s\n", a->fname, strerror (errno));
458 *ret_len = nbytes;
460 else if (control == IOBUFCTRL_INIT)
462 a->keep_open = a->no_cache = 0;
464 else if (control == IOBUFCTRL_DESC)
466 *(char **) buf = "file_filter";
468 else if (control == IOBUFCTRL_FREE)
470 if (f != stdin && f != stdout)
472 if (DBG_IOBUF)
473 log_debug ("%s: close fd %d\n", a->fname, fileno (f));
474 if (!a->keep_open)
475 fclose (f);
477 f = NULL;
478 xfree (a); /* We can free our context now. */
480 #else /* !stdio implementation */
482 if (control == IOBUFCTRL_UNDERFLOW)
484 assert (size); /* We need a buffer. */
485 if (a->eof_seen)
487 rc = -1;
488 *ret_len = 0;
490 else
492 #ifdef HAVE_W32_SYSTEM
493 unsigned long nread;
495 nbytes = 0;
496 if (!ReadFile (f, buf, size, &nread, NULL))
498 int ec = (int) GetLastError ();
499 if (ec != ERROR_BROKEN_PIPE)
501 rc = gpg_error_from_errno (ec);
502 log_error ("%s: read error: ec=%d\n", a->fname, ec);
505 else if (!nread)
507 a->eof_seen = 1;
508 rc = -1;
510 else
512 nbytes = nread;
515 #else
517 int n;
519 nbytes = 0;
522 n = read (f, buf, size);
524 while (n == -1 && errno == EINTR);
525 if (n == -1)
526 { /* error */
527 if (errno != EPIPE)
529 rc = gpg_error_from_syserror ();
530 log_error ("%s: read error: %s\n",
531 a->fname, strerror (errno));
534 else if (!n)
535 { /* eof */
536 a->eof_seen = 1;
537 rc = -1;
539 else
541 nbytes = n;
543 #endif
544 *ret_len = nbytes;
547 else if (control == IOBUFCTRL_FLUSH)
549 if (size)
551 #ifdef HAVE_W32_SYSTEM
552 byte *p = buf;
553 unsigned long n;
555 nbytes = size;
558 if (size && !WriteFile (f, p, nbytes, &n, NULL))
560 int ec = (int) GetLastError ();
561 rc = gpg_error_from_errno (ec);
562 log_error ("%s: write error: ec=%d\n", a->fname, ec);
563 break;
565 p += n;
566 nbytes -= n;
568 while (nbytes);
569 nbytes = p - buf;
570 #else
571 byte *p = buf;
572 int n;
574 nbytes = size;
579 n = write (f, p, nbytes);
581 while (n == -1 && errno == EINTR);
582 if (n > 0)
584 p += n;
585 nbytes -= n;
588 while (n != -1 && nbytes);
589 if (n == -1)
591 rc = gpg_error_from_syserror ();
592 log_error ("%s: write error: %s\n", a->fname, strerror (errno));
594 nbytes = p - buf;
595 #endif
597 *ret_len = nbytes;
599 else if (control == IOBUFCTRL_INIT)
601 a->eof_seen = 0;
602 a->keep_open = 0;
603 a->no_cache = 0;
605 else if (control == IOBUFCTRL_DESC)
607 *(char **) buf = "file_filter(fd)";
609 else if (control == IOBUFCTRL_FREE)
611 #ifdef HAVE_W32_SYSTEM
612 if (f != FILEP_OR_FD_FOR_STDIN && f != FILEP_OR_FD_FOR_STDOUT)
614 if (DBG_IOBUF)
615 log_debug ("%s: close handle %p\n", a->fname, f);
616 if (!a->keep_open)
617 fd_cache_close (a->no_cache ? NULL : a->fname, f);
619 #else
620 if ((int) f != 0 && (int) f != 1)
622 if (DBG_IOBUF)
623 log_debug ("%s: close fd %d\n", a->fname, f);
624 if (!a->keep_open)
625 fd_cache_close (a->no_cache ? NULL : a->fname, f);
627 f = INVALID_FP;
628 #endif
629 xfree (a); /* We can free our context now. */
631 #endif /* !stdio implementation. */
632 return rc;
636 #ifdef HAVE_W32_SYSTEM
637 /* Because network sockets are special objects under Lose32 we have to
638 use a dedicated filter for them. */
639 static int
640 sock_filter (void *opaque, int control, iobuf_t chain, byte * buf,
641 size_t * ret_len)
643 sock_filter_ctx_t *a = opaque;
644 size_t size = *ret_len;
645 size_t nbytes = 0;
646 int rc = 0;
648 (void)chain;
650 if (control == IOBUFCTRL_UNDERFLOW)
652 assert (size); /* need a buffer */
653 if (a->eof_seen)
655 rc = -1;
656 *ret_len = 0;
658 else
660 int nread;
662 nread = recv (a->sock, buf, size, 0);
663 if (nread == SOCKET_ERROR)
665 int ec = (int) WSAGetLastError ();
666 rc = gpg_error_from_errno (ec);
667 log_error ("socket read error: ec=%d\n", ec);
669 else if (!nread)
671 a->eof_seen = 1;
672 rc = -1;
674 else
676 nbytes = nread;
678 *ret_len = nbytes;
681 else if (control == IOBUFCTRL_FLUSH)
683 if (size)
685 byte *p = buf;
686 int n;
688 nbytes = size;
691 n = send (a->sock, p, nbytes, 0);
692 if (n == SOCKET_ERROR)
694 int ec = (int) WSAGetLastError ();
695 rc = gpg_error_from_errno (ec);
696 log_error ("socket write error: ec=%d\n", ec);
697 break;
699 p += n;
700 nbytes -= n;
702 while (nbytes);
703 nbytes = p - buf;
705 *ret_len = nbytes;
707 else if (control == IOBUFCTRL_INIT)
709 a->eof_seen = 0;
710 a->keep_open = 0;
711 a->no_cache = 0;
713 else if (control == IOBUFCTRL_DESC)
715 *(char **) buf = "sock_filter";
717 else if (control == IOBUFCTRL_FREE)
719 if (!a->keep_open)
720 closesocket (a->sock);
721 xfree (a); /* we can free our context now */
723 return rc;
725 #endif /*HAVE_W32_SYSTEM*/
727 /****************
728 * This is used to implement the block write mode.
729 * Block reading is done on a byte by byte basis in readbyte(),
730 * without a filter
732 static int
733 block_filter (void *opaque, int control, iobuf_t chain, byte * buffer,
734 size_t * ret_len)
736 block_filter_ctx_t *a = opaque;
737 char *buf = (char *)buffer;
738 size_t size = *ret_len;
739 int c, needed, rc = 0;
740 char *p;
742 if (control == IOBUFCTRL_UNDERFLOW)
744 size_t n = 0;
746 p = buf;
747 assert (size); /* need a buffer */
748 if (a->eof) /* don't read any further */
749 rc = -1;
750 while (!rc && size)
752 if (!a->size)
753 { /* get the length bytes */
754 if (a->partial == 2)
756 a->eof = 1;
757 if (!n)
758 rc = -1;
759 break;
761 else if (a->partial)
763 /* These OpenPGP introduced huffman like encoded length
764 * bytes are really a mess :-( */
765 if (a->first_c)
767 c = a->first_c;
768 a->first_c = 0;
770 else if ((c = iobuf_get (chain)) == -1)
772 log_error ("block_filter: 1st length byte missing\n");
773 rc = GPG_ERR_BAD_DATA;
774 break;
776 if (c < 192)
778 a->size = c;
779 a->partial = 2;
780 if (!a->size)
782 a->eof = 1;
783 if (!n)
784 rc = -1;
785 break;
788 else if (c < 224)
790 a->size = (c - 192) * 256;
791 if ((c = iobuf_get (chain)) == -1)
793 log_error
794 ("block_filter: 2nd length byte missing\n");
795 rc = GPG_ERR_BAD_DATA;
796 break;
798 a->size += c + 192;
799 a->partial = 2;
800 if (!a->size)
802 a->eof = 1;
803 if (!n)
804 rc = -1;
805 break;
808 else if (c == 255)
810 a->size = iobuf_get (chain) << 24;
811 a->size |= iobuf_get (chain) << 16;
812 a->size |= iobuf_get (chain) << 8;
813 if ((c = iobuf_get (chain)) == -1)
815 log_error ("block_filter: invalid 4 byte length\n");
816 rc = GPG_ERR_BAD_DATA;
817 break;
819 a->size |= c;
820 a->partial = 2;
821 if (!a->size)
823 a->eof = 1;
824 if (!n)
825 rc = -1;
826 break;
829 else
830 { /* Next partial body length. */
831 a->size = 1 << (c & 0x1f);
833 /* log_debug("partial: ctx=%p c=%02x size=%u\n", a, c, a->size); */
835 else
836 BUG ();
839 while (!rc && size && a->size)
841 needed = size < a->size ? size : a->size;
842 c = iobuf_read (chain, p, needed);
843 if (c < needed)
845 if (c == -1)
846 c = 0;
847 log_error
848 ("block_filter %p: read error (size=%lu,a->size=%lu)\n",
849 a, (ulong) size + c, (ulong) a->size + c);
850 rc = GPG_ERR_BAD_DATA;
852 else
854 size -= c;
855 a->size -= c;
856 p += c;
857 n += c;
861 *ret_len = n;
863 else if (control == IOBUFCTRL_FLUSH)
865 if (a->partial)
866 { /* the complicated openpgp scheme */
867 size_t blen, n, nbytes = size + a->buflen;
869 assert (a->buflen <= OP_MIN_PARTIAL_CHUNK);
870 if (nbytes < OP_MIN_PARTIAL_CHUNK)
872 /* not enough to write a partial block out; so we store it */
873 if (!a->buffer)
874 a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK);
875 memcpy (a->buffer + a->buflen, buf, size);
876 a->buflen += size;
878 else
879 { /* okay, we can write out something */
880 /* do this in a loop to use the most efficient block lengths */
881 p = buf;
884 /* find the best matching block length - this is limited
885 * by the size of the internal buffering */
886 for (blen = OP_MIN_PARTIAL_CHUNK * 2,
887 c = OP_MIN_PARTIAL_CHUNK_2POW + 1; blen <= nbytes;
888 blen *= 2, c++)
890 blen /= 2;
891 c--;
892 /* write the partial length header */
893 assert (c <= 0x1f); /*;-) */
894 c |= 0xe0;
895 iobuf_put (chain, c);
896 if ((n = a->buflen))
897 { /* write stuff from the buffer */
898 assert (n == OP_MIN_PARTIAL_CHUNK);
899 if (iobuf_write (chain, a->buffer, n))
900 rc = gpg_error_from_syserror ();
901 a->buflen = 0;
902 nbytes -= n;
904 if ((n = nbytes) > blen)
905 n = blen;
906 if (n && iobuf_write (chain, p, n))
907 rc = gpg_error_from_syserror ();
908 p += n;
909 nbytes -= n;
911 while (!rc && nbytes >= OP_MIN_PARTIAL_CHUNK);
912 /* store the rest in the buffer */
913 if (!rc && nbytes)
915 assert (!a->buflen);
916 assert (nbytes < OP_MIN_PARTIAL_CHUNK);
917 if (!a->buffer)
918 a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK);
919 memcpy (a->buffer, p, nbytes);
920 a->buflen = nbytes;
924 else
925 BUG ();
927 else if (control == IOBUFCTRL_INIT)
929 if (DBG_IOBUF)
930 log_debug ("init block_filter %p\n", a);
931 if (a->partial)
932 a->count = 0;
933 else if (a->use == 1)
934 a->count = a->size = 0;
935 else
936 a->count = a->size; /* force first length bytes */
937 a->eof = 0;
938 a->buffer = NULL;
939 a->buflen = 0;
941 else if (control == IOBUFCTRL_DESC)
943 *(char **) buf = "block_filter";
945 else if (control == IOBUFCTRL_FREE)
947 if (a->use == 2)
948 { /* write the end markers */
949 if (a->partial)
951 u32 len;
952 /* write out the remaining bytes without a partial header
953 * the length of this header may be 0 - but if it is
954 * the first block we are not allowed to use a partial header
955 * and frankly we can't do so, because this length must be
956 * a power of 2. This is _really_ complicated because we
957 * have to check the possible length of a packet prior
958 * to it's creation: a chain of filters becomes complicated
959 * and we need a lot of code to handle compressed packets etc.
960 * :-(((((((
962 /* construct header */
963 len = a->buflen;
964 /*log_debug("partial: remaining length=%u\n", len ); */
965 if (len < 192)
966 rc = iobuf_put (chain, len);
967 else if (len < 8384)
969 if (!(rc = iobuf_put (chain, ((len - 192) / 256) + 192)))
970 rc = iobuf_put (chain, ((len - 192) % 256));
972 else
973 { /* use a 4 byte header */
974 if (!(rc = iobuf_put (chain, 0xff)))
975 if (!(rc = iobuf_put (chain, (len >> 24) & 0xff)))
976 if (!(rc = iobuf_put (chain, (len >> 16) & 0xff)))
977 if (!(rc = iobuf_put (chain, (len >> 8) & 0xff)))
978 rc = iobuf_put (chain, len & 0xff);
980 if (!rc && len)
981 rc = iobuf_write (chain, a->buffer, len);
982 if (rc)
984 log_error ("block_filter: write error: %s\n",
985 strerror (errno));
986 rc = gpg_error_from_syserror ();
988 xfree (a->buffer);
989 a->buffer = NULL;
990 a->buflen = 0;
992 else
993 BUG ();
995 else if (a->size)
997 log_error ("block_filter: pending bytes!\n");
999 if (DBG_IOBUF)
1000 log_debug ("free block_filter %p\n", a);
1001 xfree (a); /* we can free our context now */
1004 return rc;
1008 static void
1009 print_chain (iobuf_t a)
1011 if (!DBG_IOBUF)
1012 return;
1013 for (; a; a = a->chain)
1015 size_t dummy_len = 0;
1016 const char *desc = "[none]";
1018 if (a->filter)
1019 a->filter (a->filter_ov, IOBUFCTRL_DESC, NULL,
1020 (byte *) & desc, &dummy_len);
1022 log_debug ("iobuf chain: %d.%d `%s' filter_eof=%d start=%d len=%d\n",
1023 a->no, a->subno, desc?desc:"?", a->filter_eof,
1024 (int) a->d.start, (int) a->d.len);
1029 iobuf_print_chain (iobuf_t a)
1031 print_chain (a);
1032 return 0;
1035 /****************
1036 * Allocate a new io buffer, with no function assigned.
1037 * Use is the desired usage: 1 for input, 2 for output, 3 for temp buffer
1038 * BUFSIZE is a suggested buffer size.
1040 iobuf_t
1041 iobuf_alloc (int use, size_t bufsize)
1043 iobuf_t a;
1044 static int number = 0;
1046 a = xcalloc (1, sizeof *a);
1047 a->use = use;
1048 a->d.buf = xmalloc (bufsize);
1049 a->d.size = bufsize;
1050 a->no = ++number;
1051 a->subno = 0;
1052 a->opaque = NULL;
1053 a->real_fname = NULL;
1054 return a;
1058 iobuf_close (iobuf_t a)
1060 iobuf_t a2;
1061 size_t dummy_len = 0;
1062 int rc = 0;
1064 if (a && a->directfp)
1066 fclose (a->directfp);
1067 xfree (a->real_fname);
1068 if (DBG_IOBUF)
1069 log_debug ("iobuf_close -> %p\n", a->directfp);
1070 return 0;
1073 for (; a && !rc; a = a2)
1075 a2 = a->chain;
1076 if (a->use == 2 && (rc = iobuf_flush (a)))
1077 log_error ("iobuf_flush failed on close: %s\n", gpg_strerror (rc));
1079 if (DBG_IOBUF)
1080 log_debug ("iobuf-%d.%d: close `%s'\n", a->no, a->subno,
1081 a->desc?a->desc:"?");
1082 if (a->filter && (rc = a->filter (a->filter_ov, IOBUFCTRL_FREE,
1083 a->chain, NULL, &dummy_len)))
1084 log_error ("IOBUFCTRL_FREE failed on close: %s\n", gpg_strerror (rc));
1085 xfree (a->real_fname);
1086 if (a->d.buf)
1088 memset (a->d.buf, 0, a->d.size); /* erase the buffer */
1089 xfree (a->d.buf);
1091 xfree (a);
1093 return rc;
1097 iobuf_cancel (iobuf_t a)
1099 const char *s;
1100 iobuf_t a2;
1101 int rc;
1102 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1103 char *remove_name = NULL;
1104 #endif
1106 if (a && a->use == 2)
1108 s = iobuf_get_real_fname (a);
1109 if (s && *s)
1111 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1112 remove_name = xstrdup (s);
1113 #else
1114 remove (s);
1115 #endif
1119 /* send a cancel message to all filters */
1120 for (a2 = a; a2; a2 = a2->chain)
1122 size_t dummy;
1123 if (a2->filter)
1124 a2->filter (a2->filter_ov, IOBUFCTRL_CANCEL, a2->chain, NULL, &dummy);
1127 rc = iobuf_close (a);
1128 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1129 if (remove_name)
1131 /* Argg, MSDOS does not allow to remove open files. So
1132 * we have to do it here */
1133 remove (remove_name);
1134 xfree (remove_name);
1136 #endif
1137 return rc;
1141 /****************
1142 * create a temporary iobuf, which can be used to collect stuff
1143 * in an iobuf and later be written by iobuf_write_temp() to another
1144 * iobuf.
1146 iobuf_t
1147 iobuf_temp ()
1149 iobuf_t a;
1151 a = iobuf_alloc (3, IOBUF_BUFFER_SIZE);
1153 return a;
1156 iobuf_t
1157 iobuf_temp_with_content (const char *buffer, size_t length)
1159 iobuf_t a;
1161 a = iobuf_alloc (3, length);
1162 memcpy (a->d.buf, buffer, length);
1163 a->d.len = length;
1165 return a;
1168 void
1169 iobuf_enable_special_filenames (int yes)
1171 special_names_enabled = yes;
1175 /* See whether the filename has the form "-&nnnn", where n is a
1176 non-zero number. Returns this number or -1 if it is not the
1177 case. */
1178 static int
1179 check_special_filename (const char *fname)
1181 if (special_names_enabled && fname && *fname == '-' && fname[1] == '&')
1183 int i;
1185 fname += 2;
1186 for (i = 0; digitp (fname+i); i++)
1188 if (!fname[i])
1189 return atoi (fname);
1191 return -1;
1195 /* This fucntion returns true if FNAME indicates a PIPE (stdout or
1196 stderr) or a special file name if those are enabled. */
1198 iobuf_is_pipe_filename (const char *fname)
1200 if (!fname || (*fname=='-' && !fname[1]) )
1201 return 1;
1202 return check_special_filename (fname) != -1;
1205 /****************
1206 * Create a head iobuf for reading from a file
1207 * returns: NULL if an error occures and sets errno
1209 iobuf_t
1210 iobuf_open (const char *fname)
1212 iobuf_t a;
1213 fp_or_fd_t fp;
1214 file_filter_ctx_t *fcx;
1215 size_t len;
1216 int print_only = 0;
1217 int fd;
1219 if (!fname || (*fname == '-' && !fname[1]))
1221 fp = FILEP_OR_FD_FOR_STDIN;
1222 #ifdef USE_SETMODE
1223 setmode (my_fileno (fp), O_BINARY);
1224 #endif
1225 fname = "[stdin]";
1226 print_only = 1;
1228 else if ((fd = check_special_filename (fname)) != -1)
1229 return iobuf_fdopen (translate_file_handle (fd, 0), "rb");
1230 else if ((fp = my_fopen_ro (fname, "rb")) == INVALID_FP)
1231 return NULL;
1232 a = iobuf_alloc (1, IOBUF_BUFFER_SIZE);
1233 fcx = xmalloc (sizeof *fcx + strlen (fname));
1234 fcx->fp = fp;
1235 fcx->print_only_name = print_only;
1236 strcpy (fcx->fname, fname);
1237 if (!print_only)
1238 a->real_fname = xstrdup (fname);
1239 a->filter = file_filter;
1240 a->filter_ov = fcx;
1241 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1242 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1243 if (DBG_IOBUF)
1244 log_debug ("iobuf-%d.%d: open `%s' fd=%d\n",
1245 a->no, a->subno, fname, (int) my_fileno (fcx->fp));
1247 return a;
1250 /****************
1251 * Create a head iobuf for reading from a file
1252 * returns: NULL if an error occures and sets errno
1254 iobuf_t
1255 iobuf_fdopen (int fd, const char *mode)
1257 iobuf_t a;
1258 fp_or_fd_t fp;
1259 file_filter_ctx_t *fcx;
1260 size_t len;
1262 #ifdef FILE_FILTER_USES_STDIO
1263 if (!(fp = fdopen (fd, mode)))
1264 return NULL;
1265 #else
1266 fp = (fp_or_fd_t) fd;
1267 #endif
1268 a = iobuf_alloc (strchr (mode, 'w') ? 2 : 1, IOBUF_BUFFER_SIZE);
1269 fcx = xmalloc (sizeof *fcx + 20);
1270 fcx->fp = fp;
1271 fcx->print_only_name = 1;
1272 sprintf (fcx->fname, "[fd %d]", fd);
1273 a->filter = file_filter;
1274 a->filter_ov = fcx;
1275 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1276 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1277 if (DBG_IOBUF)
1278 log_debug ("iobuf-%d.%d: fdopen `%s'\n", a->no, a->subno, fcx->fname);
1279 iobuf_ioctl (a, 3, 1, NULL); /* disable fd caching */
1280 return a;
1284 iobuf_t
1285 iobuf_sockopen (int fd, const char *mode)
1287 iobuf_t a;
1288 #ifdef HAVE_W32_SYSTEM
1289 sock_filter_ctx_t *scx;
1290 size_t len;
1292 a = iobuf_alloc (strchr (mode, 'w') ? 2 : 1, IOBUF_BUFFER_SIZE);
1293 scx = xmalloc (sizeof *scx + 25);
1294 scx->sock = fd;
1295 scx->print_only_name = 1;
1296 sprintf (scx->fname, "[sock %d]", fd);
1297 a->filter = sock_filter;
1298 a->filter_ov = scx;
1299 sock_filter (scx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1300 sock_filter (scx, IOBUFCTRL_INIT, NULL, NULL, &len);
1301 if (DBG_IOBUF)
1302 log_debug ("iobuf-%d.%d: sockopen `%s'\n", a->no, a->subno, scx->fname);
1303 iobuf_ioctl (a, 3, 1, NULL); /* disable fd caching */
1304 #else
1305 a = iobuf_fdopen (fd, mode);
1306 #endif
1307 return a;
1310 /****************
1311 * create an iobuf for writing to a file; the file will be created.
1313 iobuf_t
1314 iobuf_create (const char *fname)
1316 iobuf_t a;
1317 fp_or_fd_t fp;
1318 file_filter_ctx_t *fcx;
1319 size_t len;
1320 int print_only = 0;
1321 int fd;
1323 if (!fname || (*fname == '-' && !fname[1]))
1325 fp = FILEP_OR_FD_FOR_STDOUT;
1326 #ifdef USE_SETMODE
1327 setmode (my_fileno (fp), O_BINARY);
1328 #endif
1329 fname = "[stdout]";
1330 print_only = 1;
1332 else if ((fd = check_special_filename (fname)) != -1)
1333 return iobuf_fdopen (translate_file_handle (fd, 1), "wb");
1334 else if ((fp = my_fopen (fname, "wb")) == INVALID_FP)
1335 return NULL;
1336 a = iobuf_alloc (2, IOBUF_BUFFER_SIZE);
1337 fcx = xmalloc (sizeof *fcx + strlen (fname));
1338 fcx->fp = fp;
1339 fcx->print_only_name = print_only;
1340 strcpy (fcx->fname, fname);
1341 if (!print_only)
1342 a->real_fname = xstrdup (fname);
1343 a->filter = file_filter;
1344 a->filter_ov = fcx;
1345 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1346 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1347 if (DBG_IOBUF)
1348 log_debug ("iobuf-%d.%d: create `%s'\n", a->no, a->subno,
1349 a->desc?a->desc:"?");
1351 return a;
1354 /****************
1355 * append to an iobuf; if the file does not exist, create it.
1356 * cannot be used for stdout.
1357 * Note: This is not used.
1359 #if 0 /* not used */
1360 iobuf_t
1361 iobuf_append (const char *fname)
1363 iobuf_t a;
1364 FILE *fp;
1365 file_filter_ctx_t *fcx;
1366 size_t len;
1368 if (!fname)
1369 return NULL;
1370 else if (!(fp = my_fopen (fname, "ab")))
1371 return NULL;
1372 a = iobuf_alloc (2, IOBUF_BUFFER_SIZE);
1373 fcx = m_alloc (sizeof *fcx + strlen (fname));
1374 fcx->fp = fp;
1375 strcpy (fcx->fname, fname);
1376 a->real_fname = m_strdup (fname);
1377 a->filter = file_filter;
1378 a->filter_ov = fcx;
1379 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1380 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1381 if (DBG_IOBUF)
1382 log_debug ("iobuf-%d.%d: append `%s'\n", a->no, a->subno,
1383 a->desc?a->desc:"?");
1385 return a;
1387 #endif
1389 iobuf_t
1390 iobuf_openrw (const char *fname)
1392 iobuf_t a;
1393 fp_or_fd_t fp;
1394 file_filter_ctx_t *fcx;
1395 size_t len;
1397 if (!fname)
1398 return NULL;
1399 else if ((fp = my_fopen (fname, "r+b")) == INVALID_FP)
1400 return NULL;
1401 a = iobuf_alloc (2, IOBUF_BUFFER_SIZE);
1402 fcx = xmalloc (sizeof *fcx + strlen (fname));
1403 fcx->fp = fp;
1404 strcpy (fcx->fname, fname);
1405 a->real_fname = xstrdup (fname);
1406 a->filter = file_filter;
1407 a->filter_ov = fcx;
1408 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1409 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1410 if (DBG_IOBUF)
1411 log_debug ("iobuf-%d.%d: openrw `%s'\n", a->no, a->subno,
1412 a->desc?a->desc:"?");
1414 return a;
1419 iobuf_ioctl (iobuf_t a, int cmd, int intval, void *ptrval)
1421 if (cmd == 1)
1422 { /* keep system filepointer/descriptor open */
1423 if (DBG_IOBUF)
1424 log_debug ("iobuf-%d.%d: ioctl `%s' keep=%d\n",
1425 a ? a->no : -1, a ? a->subno : -1,
1426 a && a->desc ? a->desc : "?",
1427 intval);
1428 for (; a; a = a->chain)
1429 if (!a->chain && a->filter == file_filter)
1431 file_filter_ctx_t *b = a->filter_ov;
1432 b->keep_open = intval;
1433 return 0;
1435 #ifdef HAVE_W32_SYSTEM
1436 else if (!a->chain && a->filter == sock_filter)
1438 sock_filter_ctx_t *b = a->filter_ov;
1439 b->keep_open = intval;
1440 return 0;
1442 #endif
1444 else if (cmd == 2)
1445 { /* invalidate cache */
1446 if (DBG_IOBUF)
1447 log_debug ("iobuf-*.*: ioctl `%s' invalidate\n",
1448 ptrval ? (char *) ptrval : "?");
1449 if (!a && !intval && ptrval)
1451 #ifndef FILE_FILTER_USES_STDIO
1452 fd_cache_invalidate (ptrval);
1453 #endif
1454 return 0;
1457 else if (cmd == 3)
1458 { /* disallow/allow caching */
1459 if (DBG_IOBUF)
1460 log_debug ("iobuf-%d.%d: ioctl `%s' no_cache=%d\n",
1461 a ? a->no : -1, a ? a->subno : -1,
1462 a && a->desc? a->desc : "?",
1463 intval);
1464 for (; a; a = a->chain)
1465 if (!a->chain && a->filter == file_filter)
1467 file_filter_ctx_t *b = a->filter_ov;
1468 b->no_cache = intval;
1469 return 0;
1471 #ifdef HAVE_W32_SYSTEM
1472 else if (!a->chain && a->filter == sock_filter)
1474 sock_filter_ctx_t *b = a->filter_ov;
1475 b->no_cache = intval;
1476 return 0;
1478 #endif
1481 return -1;
1485 /****************
1486 * Register an i/o filter.
1489 iobuf_push_filter (iobuf_t a,
1490 int (*f) (void *opaque, int control,
1491 iobuf_t chain, byte * buf, size_t * len),
1492 void *ov)
1494 return iobuf_push_filter2 (a, f, ov, 0);
1498 iobuf_push_filter2 (iobuf_t a,
1499 int (*f) (void *opaque, int control,
1500 iobuf_t chain, byte * buf, size_t * len),
1501 void *ov, int rel_ov)
1503 iobuf_t b;
1504 size_t dummy_len = 0;
1505 int rc = 0;
1507 if (a->directfp)
1508 BUG ();
1510 if (a->use == 2 && (rc = iobuf_flush (a)))
1511 return rc;
1512 /* make a copy of the current stream, so that
1513 * A is the new stream and B the original one.
1514 * The contents of the buffers are transferred to the
1515 * new stream.
1517 b = xmalloc (sizeof *b);
1518 memcpy (b, a, sizeof *b);
1519 /* fixme: it is stupid to keep a copy of the name at every level
1520 * but we need the name somewhere because the name known by file_filter
1521 * may have been released when we need the name of the file */
1522 b->real_fname = a->real_fname ? xstrdup (a->real_fname) : NULL;
1523 /* remove the filter stuff from the new stream */
1524 a->filter = NULL;
1525 a->filter_ov = NULL;
1526 a->filter_ov_owner = 0;
1527 a->filter_eof = 0;
1528 if (a->use == 3)
1529 a->use = 2; /* make a write stream from a temp stream */
1531 if (a->use == 2)
1532 { /* allocate a fresh buffer for the
1533 original stream */
1534 b->d.buf = xmalloc (a->d.size);
1535 b->d.len = 0;
1536 b->d.start = 0;
1538 else
1539 { /* allocate a fresh buffer for the new
1540 stream */
1541 a->d.buf = xmalloc (a->d.size);
1542 a->d.len = 0;
1543 a->d.start = 0;
1545 /* disable nlimit for the new stream */
1546 a->ntotal = b->ntotal + b->nbytes;
1547 a->nlimit = a->nbytes = 0;
1548 a->nofast &= ~1;
1549 /* make a link from the new stream to the original stream */
1550 a->chain = b;
1551 a->opaque = b->opaque;
1553 /* setup the function on the new stream */
1554 a->filter = f;
1555 a->filter_ov = ov;
1556 a->filter_ov_owner = rel_ov;
1558 a->subno = b->subno + 1;
1559 f (ov, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &dummy_len);
1561 if (DBG_IOBUF)
1563 log_debug ("iobuf-%d.%d: push `%s'\n", a->no, a->subno,
1564 a->desc?a->desc:"?");
1565 print_chain (a);
1568 /* now we can initialize the new function if we have one */
1569 if (a->filter && (rc = a->filter (a->filter_ov, IOBUFCTRL_INIT, a->chain,
1570 NULL, &dummy_len)))
1571 log_error ("IOBUFCTRL_INIT failed: %s\n", gpg_strerror (rc));
1572 return rc;
1575 /****************
1576 * Remove an i/o filter.
1578 static int
1579 pop_filter (iobuf_t a, int (*f) (void *opaque, int control,
1580 iobuf_t chain, byte * buf, size_t * len),
1581 void *ov)
1583 iobuf_t b;
1584 size_t dummy_len = 0;
1585 int rc = 0;
1587 if (a->directfp)
1588 BUG ();
1590 if (DBG_IOBUF)
1591 log_debug ("iobuf-%d.%d: pop `%s'\n", a->no, a->subno,
1592 a->desc?a->desc:"?");
1593 if (!a->filter)
1594 { /* this is simple */
1595 b = a->chain;
1596 assert (b);
1597 xfree (a->d.buf);
1598 xfree (a->real_fname);
1599 memcpy (a, b, sizeof *a);
1600 xfree (b);
1601 return 0;
1603 for (b = a; b; b = b->chain)
1604 if (b->filter == f && (!ov || b->filter_ov == ov))
1605 break;
1606 if (!b)
1607 log_bug ("pop_filter(): filter function not found\n");
1609 /* flush this stream if it is an output stream */
1610 if (a->use == 2 && (rc = iobuf_flush (b)))
1612 log_error ("iobuf_flush failed in pop_filter: %s\n", gpg_strerror (rc));
1613 return rc;
1615 /* and tell the filter to free it self */
1616 if (b->filter && (rc = b->filter (b->filter_ov, IOBUFCTRL_FREE, b->chain,
1617 NULL, &dummy_len)))
1619 log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc));
1620 return rc;
1622 if (b->filter_ov && b->filter_ov_owner)
1624 xfree (b->filter_ov);
1625 b->filter_ov = NULL;
1629 /* and see how to remove it */
1630 if (a == b && !b->chain)
1631 log_bug ("can't remove the last filter from the chain\n");
1632 else if (a == b)
1633 { /* remove the first iobuf from the chain */
1634 /* everything from b is copied to a. This is save because
1635 * a flush has been done on the to be removed entry
1637 b = a->chain;
1638 xfree (a->d.buf);
1639 xfree (a->real_fname);
1640 memcpy (a, b, sizeof *a);
1641 xfree (b);
1642 if (DBG_IOBUF)
1643 log_debug ("iobuf-%d.%d: popped filter\n", a->no, a->subno);
1645 else if (!b->chain)
1646 { /* remove the last iobuf from the chain */
1647 log_bug ("Ohh jeee, trying to remove a head filter\n");
1649 else
1650 { /* remove an intermediate iobuf from the chain */
1651 log_bug ("Ohh jeee, trying to remove an intermediate filter\n");
1654 return rc;
1658 /****************
1659 * read underflow: read more bytes into the buffer and return
1660 * the first byte or -1 on EOF.
1662 static int
1663 underflow (iobuf_t a)
1665 size_t len;
1666 int rc;
1668 assert (a->d.start == a->d.len);
1669 if (a->use == 3)
1670 return -1; /* EOF because a temp buffer can't do an underflow */
1672 if (a->filter_eof)
1674 if (a->chain)
1676 iobuf_t b = a->chain;
1677 if (DBG_IOBUF)
1678 log_debug ("iobuf-%d.%d: pop `%s' in underflow\n",
1679 a->no, a->subno, a->desc?a->desc:"?");
1680 xfree (a->d.buf);
1681 xfree (a->real_fname);
1682 memcpy (a, b, sizeof *a);
1683 xfree (b);
1684 print_chain (a);
1686 else
1687 a->filter_eof = 0; /* for the top level filter */
1688 if (DBG_IOBUF)
1689 log_debug ("iobuf-%d.%d: underflow: eof (due to filter eof)\n",
1690 a->no, a->subno);
1691 return -1; /* return one(!) EOF */
1693 if (a->error)
1695 if (DBG_IOBUF)
1696 log_debug ("iobuf-%d.%d: error\n", a->no, a->subno);
1697 return -1;
1700 if (a->directfp)
1702 FILE *fp = a->directfp;
1704 len = fread (a->d.buf, 1, a->d.size, fp);
1705 if (len < a->d.size)
1707 if (ferror (fp))
1708 a->error = gpg_error_from_syserror ();
1710 a->d.len = len;
1711 a->d.start = 0;
1712 return len ? a->d.buf[a->d.start++] : -1;
1716 if (a->filter)
1718 len = a->d.size;
1719 if (DBG_IOBUF)
1720 log_debug ("iobuf-%d.%d: underflow: req=%lu\n",
1721 a->no, a->subno, (ulong) len);
1722 rc = a->filter (a->filter_ov, IOBUFCTRL_UNDERFLOW, a->chain,
1723 a->d.buf, &len);
1724 if (DBG_IOBUF)
1726 log_debug ("iobuf-%d.%d: underflow: got=%lu rc=%d\n",
1727 a->no, a->subno, (ulong) len, rc);
1728 /* if( a->no == 1 ) */
1729 /* log_hexdump (" data:", a->d.buf, len); */
1731 if (a->use == 1 && rc == -1)
1732 { /* EOF: we can remove the filter */
1733 size_t dummy_len = 0;
1735 /* and tell the filter to free itself */
1736 if ((rc = a->filter (a->filter_ov, IOBUFCTRL_FREE, a->chain,
1737 NULL, &dummy_len)))
1738 log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc));
1739 if (a->filter_ov && a->filter_ov_owner)
1741 xfree (a->filter_ov);
1742 a->filter_ov = NULL;
1744 a->filter = NULL;
1745 a->desc = NULL;
1746 a->filter_ov = NULL;
1747 a->filter_eof = 1;
1748 if (!len && a->chain)
1750 iobuf_t b = a->chain;
1751 if (DBG_IOBUF)
1752 log_debug ("iobuf-%d.%d: pop in underflow (!len)\n",
1753 a->no, a->subno);
1754 xfree (a->d.buf);
1755 xfree (a->real_fname);
1756 memcpy (a, b, sizeof *a);
1757 xfree (b);
1758 print_chain (a);
1761 else if (rc)
1762 a->error = rc;
1764 if (!len)
1766 if (DBG_IOBUF)
1767 log_debug ("iobuf-%d.%d: underflow: eof\n", a->no, a->subno);
1768 return -1;
1770 a->d.len = len;
1771 a->d.start = 0;
1772 return a->d.buf[a->d.start++];
1774 else
1776 if (DBG_IOBUF)
1777 log_debug ("iobuf-%d.%d: underflow: eof (no filter)\n",
1778 a->no, a->subno);
1779 return -1; /* no filter; return EOF */
1785 iobuf_flush (iobuf_t a)
1787 size_t len;
1788 int rc;
1790 if (a->directfp)
1791 return 0;
1793 if (a->use == 3)
1794 { /* increase the temp buffer */
1795 unsigned char *newbuf;
1796 size_t newsize = a->d.size + IOBUF_BUFFER_SIZE;
1798 if (DBG_IOBUF)
1799 log_debug ("increasing temp iobuf from %lu to %lu\n",
1800 (ulong) a->d.size, (ulong) newsize);
1801 newbuf = xmalloc (newsize);
1802 memcpy (newbuf, a->d.buf, a->d.len);
1803 xfree (a->d.buf);
1804 a->d.buf = newbuf;
1805 a->d.size = newsize;
1806 return 0;
1808 else if (a->use != 2)
1809 log_bug ("flush on non-output iobuf\n");
1810 else if (!a->filter)
1811 log_bug ("iobuf_flush: no filter\n");
1812 len = a->d.len;
1813 rc = a->filter (a->filter_ov, IOBUFCTRL_FLUSH, a->chain, a->d.buf, &len);
1814 if (!rc && len != a->d.len)
1816 log_info ("iobuf_flush did not write all!\n");
1817 rc = GPG_ERR_INTERNAL;
1819 else if (rc)
1820 a->error = rc;
1821 a->d.len = 0;
1823 return rc;
1827 /****************
1828 * Read a byte from the iobuf; returns -1 on EOF
1831 iobuf_readbyte (iobuf_t a)
1833 int c;
1835 if (a->nlimit && a->nbytes >= a->nlimit)
1836 return -1; /* forced EOF */
1838 if (a->d.start < a->d.len)
1840 c = a->d.buf[a->d.start++];
1842 else if ((c = underflow (a)) == -1)
1843 return -1; /* EOF */
1845 a->nbytes++;
1846 return c;
1851 iobuf_read (iobuf_t a, void *buffer, unsigned int buflen)
1853 unsigned char *buf = (unsigned char *)buffer;
1854 int c, n;
1856 if (a->nlimit)
1858 /* Handle special cases. */
1859 for (n = 0; n < buflen; n++)
1861 if ((c = iobuf_readbyte (a)) == -1)
1863 if (!n)
1864 return -1; /* eof */
1865 break;
1867 else if (buf)
1868 *buf = c;
1869 if (buf)
1870 buf++;
1872 return n;
1875 n = 0;
1878 if (n < buflen && a->d.start < a->d.len)
1880 unsigned size = a->d.len - a->d.start;
1881 if (size > buflen - n)
1882 size = buflen - n;
1883 if (buf)
1884 memcpy (buf, a->d.buf + a->d.start, size);
1885 n += size;
1886 a->d.start += size;
1887 if (buf)
1888 buf += size;
1890 if (n < buflen)
1892 if ((c = underflow (a)) == -1)
1894 a->nbytes += n;
1895 return n ? n : -1 /*EOF*/;
1897 if (buf)
1898 *buf++ = c;
1899 n++;
1902 while (n < buflen);
1903 a->nbytes += n;
1904 return n;
1909 /****************
1910 * Have a look at the iobuf.
1911 * NOTE: This only works in special cases.
1914 iobuf_peek (iobuf_t a, byte * buf, unsigned buflen)
1916 int n = 0;
1918 if (a->filter_eof)
1919 return -1;
1921 if (!(a->d.start < a->d.len))
1923 if (underflow (a) == -1)
1924 return -1;
1925 /* And unget this character. */
1926 assert (a->d.start == 1);
1927 a->d.start = 0;
1930 for (n = 0; n < buflen && (a->d.start + n) < a->d.len; n++, buf++)
1931 *buf = a->d.buf[n];
1932 return n;
1939 iobuf_writebyte (iobuf_t a, unsigned int c)
1941 int rc;
1943 if (a->directfp)
1944 BUG ();
1946 if (a->d.len == a->d.size)
1947 if ((rc=iobuf_flush (a)))
1948 return rc;
1950 assert (a->d.len < a->d.size);
1951 a->d.buf[a->d.len++] = c;
1952 return 0;
1957 iobuf_write (iobuf_t a, const void *buffer, unsigned int buflen)
1959 const unsigned char *buf = (const unsigned char *)buffer;
1960 int rc;
1962 if (a->directfp)
1963 BUG ();
1967 if (buflen && a->d.len < a->d.size)
1969 unsigned size = a->d.size - a->d.len;
1970 if (size > buflen)
1971 size = buflen;
1972 memcpy (a->d.buf + a->d.len, buf, size);
1973 buflen -= size;
1974 buf += size;
1975 a->d.len += size;
1977 if (buflen)
1979 rc = iobuf_flush (a);
1980 if (rc)
1981 return rc;
1984 while (buflen);
1985 return 0;
1990 iobuf_writestr (iobuf_t a, const char *buf)
1992 int rc;
1994 for (; *buf; buf++)
1995 if ((rc=iobuf_writebyte (a, *buf)))
1996 return rc;
1997 return 0;
2002 /****************
2003 * copy the contents of TEMP to A.
2006 iobuf_write_temp (iobuf_t a, iobuf_t temp)
2008 while (temp->chain)
2009 pop_filter (temp, temp->filter, NULL);
2010 return iobuf_write (a, temp->d.buf, temp->d.len);
2013 /****************
2014 * copy the contents of the temp io stream to BUFFER.
2016 size_t
2017 iobuf_temp_to_buffer (iobuf_t a, byte * buffer, size_t buflen)
2019 size_t n = a->d.len;
2021 if (n > buflen)
2022 n = buflen;
2023 memcpy (buffer, a->d.buf, n);
2024 return n;
2028 /****************
2029 * Call this function to terminate processing of the temp stream
2030 * without closing it. This removes all filters from the stream
2031 * makes sure that iobuf_get_temp_{buffer,length}() returns correct
2032 * values.
2034 void
2035 iobuf_flush_temp (iobuf_t temp)
2037 while (temp->chain)
2038 pop_filter (temp, temp->filter, NULL);
2042 /****************
2043 * Set a limit on how many bytes may be read from the input stream A.
2044 * Setting the limit to 0 disables this feature.
2046 void
2047 iobuf_set_limit (iobuf_t a, off_t nlimit)
2049 if (nlimit)
2050 a->nofast |= 1;
2051 else
2052 a->nofast &= ~1;
2053 a->nlimit = nlimit;
2054 a->ntotal += a->nbytes;
2055 a->nbytes = 0;
2060 /* Return the length of an open file A. IF OVERFLOW is not NULL it
2061 will be set to true if the file is larger than what off_t can cope
2062 with. The function return 0 on error or on overflow condition. */
2063 off_t
2064 iobuf_get_filelength (iobuf_t a, int *overflow)
2066 struct stat st;
2068 if (overflow)
2069 *overflow = 0;
2071 if ( a->directfp )
2073 FILE *fp = a->directfp;
2075 if ( !fstat(fileno(fp), &st) )
2076 return st.st_size;
2077 log_error("fstat() failed: %s\n", strerror(errno) );
2078 return 0;
2081 /* Hmmm: file_filter may have already been removed */
2082 for ( ; a; a = a->chain )
2083 if ( !a->chain && a->filter == file_filter )
2085 file_filter_ctx_t *b = a->filter_ov;
2086 fp_or_fd_t fp = b->fp;
2088 #if defined(HAVE_W32_SYSTEM) && !defined(FILE_FILTER_USES_STDIO)
2089 ulong size;
2090 static int (* __stdcall get_file_size_ex) (void *handle,
2091 LARGE_INTEGER *r_size);
2092 static int get_file_size_ex_initialized;
2094 if (!get_file_size_ex_initialized)
2096 void *handle;
2098 handle = dlopen ("kernel32.dll", RTLD_LAZY);
2099 if (handle)
2101 get_file_size_ex = dlsym (handle, "GetFileSizeEx");
2102 if (!get_file_size_ex)
2103 dlclose (handle);
2105 get_file_size_ex_initialized = 1;
2108 if (get_file_size_ex)
2110 /* This is a newer system with GetFileSizeEx; we use this
2111 then because it seem that GetFileSize won't return a
2112 proper error in case a file is larger than 4GB. */
2113 LARGE_INTEGER exsize;
2115 if (get_file_size_ex (fp, &exsize))
2117 if (!exsize.u.HighPart)
2118 return exsize.u.LowPart;
2119 if (overflow)
2120 *overflow = 1;
2121 return 0;
2124 else
2126 if ((size=GetFileSize (fp, NULL)) != 0xffffffff)
2127 return size;
2129 log_error ("GetFileSize for handle %p failed: %s\n",
2130 fp, w32_strerror (0));
2131 #else
2132 if ( !fstat(my_fileno(fp), &st) )
2133 return st.st_size;
2134 log_error("fstat() failed: %s\n", strerror(errno) );
2135 #endif
2136 break/*the for loop*/;
2139 return 0;
2143 /* Return the file descriptor of the underlying file or -1 if it is
2144 not available. */
2145 int
2146 iobuf_get_fd (iobuf_t a)
2148 if (a->directfp)
2149 return fileno ( (FILE*)a->directfp );
2151 for ( ; a; a = a->chain )
2152 if (!a->chain && a->filter == file_filter)
2154 file_filter_ctx_t *b = a->filter_ov;
2155 fp_or_fd_t fp = b->fp;
2157 return my_fileno (fp);
2160 return -1;
2165 /****************
2166 * Tell the file position, where the next read will take place
2168 off_t
2169 iobuf_tell (iobuf_t a)
2171 return a->ntotal + a->nbytes;
2175 #if !defined(HAVE_FSEEKO) && !defined(fseeko)
2177 #ifdef HAVE_LIMITS_H
2178 # include <limits.h>
2179 #endif
2180 #ifndef LONG_MAX
2181 # define LONG_MAX ((long) ((unsigned long) -1 >> 1))
2182 #endif
2183 #ifndef LONG_MIN
2184 # define LONG_MIN (-1 - LONG_MAX)
2185 #endif
2187 /****************
2188 * A substitute for fseeko, for hosts that don't have it.
2190 static int
2191 fseeko (FILE * stream, off_t newpos, int whence)
2193 while (newpos != (long) newpos)
2195 long pos = newpos < 0 ? LONG_MIN : LONG_MAX;
2196 if (fseek (stream, pos, whence) != 0)
2197 return -1;
2198 newpos -= pos;
2199 whence = SEEK_CUR;
2201 return fseek (stream, (long) newpos, whence);
2203 #endif
2205 /****************
2206 * This is a very limited implementation. It simply discards all internal
2207 * buffering and removes all filters but the first one.
2210 iobuf_seek (iobuf_t a, off_t newpos)
2212 file_filter_ctx_t *b = NULL;
2214 if (a->directfp)
2216 FILE *fp = a->directfp;
2217 if (fseeko (fp, newpos, SEEK_SET))
2219 log_error ("can't seek: %s\n", strerror (errno));
2220 return -1;
2222 clearerr (fp);
2224 else
2226 for (; a; a = a->chain)
2228 if (!a->chain && a->filter == file_filter)
2230 b = a->filter_ov;
2231 break;
2234 if (!a)
2235 return -1;
2236 #ifdef FILE_FILTER_USES_STDIO
2237 if (fseeko (b->fp, newpos, SEEK_SET))
2239 log_error ("can't fseek: %s\n", strerror (errno));
2240 return -1;
2242 #else
2243 #ifdef HAVE_W32_SYSTEM
2244 if (SetFilePointer (b->fp, newpos, NULL, FILE_BEGIN) == 0xffffffff)
2246 log_error ("SetFilePointer failed on handle %p: ec=%d\n",
2247 b->fp, (int) GetLastError ());
2248 return -1;
2250 #else
2251 if (lseek (b->fp, newpos, SEEK_SET) == (off_t) - 1)
2253 log_error ("can't lseek: %s\n", strerror (errno));
2254 return -1;
2256 #endif
2257 #endif
2259 a->d.len = 0; /* discard buffer */
2260 a->d.start = 0;
2261 a->nbytes = 0;
2262 a->nlimit = 0;
2263 a->nofast &= ~1;
2264 a->ntotal = newpos;
2265 a->error = 0;
2266 /* remove filters, but the last */
2267 if (a->chain)
2268 log_debug ("pop_filter called in iobuf_seek - please report\n");
2269 while (a->chain)
2270 pop_filter (a, a->filter, NULL);
2272 return 0;
2280 /****************
2281 * Retrieve the real filename
2283 const char *
2284 iobuf_get_real_fname (iobuf_t a)
2286 if (a->real_fname)
2287 return a->real_fname;
2289 /* the old solution */
2290 for (; a; a = a->chain)
2291 if (!a->chain && a->filter == file_filter)
2293 file_filter_ctx_t *b = a->filter_ov;
2294 return b->print_only_name ? NULL : b->fname;
2297 return NULL;
2301 /****************
2302 * Retrieve the filename
2304 const char *
2305 iobuf_get_fname (iobuf_t a)
2307 for (; a; a = a->chain)
2308 if (!a->chain && a->filter == file_filter)
2310 file_filter_ctx_t *b = a->filter_ov;
2311 return b->fname;
2314 return NULL;
2318 /****************
2319 * enable partial block mode as described in the OpenPGP draft.
2320 * LEN is the first length byte on read, but ignored on writes.
2322 void
2323 iobuf_set_partial_block_mode (iobuf_t a, size_t len)
2325 block_filter_ctx_t *ctx = xcalloc (1, sizeof *ctx);
2327 assert (a->use == 1 || a->use == 2);
2328 ctx->use = a->use;
2329 if (!len)
2331 if (a->use == 1)
2332 log_debug ("pop_filter called in set_partial_block_mode"
2333 " - please report\n");
2334 pop_filter (a, block_filter, NULL);
2336 else
2338 ctx->partial = 1;
2339 ctx->size = 0;
2340 ctx->first_c = len;
2341 iobuf_push_filter (a, block_filter, ctx);
2347 /****************
2348 * Same as fgets() but if the buffer is too short a larger one will
2349 * be allocated up to some limit *max_length.
2350 * A line is considered a byte stream ending in a LF.
2351 * Returns the length of the line. EOF is indicated by a line of
2352 * length zero. The last LF may be missing due to an EOF.
2353 * is max_length is zero on return, the line has been truncated.
2355 * Note: The buffer is allocated with enough space to append a CR,LF,EOL
2357 unsigned int
2358 iobuf_read_line (iobuf_t a, byte ** addr_of_buffer,
2359 unsigned *length_of_buffer, unsigned *max_length)
2361 int c;
2362 char *buffer = (char *)*addr_of_buffer;
2363 unsigned length = *length_of_buffer;
2364 unsigned nbytes = 0;
2365 unsigned maxlen = *max_length;
2366 char *p;
2368 if (!buffer)
2369 { /* must allocate a new buffer */
2370 length = 256;
2371 buffer = xmalloc (length);
2372 *addr_of_buffer = (unsigned char *)buffer;
2373 *length_of_buffer = length;
2376 length -= 3; /* reserve 3 bytes (cr,lf,eol) */
2377 p = buffer;
2378 while ((c = iobuf_get (a)) != -1)
2380 if (nbytes == length)
2381 { /* increase the buffer */
2382 if (length > maxlen)
2383 { /* this is out limit */
2384 /* skip the rest of the line */
2385 while (c != '\n' && (c = iobuf_get (a)) != -1)
2387 *p++ = '\n'; /* always append a LF (we have reserved space) */
2388 nbytes++;
2389 *max_length = 0; /* indicate truncation */
2390 break;
2392 length += 3; /* correct for the reserved byte */
2393 length += length < 1024 ? 256 : 1024;
2394 buffer = xrealloc (buffer, length);
2395 *addr_of_buffer = (unsigned char *)buffer;
2396 *length_of_buffer = length;
2397 length -= 3; /* and reserve again */
2398 p = buffer + nbytes;
2400 *p++ = c;
2401 nbytes++;
2402 if (c == '\n')
2403 break;
2405 *p = 0; /* make sure the line is a string */
2407 return nbytes;
2410 static int
2411 translate_file_handle (int fd, int for_write)
2413 #ifdef HAVE_W32_SYSTEM
2414 # ifdef FILE_FILTER_USES_STDIO
2415 fd = translate_sys2libc_fd (fd, for_write);
2416 # else
2418 int x;
2420 (void)for_write;
2422 if (fd == 0)
2423 x = (int) GetStdHandle (STD_INPUT_HANDLE);
2424 else if (fd == 1)
2425 x = (int) GetStdHandle (STD_OUTPUT_HANDLE);
2426 else if (fd == 2)
2427 x = (int) GetStdHandle (STD_ERROR_HANDLE);
2428 else
2429 x = fd;
2431 if (x == -1)
2432 log_debug ("GetStdHandle(%d) failed: ec=%d\n",
2433 fd, (int) GetLastError ());
2435 fd = x;
2437 # endif
2438 #else
2439 (void)for_write;
2440 #endif
2441 return fd;
2445 void
2446 iobuf_skip_rest (iobuf_t a, unsigned long n, int partial)
2448 if ( partial )
2450 for (;;)
2452 if (a->nofast || a->d.start >= a->d.len)
2454 if (iobuf_readbyte (a) == -1)
2456 break;
2459 else
2461 unsigned long count = a->d.len - a->d.start;
2462 a->nbytes += count;
2463 a->d.start = a->d.len;
2467 else
2469 unsigned long remaining = n;
2470 while (remaining > 0)
2472 if (a->nofast || a->d.start >= a->d.len)
2474 if (iobuf_readbyte (a) == -1)
2476 break;
2478 --remaining;
2480 else
2482 unsigned long count = a->d.len - a->d.start;
2483 if (count > remaining)
2485 count = remaining;
2487 a->nbytes += count;
2488 a->d.start += count;
2489 remaining -= count;