2007-07-05 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / common / iobuf.c
blobabab69d0195aaf79c97954c91fd18d68e3ac1ffa
1 /* iobuf.c - File Handling for OpenPGP.
2 * Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2006,
3 * 2007 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 fiel 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 #ifdef FILE_FILTER_USES_STDIO
416 if (control == IOBUFCTRL_UNDERFLOW)
418 assert (size); /* need a buffer */
419 if (feof (f))
420 { /* On terminals you could easiely read as many EOFs as you call */
421 rc = -1; /* fread() or fgetc() repeatly. Every call will block until you press */
422 *ret_len = 0; /* CTRL-D. So we catch this case before we call fread() again. */
424 else
426 clearerr (f);
427 nbytes = fread (buf, 1, size, f);
428 if (feof (f) && !nbytes)
430 rc = -1; /* okay: we can return EOF now. */
432 else if (ferror (f) && errno != EPIPE)
434 rc = gpg_error_from_syserror ();
435 log_error ("%s: read error: %s\n", a->fname, strerror (errno));
437 *ret_len = nbytes;
440 else if (control == IOBUFCTRL_FLUSH)
442 if (size)
444 clearerr (f);
445 nbytes = fwrite (buf, 1, size, f);
446 if (ferror (f))
448 rc = gpg_error_from_syserror ();
449 log_error ("%s: write error: %s\n", a->fname, strerror (errno));
452 *ret_len = nbytes;
454 else if (control == IOBUFCTRL_INIT)
456 a->keep_open = a->no_cache = 0;
458 else if (control == IOBUFCTRL_DESC)
460 *(char **) buf = "file_filter";
462 else if (control == IOBUFCTRL_FREE)
464 if (f != stdin && f != stdout)
466 if (DBG_IOBUF)
467 log_debug ("%s: close fd %d\n", a->fname, fileno (f));
468 if (!a->keep_open)
469 fclose (f);
471 f = NULL;
472 xfree (a); /* we can free our context now */
474 #else /* !stdio implementation */
476 if (control == IOBUFCTRL_UNDERFLOW)
478 assert (size); /* need a buffer */
479 if (a->eof_seen)
481 rc = -1;
482 *ret_len = 0;
484 else
486 #ifdef HAVE_W32_SYSTEM
487 unsigned long nread;
489 nbytes = 0;
490 if (!ReadFile (f, buf, size, &nread, NULL))
492 int ec = (int) GetLastError ();
493 if (ec != ERROR_BROKEN_PIPE)
495 rc = gpg_error_from_errno (ec);
496 log_error ("%s: read error: ec=%d\n", a->fname, ec);
499 else if (!nread)
501 a->eof_seen = 1;
502 rc = -1;
504 else
506 nbytes = nread;
509 #else
511 int n;
513 nbytes = 0;
516 n = read (f, buf, size);
518 while (n == -1 && errno == EINTR);
519 if (n == -1)
520 { /* error */
521 if (errno != EPIPE)
523 rc = gpg_error_from_syserror ();
524 log_error ("%s: read error: %s\n",
525 a->fname, strerror (errno));
528 else if (!n)
529 { /* eof */
530 a->eof_seen = 1;
531 rc = -1;
533 else
535 nbytes = n;
537 #endif
538 *ret_len = nbytes;
541 else if (control == IOBUFCTRL_FLUSH)
543 if (size)
545 #ifdef HAVE_W32_SYSTEM
546 byte *p = buf;
547 unsigned long n;
549 nbytes = size;
552 if (size && !WriteFile (f, p, nbytes, &n, NULL))
554 int ec = (int) GetLastError ();
555 rc = gpg_error_from_errno (ec);
556 log_error ("%s: write error: ec=%d\n", a->fname, ec);
557 break;
559 p += n;
560 nbytes -= n;
562 while (nbytes);
563 nbytes = p - buf;
564 #else
565 byte *p = buf;
566 int n;
568 nbytes = size;
573 n = write (f, p, nbytes);
575 while (n == -1 && errno == EINTR);
576 if (n > 0)
578 p += n;
579 nbytes -= n;
582 while (n != -1 && nbytes);
583 if (n == -1)
585 rc = gpg_error_from_syserror ();
586 log_error ("%s: write error: %s\n", a->fname, strerror (errno));
588 nbytes = p - buf;
589 #endif
591 *ret_len = nbytes;
593 else if (control == IOBUFCTRL_INIT)
595 a->eof_seen = 0;
596 a->keep_open = 0;
597 a->no_cache = 0;
599 else if (control == IOBUFCTRL_DESC)
601 *(char **) buf = "file_filter(fd)";
603 else if (control == IOBUFCTRL_FREE)
605 #ifdef HAVE_W32_SYSTEM
606 if (f != FILEP_OR_FD_FOR_STDIN && f != FILEP_OR_FD_FOR_STDOUT)
608 if (DBG_IOBUF)
609 log_debug ("%s: close handle %p\n", a->fname, f);
610 if (!a->keep_open)
611 fd_cache_close (a->no_cache ? NULL : a->fname, f);
613 #else
614 if ((int) f != 0 && (int) f != 1)
616 if (DBG_IOBUF)
617 log_debug ("%s: close fd %d\n", a->fname, f);
618 if (!a->keep_open)
619 fd_cache_close (a->no_cache ? NULL : a->fname, f);
621 f = INVALID_FP;
622 #endif
623 xfree (a); /* we can free our context now */
625 #endif /* !stdio implementation */
626 return rc;
630 #ifdef HAVE_W32_SYSTEM
631 /* Because network sockets are special objects under Lose32 we have to
632 use a dedicated filter for them. */
633 static int
634 sock_filter (void *opaque, int control, iobuf_t chain, byte * buf,
635 size_t * ret_len)
637 sock_filter_ctx_t *a = opaque;
638 size_t size = *ret_len;
639 size_t nbytes = 0;
640 int rc = 0;
642 if (control == IOBUFCTRL_UNDERFLOW)
644 assert (size); /* need a buffer */
645 if (a->eof_seen)
647 rc = -1;
648 *ret_len = 0;
650 else
652 int nread;
654 nread = recv (a->sock, buf, size, 0);
655 if (nread == SOCKET_ERROR)
657 int ec = (int) WSAGetLastError ();
658 rc = gpg_error_from_errno (ec);
659 log_error ("socket read error: ec=%d\n", ec);
661 else if (!nread)
663 a->eof_seen = 1;
664 rc = -1;
666 else
668 nbytes = nread;
670 *ret_len = nbytes;
673 else if (control == IOBUFCTRL_FLUSH)
675 if (size)
677 byte *p = buf;
678 int n;
680 nbytes = size;
683 n = send (a->sock, p, nbytes, 0);
684 if (n == SOCKET_ERROR)
686 int ec = (int) WSAGetLastError ();
687 rc = gpg_error_from_errno (ec);
688 log_error ("socket write error: ec=%d\n", ec);
689 break;
691 p += n;
692 nbytes -= n;
694 while (nbytes);
695 nbytes = p - buf;
697 *ret_len = nbytes;
699 else if (control == IOBUFCTRL_INIT)
701 a->eof_seen = 0;
702 a->keep_open = 0;
703 a->no_cache = 0;
705 else if (control == IOBUFCTRL_DESC)
707 *(char **) buf = "sock_filter";
709 else if (control == IOBUFCTRL_FREE)
711 if (!a->keep_open)
712 closesocket (a->sock);
713 xfree (a); /* we can free our context now */
715 return rc;
717 #endif /*HAVE_W32_SYSTEM*/
719 /****************
720 * This is used to implement the block write mode.
721 * Block reading is done on a byte by byte basis in readbyte(),
722 * without a filter
724 static int
725 block_filter (void *opaque, int control, iobuf_t chain, byte * buffer,
726 size_t * ret_len)
728 block_filter_ctx_t *a = opaque;
729 char *buf = (char *)buffer;
730 size_t size = *ret_len;
731 int c, needed, rc = 0;
732 char *p;
734 if (control == IOBUFCTRL_UNDERFLOW)
736 size_t n = 0;
738 p = buf;
739 assert (size); /* need a buffer */
740 if (a->eof) /* don't read any further */
741 rc = -1;
742 while (!rc && size)
744 if (!a->size)
745 { /* get the length bytes */
746 if (a->partial == 2)
748 a->eof = 1;
749 if (!n)
750 rc = -1;
751 break;
753 else if (a->partial)
755 /* These OpenPGP introduced huffman like encoded length
756 * bytes are really a mess :-( */
757 if (a->first_c)
759 c = a->first_c;
760 a->first_c = 0;
762 else if ((c = iobuf_get (chain)) == -1)
764 log_error ("block_filter: 1st length byte missing\n");
765 rc = GPG_ERR_BAD_DATA;
766 break;
768 if (c < 192)
770 a->size = c;
771 a->partial = 2;
772 if (!a->size)
774 a->eof = 1;
775 if (!n)
776 rc = -1;
777 break;
780 else if (c < 224)
782 a->size = (c - 192) * 256;
783 if ((c = iobuf_get (chain)) == -1)
785 log_error
786 ("block_filter: 2nd length byte missing\n");
787 rc = GPG_ERR_BAD_DATA;
788 break;
790 a->size += c + 192;
791 a->partial = 2;
792 if (!a->size)
794 a->eof = 1;
795 if (!n)
796 rc = -1;
797 break;
800 else if (c == 255)
802 a->size = iobuf_get (chain) << 24;
803 a->size |= iobuf_get (chain) << 16;
804 a->size |= iobuf_get (chain) << 8;
805 if ((c = iobuf_get (chain)) == -1)
807 log_error ("block_filter: invalid 4 byte length\n");
808 rc = GPG_ERR_BAD_DATA;
809 break;
811 a->size |= c;
812 a->partial = 2;
813 if (!a->size)
815 a->eof = 1;
816 if (!n)
817 rc = -1;
818 break;
821 else
822 { /* Next partial body length. */
823 a->size = 1 << (c & 0x1f);
825 /* log_debug("partial: ctx=%p c=%02x size=%u\n", a, c, a->size); */
827 else
828 BUG ();
831 while (!rc && size && a->size)
833 needed = size < a->size ? size : a->size;
834 c = iobuf_read (chain, p, needed);
835 if (c < needed)
837 if (c == -1)
838 c = 0;
839 log_error
840 ("block_filter %p: read error (size=%lu,a->size=%lu)\n",
841 a, (ulong) size + c, (ulong) a->size + c);
842 rc = GPG_ERR_BAD_DATA;
844 else
846 size -= c;
847 a->size -= c;
848 p += c;
849 n += c;
853 *ret_len = n;
855 else if (control == IOBUFCTRL_FLUSH)
857 if (a->partial)
858 { /* the complicated openpgp scheme */
859 size_t blen, n, nbytes = size + a->buflen;
861 assert (a->buflen <= OP_MIN_PARTIAL_CHUNK);
862 if (nbytes < OP_MIN_PARTIAL_CHUNK)
864 /* not enough to write a partial block out; so we store it */
865 if (!a->buffer)
866 a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK);
867 memcpy (a->buffer + a->buflen, buf, size);
868 a->buflen += size;
870 else
871 { /* okay, we can write out something */
872 /* do this in a loop to use the most efficient block lengths */
873 p = buf;
876 /* find the best matching block length - this is limited
877 * by the size of the internal buffering */
878 for (blen = OP_MIN_PARTIAL_CHUNK * 2,
879 c = OP_MIN_PARTIAL_CHUNK_2POW + 1; blen <= nbytes;
880 blen *= 2, c++)
882 blen /= 2;
883 c--;
884 /* write the partial length header */
885 assert (c <= 0x1f); /*;-) */
886 c |= 0xe0;
887 iobuf_put (chain, c);
888 if ((n = a->buflen))
889 { /* write stuff from the buffer */
890 assert (n == OP_MIN_PARTIAL_CHUNK);
891 if (iobuf_write (chain, a->buffer, n))
892 rc = gpg_error_from_syserror ();
893 a->buflen = 0;
894 nbytes -= n;
896 if ((n = nbytes) > blen)
897 n = blen;
898 if (n && iobuf_write (chain, p, n))
899 rc = gpg_error_from_syserror ();
900 p += n;
901 nbytes -= n;
903 while (!rc && nbytes >= OP_MIN_PARTIAL_CHUNK);
904 /* store the rest in the buffer */
905 if (!rc && nbytes)
907 assert (!a->buflen);
908 assert (nbytes < OP_MIN_PARTIAL_CHUNK);
909 if (!a->buffer)
910 a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK);
911 memcpy (a->buffer, p, nbytes);
912 a->buflen = nbytes;
916 else
917 BUG ();
919 else if (control == IOBUFCTRL_INIT)
921 if (DBG_IOBUF)
922 log_debug ("init block_filter %p\n", a);
923 if (a->partial)
924 a->count = 0;
925 else if (a->use == 1)
926 a->count = a->size = 0;
927 else
928 a->count = a->size; /* force first length bytes */
929 a->eof = 0;
930 a->buffer = NULL;
931 a->buflen = 0;
933 else if (control == IOBUFCTRL_DESC)
935 *(char **) buf = "block_filter";
937 else if (control == IOBUFCTRL_FREE)
939 if (a->use == 2)
940 { /* write the end markers */
941 if (a->partial)
943 u32 len;
944 /* write out the remaining bytes without a partial header
945 * the length of this header may be 0 - but if it is
946 * the first block we are not allowed to use a partial header
947 * and frankly we can't do so, because this length must be
948 * a power of 2. This is _really_ complicated because we
949 * have to check the possible length of a packet prior
950 * to it's creation: a chain of filters becomes complicated
951 * and we need a lot of code to handle compressed packets etc.
952 * :-(((((((
954 /* construct header */
955 len = a->buflen;
956 /*log_debug("partial: remaining length=%u\n", len ); */
957 if (len < 192)
958 rc = iobuf_put (chain, len);
959 else if (len < 8384)
961 if (!(rc = iobuf_put (chain, ((len - 192) / 256) + 192)))
962 rc = iobuf_put (chain, ((len - 192) % 256));
964 else
965 { /* use a 4 byte header */
966 if (!(rc = iobuf_put (chain, 0xff)))
967 if (!(rc = iobuf_put (chain, (len >> 24) & 0xff)))
968 if (!(rc = iobuf_put (chain, (len >> 16) & 0xff)))
969 if (!(rc = iobuf_put (chain, (len >> 8) & 0xff)))
970 rc = iobuf_put (chain, len & 0xff);
972 if (!rc && len)
973 rc = iobuf_write (chain, a->buffer, len);
974 if (rc)
976 log_error ("block_filter: write error: %s\n",
977 strerror (errno));
978 rc = gpg_error_from_syserror ();
980 xfree (a->buffer);
981 a->buffer = NULL;
982 a->buflen = 0;
984 else
985 BUG ();
987 else if (a->size)
989 log_error ("block_filter: pending bytes!\n");
991 if (DBG_IOBUF)
992 log_debug ("free block_filter %p\n", a);
993 xfree (a); /* we can free our context now */
996 return rc;
1000 static void
1001 print_chain (iobuf_t a)
1003 if (!DBG_IOBUF)
1004 return;
1005 for (; a; a = a->chain)
1007 size_t dummy_len = 0;
1008 const char *desc = "[none]";
1010 if (a->filter)
1011 a->filter (a->filter_ov, IOBUFCTRL_DESC, NULL,
1012 (byte *) & desc, &dummy_len);
1014 log_debug ("iobuf chain: %d.%d `%s' filter_eof=%d start=%d len=%d\n",
1015 a->no, a->subno, desc, a->filter_eof,
1016 (int) a->d.start, (int) a->d.len);
1021 iobuf_print_chain (iobuf_t a)
1023 print_chain (a);
1024 return 0;
1027 /****************
1028 * Allocate a new io buffer, with no function assigned.
1029 * Use is the desired usage: 1 for input, 2 for output, 3 for temp buffer
1030 * BUFSIZE is a suggested buffer size.
1032 iobuf_t
1033 iobuf_alloc (int use, size_t bufsize)
1035 iobuf_t a;
1036 static int number = 0;
1038 a = xcalloc (1, sizeof *a);
1039 a->use = use;
1040 a->d.buf = xmalloc (bufsize);
1041 a->d.size = bufsize;
1042 a->no = ++number;
1043 a->subno = 0;
1044 a->opaque = NULL;
1045 a->real_fname = NULL;
1046 return a;
1050 iobuf_close (iobuf_t a)
1052 iobuf_t a2;
1053 size_t dummy_len = 0;
1054 int rc = 0;
1056 if (a && a->directfp)
1058 fclose (a->directfp);
1059 xfree (a->real_fname);
1060 if (DBG_IOBUF)
1061 log_debug ("iobuf_close -> %p\n", a->directfp);
1062 return 0;
1065 for (; a && !rc; a = a2)
1067 a2 = a->chain;
1068 if (a->use == 2 && (rc = iobuf_flush (a)))
1069 log_error ("iobuf_flush failed on close: %s\n", gpg_strerror (rc));
1071 if (DBG_IOBUF)
1072 log_debug ("iobuf-%d.%d: close `%s'\n", a->no, a->subno, a->desc);
1073 if (a->filter && (rc = a->filter (a->filter_ov, IOBUFCTRL_FREE,
1074 a->chain, NULL, &dummy_len)))
1075 log_error ("IOBUFCTRL_FREE failed on close: %s\n", gpg_strerror (rc));
1076 xfree (a->real_fname);
1077 if (a->d.buf)
1079 memset (a->d.buf, 0, a->d.size); /* erase the buffer */
1080 xfree (a->d.buf);
1082 xfree (a);
1084 return rc;
1088 iobuf_cancel (iobuf_t a)
1090 const char *s;
1091 iobuf_t a2;
1092 int rc;
1093 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1094 char *remove_name = NULL;
1095 #endif
1097 if (a && a->use == 2)
1099 s = iobuf_get_real_fname (a);
1100 if (s && *s)
1102 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1103 remove_name = xstrdup (s);
1104 #else
1105 remove (s);
1106 #endif
1110 /* send a cancel message to all filters */
1111 for (a2 = a; a2; a2 = a2->chain)
1113 size_t dummy;
1114 if (a2->filter)
1115 a2->filter (a2->filter_ov, IOBUFCTRL_CANCEL, a2->chain, NULL, &dummy);
1118 rc = iobuf_close (a);
1119 #if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
1120 if (remove_name)
1122 /* Argg, MSDOS does not allow to remove open files. So
1123 * we have to do it here */
1124 remove (remove_name);
1125 xfree (remove_name);
1127 #endif
1128 return rc;
1132 /****************
1133 * create a temporary iobuf, which can be used to collect stuff
1134 * in an iobuf and later be written by iobuf_write_temp() to another
1135 * iobuf.
1137 iobuf_t
1138 iobuf_temp ()
1140 iobuf_t a;
1142 a = iobuf_alloc (3, 8192);
1144 return a;
1147 iobuf_t
1148 iobuf_temp_with_content (const char *buffer, size_t length)
1150 iobuf_t a;
1152 a = iobuf_alloc (3, length);
1153 memcpy (a->d.buf, buffer, length);
1154 a->d.len = length;
1156 return a;
1159 void
1160 iobuf_enable_special_filenames (int yes)
1162 special_names_enabled = yes;
1166 /* See whether the filename has the form "-&nnnn", where n is a
1167 non-zero number. Returns this number or -1 if it is not the
1168 case. */
1169 static int
1170 check_special_filename (const char *fname)
1172 if (special_names_enabled && fname && *fname == '-' && fname[1] == '&')
1174 int i;
1176 fname += 2;
1177 for (i = 0; digitp (fname+i); i++)
1179 if (!fname[i])
1180 return atoi (fname);
1182 return -1;
1186 /* This fucntion returns true if FNAME indicates a PIPE (stdout or
1187 stderr) or a special file name if those are enabled. */
1189 iobuf_is_pipe_filename (const char *fname)
1191 if (!fname || (*fname=='-' && !fname[1]) )
1192 return 1;
1193 return check_special_filename (fname) != -1;
1196 /****************
1197 * Create a head iobuf for reading from a file
1198 * returns: NULL if an error occures and sets errno
1200 iobuf_t
1201 iobuf_open (const char *fname)
1203 iobuf_t a;
1204 fp_or_fd_t fp;
1205 file_filter_ctx_t *fcx;
1206 size_t len;
1207 int print_only = 0;
1208 int fd;
1210 if (!fname || (*fname == '-' && !fname[1]))
1212 fp = FILEP_OR_FD_FOR_STDIN;
1213 #ifdef USE_SETMODE
1214 setmode (my_fileno (fp), O_BINARY);
1215 #endif
1216 fname = "[stdin]";
1217 print_only = 1;
1219 else if ((fd = check_special_filename (fname)) != -1)
1220 return iobuf_fdopen (translate_file_handle (fd, 0), "rb");
1221 else if ((fp = my_fopen_ro (fname, "rb")) == INVALID_FP)
1222 return NULL;
1223 a = iobuf_alloc (1, 8192);
1224 fcx = xmalloc (sizeof *fcx + strlen (fname));
1225 fcx->fp = fp;
1226 fcx->print_only_name = print_only;
1227 strcpy (fcx->fname, fname);
1228 if (!print_only)
1229 a->real_fname = xstrdup (fname);
1230 a->filter = file_filter;
1231 a->filter_ov = fcx;
1232 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1233 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1234 if (DBG_IOBUF)
1235 log_debug ("iobuf-%d.%d: open `%s' fd=%d\n",
1236 a->no, a->subno, fname, (int) my_fileno (fcx->fp));
1238 return a;
1241 /****************
1242 * Create a head iobuf for reading from a file
1243 * returns: NULL if an error occures and sets errno
1245 iobuf_t
1246 iobuf_fdopen (int fd, const char *mode)
1248 iobuf_t a;
1249 fp_or_fd_t fp;
1250 file_filter_ctx_t *fcx;
1251 size_t len;
1253 #ifdef FILE_FILTER_USES_STDIO
1254 if (!(fp = fdopen (fd, mode)))
1255 return NULL;
1256 #else
1257 fp = (fp_or_fd_t) fd;
1258 #endif
1259 a = iobuf_alloc (strchr (mode, 'w') ? 2 : 1, 8192);
1260 fcx = xmalloc (sizeof *fcx + 20);
1261 fcx->fp = fp;
1262 fcx->print_only_name = 1;
1263 sprintf (fcx->fname, "[fd %d]", fd);
1264 a->filter = file_filter;
1265 a->filter_ov = fcx;
1266 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1267 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1268 if (DBG_IOBUF)
1269 log_debug ("iobuf-%d.%d: fdopen `%s'\n", a->no, a->subno, fcx->fname);
1270 iobuf_ioctl (a, 3, 1, NULL); /* disable fd caching */
1271 return a;
1275 iobuf_t
1276 iobuf_sockopen (int fd, const char *mode)
1278 iobuf_t a;
1279 #ifdef HAVE_W32_SYSTEM
1280 sock_filter_ctx_t *scx;
1281 size_t len;
1283 a = iobuf_alloc (strchr (mode, 'w') ? 2 : 1, 8192);
1284 scx = xmalloc (sizeof *scx + 25);
1285 scx->sock = fd;
1286 scx->print_only_name = 1;
1287 sprintf (scx->fname, "[sock %d]", fd);
1288 a->filter = sock_filter;
1289 a->filter_ov = scx;
1290 sock_filter (scx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1291 sock_filter (scx, IOBUFCTRL_INIT, NULL, NULL, &len);
1292 if (DBG_IOBUF)
1293 log_debug ("iobuf-%d.%d: sockopen `%s'\n", a->no, a->subno, scx->fname);
1294 iobuf_ioctl (a, 3, 1, NULL); /* disable fd caching */
1295 #else
1296 a = iobuf_fdopen (fd, mode);
1297 #endif
1298 return a;
1301 /****************
1302 * create an iobuf for writing to a file; the file will be created.
1304 iobuf_t
1305 iobuf_create (const char *fname)
1307 iobuf_t a;
1308 fp_or_fd_t fp;
1309 file_filter_ctx_t *fcx;
1310 size_t len;
1311 int print_only = 0;
1312 int fd;
1314 if (!fname || (*fname == '-' && !fname[1]))
1316 fp = FILEP_OR_FD_FOR_STDOUT;
1317 #ifdef USE_SETMODE
1318 setmode (my_fileno (fp), O_BINARY);
1319 #endif
1320 fname = "[stdout]";
1321 print_only = 1;
1323 else if ((fd = check_special_filename (fname)) != -1)
1324 return iobuf_fdopen (translate_file_handle (fd, 1), "wb");
1325 else if ((fp = my_fopen (fname, "wb")) == INVALID_FP)
1326 return NULL;
1327 a = iobuf_alloc (2, 8192);
1328 fcx = xmalloc (sizeof *fcx + strlen (fname));
1329 fcx->fp = fp;
1330 fcx->print_only_name = print_only;
1331 strcpy (fcx->fname, fname);
1332 if (!print_only)
1333 a->real_fname = xstrdup (fname);
1334 a->filter = file_filter;
1335 a->filter_ov = fcx;
1336 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1337 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1338 if (DBG_IOBUF)
1339 log_debug ("iobuf-%d.%d: create `%s'\n", a->no, a->subno, a->desc);
1341 return a;
1344 /****************
1345 * append to an iobuf; if the file does not exist, create it.
1346 * cannot be used for stdout.
1347 * Note: This is not used.
1349 #if 0 /* not used */
1350 iobuf_t
1351 iobuf_append (const char *fname)
1353 iobuf_t a;
1354 FILE *fp;
1355 file_filter_ctx_t *fcx;
1356 size_t len;
1358 if (!fname)
1359 return NULL;
1360 else if (!(fp = my_fopen (fname, "ab")))
1361 return NULL;
1362 a = iobuf_alloc (2, 8192);
1363 fcx = m_alloc (sizeof *fcx + strlen (fname));
1364 fcx->fp = fp;
1365 strcpy (fcx->fname, fname);
1366 a->real_fname = m_strdup (fname);
1367 a->filter = file_filter;
1368 a->filter_ov = fcx;
1369 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1370 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1371 if (DBG_IOBUF)
1372 log_debug ("iobuf-%d.%d: append `%s'\n", a->no, a->subno, a->desc);
1374 return a;
1376 #endif
1378 iobuf_t
1379 iobuf_openrw (const char *fname)
1381 iobuf_t a;
1382 fp_or_fd_t fp;
1383 file_filter_ctx_t *fcx;
1384 size_t len;
1386 if (!fname)
1387 return NULL;
1388 else if ((fp = my_fopen (fname, "r+b")) == INVALID_FP)
1389 return NULL;
1390 a = iobuf_alloc (2, 8192);
1391 fcx = xmalloc (sizeof *fcx + strlen (fname));
1392 fcx->fp = fp;
1393 strcpy (fcx->fname, fname);
1394 a->real_fname = xstrdup (fname);
1395 a->filter = file_filter;
1396 a->filter_ov = fcx;
1397 file_filter (fcx, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &len);
1398 file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
1399 if (DBG_IOBUF)
1400 log_debug ("iobuf-%d.%d: openrw `%s'\n", a->no, a->subno, a->desc);
1402 return a;
1407 iobuf_ioctl (iobuf_t a, int cmd, int intval, void *ptrval)
1409 if (cmd == 1)
1410 { /* keep system filepointer/descriptor open */
1411 if (DBG_IOBUF)
1412 log_debug ("iobuf-%d.%d: ioctl `%s' keep=%d\n",
1413 a ? a->no : -1, a ? a->subno : -1, a ? a->desc : "?",
1414 intval);
1415 for (; a; a = a->chain)
1416 if (!a->chain && a->filter == file_filter)
1418 file_filter_ctx_t *b = a->filter_ov;
1419 b->keep_open = intval;
1420 return 0;
1422 #ifdef HAVE_W32_SYSTEM
1423 else if (!a->chain && a->filter == sock_filter)
1425 sock_filter_ctx_t *b = a->filter_ov;
1426 b->keep_open = intval;
1427 return 0;
1429 #endif
1431 else if (cmd == 2)
1432 { /* invalidate cache */
1433 if (DBG_IOBUF)
1434 log_debug ("iobuf-*.*: ioctl `%s' invalidate\n",
1435 ptrval ? (char *) ptrval : "?");
1436 if (!a && !intval && ptrval)
1438 #ifndef FILE_FILTER_USES_STDIO
1439 fd_cache_invalidate (ptrval);
1440 #endif
1441 return 0;
1444 else if (cmd == 3)
1445 { /* disallow/allow caching */
1446 if (DBG_IOBUF)
1447 log_debug ("iobuf-%d.%d: ioctl `%s' no_cache=%d\n",
1448 a ? a->no : -1, a ? a->subno : -1, a ? a->desc : "?",
1449 intval);
1450 for (; a; a = a->chain)
1451 if (!a->chain && a->filter == file_filter)
1453 file_filter_ctx_t *b = a->filter_ov;
1454 b->no_cache = intval;
1455 return 0;
1457 #ifdef HAVE_W32_SYSTEM
1458 else if (!a->chain && a->filter == sock_filter)
1460 sock_filter_ctx_t *b = a->filter_ov;
1461 b->no_cache = intval;
1462 return 0;
1464 #endif
1467 return -1;
1471 /****************
1472 * Register an i/o filter.
1475 iobuf_push_filter (iobuf_t a,
1476 int (*f) (void *opaque, int control,
1477 iobuf_t chain, byte * buf, size_t * len),
1478 void *ov)
1480 return iobuf_push_filter2 (a, f, ov, 0);
1484 iobuf_push_filter2 (iobuf_t a,
1485 int (*f) (void *opaque, int control,
1486 iobuf_t chain, byte * buf, size_t * len),
1487 void *ov, int rel_ov)
1489 iobuf_t b;
1490 size_t dummy_len = 0;
1491 int rc = 0;
1493 if (a->directfp)
1494 BUG ();
1496 if (a->use == 2 && (rc = iobuf_flush (a)))
1497 return rc;
1498 /* make a copy of the current stream, so that
1499 * A is the new stream and B the original one.
1500 * The contents of the buffers are transferred to the
1501 * new stream.
1503 b = xmalloc (sizeof *b);
1504 memcpy (b, a, sizeof *b);
1505 /* fixme: it is stupid to keep a copy of the name at every level
1506 * but we need the name somewhere because the name known by file_filter
1507 * may have been released when we need the name of the file */
1508 b->real_fname = a->real_fname ? xstrdup (a->real_fname) : NULL;
1509 /* remove the filter stuff from the new stream */
1510 a->filter = NULL;
1511 a->filter_ov = NULL;
1512 a->filter_ov_owner = 0;
1513 a->filter_eof = 0;
1514 if (a->use == 3)
1515 a->use = 2; /* make a write stream from a temp stream */
1517 if (a->use == 2)
1518 { /* allocate a fresh buffer for the
1519 original stream */
1520 b->d.buf = xmalloc (a->d.size);
1521 b->d.len = 0;
1522 b->d.start = 0;
1524 else
1525 { /* allocate a fresh buffer for the new
1526 stream */
1527 a->d.buf = xmalloc (a->d.size);
1528 a->d.len = 0;
1529 a->d.start = 0;
1531 /* disable nlimit for the new stream */
1532 a->ntotal = b->ntotal + b->nbytes;
1533 a->nlimit = a->nbytes = 0;
1534 a->nofast &= ~1;
1535 /* make a link from the new stream to the original stream */
1536 a->chain = b;
1537 a->opaque = b->opaque;
1539 /* setup the function on the new stream */
1540 a->filter = f;
1541 a->filter_ov = ov;
1542 a->filter_ov_owner = rel_ov;
1544 a->subno = b->subno + 1;
1545 f (ov, IOBUFCTRL_DESC, NULL, (byte *) & a->desc, &dummy_len);
1547 if (DBG_IOBUF)
1549 log_debug ("iobuf-%d.%d: push `%s'\n", a->no, a->subno, a->desc);
1550 print_chain (a);
1553 /* now we can initialize the new function if we have one */
1554 if (a->filter && (rc = a->filter (a->filter_ov, IOBUFCTRL_INIT, a->chain,
1555 NULL, &dummy_len)))
1556 log_error ("IOBUFCTRL_INIT failed: %s\n", gpg_strerror (rc));
1557 return rc;
1560 /****************
1561 * Remove an i/o filter.
1563 static int
1564 pop_filter (iobuf_t a, int (*f) (void *opaque, int control,
1565 iobuf_t chain, byte * buf, size_t * len),
1566 void *ov)
1568 iobuf_t b;
1569 size_t dummy_len = 0;
1570 int rc = 0;
1572 if (a->directfp)
1573 BUG ();
1575 if (DBG_IOBUF)
1576 log_debug ("iobuf-%d.%d: pop `%s'\n", a->no, a->subno, a->desc);
1577 if (!a->filter)
1578 { /* this is simple */
1579 b = a->chain;
1580 assert (b);
1581 xfree (a->d.buf);
1582 xfree (a->real_fname);
1583 memcpy (a, b, sizeof *a);
1584 xfree (b);
1585 return 0;
1587 for (b = a; b; b = b->chain)
1588 if (b->filter == f && (!ov || b->filter_ov == ov))
1589 break;
1590 if (!b)
1591 log_bug ("pop_filter(): filter function not found\n");
1593 /* flush this stream if it is an output stream */
1594 if (a->use == 2 && (rc = iobuf_flush (b)))
1596 log_error ("iobuf_flush failed in pop_filter: %s\n", gpg_strerror (rc));
1597 return rc;
1599 /* and tell the filter to free it self */
1600 if (b->filter && (rc = b->filter (b->filter_ov, IOBUFCTRL_FREE, b->chain,
1601 NULL, &dummy_len)))
1603 log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc));
1604 return rc;
1606 if (b->filter_ov && b->filter_ov_owner)
1608 xfree (b->filter_ov);
1609 b->filter_ov = NULL;
1613 /* and see how to remove it */
1614 if (a == b && !b->chain)
1615 log_bug ("can't remove the last filter from the chain\n");
1616 else if (a == b)
1617 { /* remove the first iobuf from the chain */
1618 /* everything from b is copied to a. This is save because
1619 * a flush has been done on the to be removed entry
1621 b = a->chain;
1622 xfree (a->d.buf);
1623 xfree (a->real_fname);
1624 memcpy (a, b, sizeof *a);
1625 xfree (b);
1626 if (DBG_IOBUF)
1627 log_debug ("iobuf-%d.%d: popped filter\n", a->no, a->subno);
1629 else if (!b->chain)
1630 { /* remove the last iobuf from the chain */
1631 log_bug ("Ohh jeee, trying to remove a head filter\n");
1633 else
1634 { /* remove an intermediate iobuf from the chain */
1635 log_bug ("Ohh jeee, trying to remove an intermediate filter\n");
1638 return rc;
1642 /****************
1643 * read underflow: read more bytes into the buffer and return
1644 * the first byte or -1 on EOF.
1646 static int
1647 underflow (iobuf_t a)
1649 size_t len;
1650 int rc;
1652 assert (a->d.start == a->d.len);
1653 if (a->use == 3)
1654 return -1; /* EOF because a temp buffer can't do an underflow */
1656 if (a->filter_eof)
1658 if (a->chain)
1660 iobuf_t b = a->chain;
1661 if (DBG_IOBUF)
1662 log_debug ("iobuf-%d.%d: pop `%s' in underflow\n",
1663 a->no, a->subno, a->desc);
1664 xfree (a->d.buf);
1665 xfree (a->real_fname);
1666 memcpy (a, b, sizeof *a);
1667 xfree (b);
1668 print_chain (a);
1670 else
1671 a->filter_eof = 0; /* for the top level filter */
1672 if (DBG_IOBUF)
1673 log_debug ("iobuf-%d.%d: underflow: eof (due to filter eof)\n",
1674 a->no, a->subno);
1675 return -1; /* return one(!) EOF */
1677 if (a->error)
1679 if (DBG_IOBUF)
1680 log_debug ("iobuf-%d.%d: error\n", a->no, a->subno);
1681 return -1;
1684 if (a->directfp)
1686 FILE *fp = a->directfp;
1688 len = fread (a->d.buf, 1, a->d.size, fp);
1689 if (len < a->d.size)
1691 if (ferror (fp))
1692 a->error = gpg_error_from_syserror ();
1694 a->d.len = len;
1695 a->d.start = 0;
1696 return len ? a->d.buf[a->d.start++] : -1;
1700 if (a->filter)
1702 len = a->d.size;
1703 if (DBG_IOBUF)
1704 log_debug ("iobuf-%d.%d: underflow: req=%lu\n",
1705 a->no, a->subno, (ulong) len);
1706 rc = a->filter (a->filter_ov, IOBUFCTRL_UNDERFLOW, a->chain,
1707 a->d.buf, &len);
1708 if (DBG_IOBUF)
1710 log_debug ("iobuf-%d.%d: underflow: got=%lu rc=%d\n",
1711 a->no, a->subno, (ulong) len, rc);
1712 /* if( a->no == 1 ) */
1713 /* log_hexdump (" data:", a->d.buf, len); */
1715 if (a->use == 1 && rc == -1)
1716 { /* EOF: we can remove the filter */
1717 size_t dummy_len = 0;
1719 /* and tell the filter to free itself */
1720 if ((rc = a->filter (a->filter_ov, IOBUFCTRL_FREE, a->chain,
1721 NULL, &dummy_len)))
1722 log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc));
1723 if (a->filter_ov && a->filter_ov_owner)
1725 xfree (a->filter_ov);
1726 a->filter_ov = NULL;
1728 a->filter = NULL;
1729 a->desc = NULL;
1730 a->filter_ov = NULL;
1731 a->filter_eof = 1;
1732 if (!len && a->chain)
1734 iobuf_t b = a->chain;
1735 if (DBG_IOBUF)
1736 log_debug ("iobuf-%d.%d: pop `%s' in underflow (!len)\n",
1737 a->no, a->subno, a->desc);
1738 xfree (a->d.buf);
1739 xfree (a->real_fname);
1740 memcpy (a, b, sizeof *a);
1741 xfree (b);
1742 print_chain (a);
1745 else if (rc)
1746 a->error = rc;
1748 if (!len)
1750 if (DBG_IOBUF)
1751 log_debug ("iobuf-%d.%d: underflow: eof\n", a->no, a->subno);
1752 return -1;
1754 a->d.len = len;
1755 a->d.start = 0;
1756 return a->d.buf[a->d.start++];
1758 else
1760 if (DBG_IOBUF)
1761 log_debug ("iobuf-%d.%d: underflow: eof (no filter)\n",
1762 a->no, a->subno);
1763 return -1; /* no filter; return EOF */
1769 iobuf_flush (iobuf_t a)
1771 size_t len;
1772 int rc;
1774 if (a->directfp)
1775 return 0;
1777 if (a->use == 3)
1778 { /* increase the temp buffer */
1779 unsigned char *newbuf;
1780 size_t newsize = a->d.size + 8192;
1782 if (DBG_IOBUF)
1783 log_debug ("increasing temp iobuf from %lu to %lu\n",
1784 (ulong) a->d.size, (ulong) newsize);
1785 newbuf = xmalloc (newsize);
1786 memcpy (newbuf, a->d.buf, a->d.len);
1787 xfree (a->d.buf);
1788 a->d.buf = newbuf;
1789 a->d.size = newsize;
1790 return 0;
1792 else if (a->use != 2)
1793 log_bug ("flush on non-output iobuf\n");
1794 else if (!a->filter)
1795 log_bug ("iobuf_flush: no filter\n");
1796 len = a->d.len;
1797 rc = a->filter (a->filter_ov, IOBUFCTRL_FLUSH, a->chain, a->d.buf, &len);
1798 if (!rc && len != a->d.len)
1800 log_info ("iobuf_flush did not write all!\n");
1801 rc = GPG_ERR_INTERNAL;
1803 else if (rc)
1804 a->error = rc;
1805 a->d.len = 0;
1807 return rc;
1811 /****************
1812 * Read a byte from the iobuf; returns -1 on EOF
1815 iobuf_readbyte (iobuf_t a)
1817 int c;
1819 if (a->nlimit && a->nbytes >= a->nlimit)
1820 return -1; /* forced EOF */
1822 if (a->d.start < a->d.len)
1824 c = a->d.buf[a->d.start++];
1826 else if ((c = underflow (a)) == -1)
1827 return -1; /* EOF */
1829 a->nbytes++;
1830 return c;
1835 iobuf_read (iobuf_t a, void *buffer, unsigned int buflen)
1837 unsigned char *buf = (unsigned char *)buffer;
1838 int c, n;
1840 if (a->nlimit)
1842 /* Handle special cases. */
1843 for (n = 0; n < buflen; n++)
1845 if ((c = iobuf_readbyte (a)) == -1)
1847 if (!n)
1848 return -1; /* eof */
1849 break;
1851 else if (buf)
1852 *buf = c;
1853 if (buf)
1854 buf++;
1856 return n;
1859 n = 0;
1862 if (n < buflen && a->d.start < a->d.len)
1864 unsigned size = a->d.len - a->d.start;
1865 if (size > buflen - n)
1866 size = buflen - n;
1867 if (buf)
1868 memcpy (buf, a->d.buf + a->d.start, size);
1869 n += size;
1870 a->d.start += size;
1871 if (buf)
1872 buf += size;
1874 if (n < buflen)
1876 if ((c = underflow (a)) == -1)
1878 a->nbytes += n;
1879 return n ? n : -1 /*EOF*/;
1881 if (buf)
1882 *buf++ = c;
1883 n++;
1886 while (n < buflen);
1887 a->nbytes += n;
1888 return n;
1893 /****************
1894 * Have a look at the iobuf.
1895 * NOTE: This only works in special cases.
1898 iobuf_peek (iobuf_t a, byte * buf, unsigned buflen)
1900 int n = 0;
1902 if (a->filter_eof)
1903 return -1;
1905 if (!(a->d.start < a->d.len))
1907 if (underflow (a) == -1)
1908 return -1;
1909 /* And unget this character. */
1910 assert (a->d.start == 1);
1911 a->d.start = 0;
1914 for (n = 0; n < buflen && (a->d.start + n) < a->d.len; n++, buf++)
1915 *buf = a->d.buf[n];
1916 return n;
1923 iobuf_writebyte (iobuf_t a, unsigned int c)
1925 int rc;
1927 if (a->directfp)
1928 BUG ();
1930 if (a->d.len == a->d.size)
1931 if ((rc=iobuf_flush (a)))
1932 return rc;
1934 assert (a->d.len < a->d.size);
1935 a->d.buf[a->d.len++] = c;
1936 return 0;
1941 iobuf_write (iobuf_t a, const void *buffer, unsigned int buflen)
1943 const unsigned char *buf = (const unsigned char *)buffer;
1944 int rc;
1946 if (a->directfp)
1947 BUG ();
1951 if (buflen && a->d.len < a->d.size)
1953 unsigned size = a->d.size - a->d.len;
1954 if (size > buflen)
1955 size = buflen;
1956 memcpy (a->d.buf + a->d.len, buf, size);
1957 buflen -= size;
1958 buf += size;
1959 a->d.len += size;
1961 if (buflen)
1963 rc = iobuf_flush (a);
1964 if (rc)
1965 return rc;
1968 while (buflen);
1969 return 0;
1974 iobuf_writestr (iobuf_t a, const char *buf)
1976 int rc;
1978 for (; *buf; buf++)
1979 if ((rc=iobuf_writebyte (a, *buf)))
1980 return rc;
1981 return 0;
1986 /****************
1987 * copy the contents of TEMP to A.
1990 iobuf_write_temp (iobuf_t a, iobuf_t temp)
1992 while (temp->chain)
1993 pop_filter (temp, temp->filter, NULL);
1994 return iobuf_write (a, temp->d.buf, temp->d.len);
1997 /****************
1998 * copy the contents of the temp io stream to BUFFER.
2000 size_t
2001 iobuf_temp_to_buffer (iobuf_t a, byte * buffer, size_t buflen)
2003 size_t n = a->d.len;
2005 if (n > buflen)
2006 n = buflen;
2007 memcpy (buffer, a->d.buf, n);
2008 return n;
2012 /****************
2013 * Call this function to terminate processing of the temp stream
2014 * without closing it. This removes all filters from the stream
2015 * makes sure that iobuf_get_temp_{buffer,length}() returns correct
2016 * values.
2018 void
2019 iobuf_flush_temp (iobuf_t temp)
2021 while (temp->chain)
2022 pop_filter (temp, temp->filter, NULL);
2026 /****************
2027 * Set a limit on how many bytes may be read from the input stream A.
2028 * Setting the limit to 0 disables this feature.
2030 void
2031 iobuf_set_limit (iobuf_t a, off_t nlimit)
2033 if (nlimit)
2034 a->nofast |= 1;
2035 else
2036 a->nofast &= ~1;
2037 a->nlimit = nlimit;
2038 a->ntotal += a->nbytes;
2039 a->nbytes = 0;
2044 /* Return the length of an open file A. IF OVERFLOW is not NULL it
2045 will be set to true if the file is larger than what off_t can cope
2046 with. The function return 0 on error or on overflow condition. */
2047 off_t
2048 iobuf_get_filelength (iobuf_t a, int *overflow)
2050 struct stat st;
2052 if (overflow)
2053 *overflow = 0;
2055 if ( a->directfp )
2057 FILE *fp = a->directfp;
2059 if ( !fstat(fileno(fp), &st) )
2060 return st.st_size;
2061 log_error("fstat() failed: %s\n", strerror(errno) );
2062 return 0;
2065 /* Hmmm: file_filter may have already been removed */
2066 for ( ; a; a = a->chain )
2067 if ( !a->chain && a->filter == file_filter )
2069 file_filter_ctx_t *b = a->filter_ov;
2070 fp_or_fd_t fp = b->fp;
2072 #if defined(HAVE_W32_SYSTEM) && !defined(FILE_FILTER_USES_STDIO)
2073 ulong size;
2074 static int (* __stdcall get_file_size_ex) (void *handle,
2075 LARGE_INTEGER *r_size);
2076 static int get_file_size_ex_initialized;
2078 if (!get_file_size_ex_initialized)
2080 void *handle;
2082 handle = dlopen ("kernel32.dll", RTLD_LAZY);
2083 if (handle)
2085 get_file_size_ex = dlsym (handle, "GetFileSizeEx");
2086 if (!get_file_size_ex)
2087 dlclose (handle);
2089 get_file_size_ex_initialized = 1;
2092 if (get_file_size_ex)
2094 /* This is a newer system with GetFileSizeEx; we use this
2095 then because it seem that GetFileSize won't return a
2096 proper error in case a file is larger than 4GB. */
2097 LARGE_INTEGER exsize;
2099 if (get_file_size_ex (fp, &exsize))
2101 if (!exsize.u.HighPart)
2102 return exsize.u.LowPart;
2103 if (overflow)
2104 *overflow = 1;
2105 return 0;
2108 else
2110 if ((size=GetFileSize (fp, NULL)) != 0xffffffff)
2111 return size;
2113 log_error ("GetFileSize for handle %p failed: %s\n",
2114 fp, w32_strerror (0));
2115 #else
2116 if ( !fstat(my_fileno(fp), &st) )
2117 return st.st_size;
2118 log_error("fstat() failed: %s\n", strerror(errno) );
2119 #endif
2120 break/*the for loop*/;
2123 return 0;
2127 /* Return the file descriptor of the underlying file or -1 if it is
2128 not available. */
2129 int
2130 iobuf_get_fd (iobuf_t a)
2132 if (a->directfp)
2133 return fileno ( (FILE*)a->directfp );
2135 for ( ; a; a = a->chain )
2136 if (!a->chain && a->filter == file_filter)
2138 file_filter_ctx_t *b = a->filter_ov;
2139 fp_or_fd_t fp = b->fp;
2141 return my_fileno (fp);
2144 return -1;
2149 /****************
2150 * Tell the file position, where the next read will take place
2152 off_t
2153 iobuf_tell (iobuf_t a)
2155 return a->ntotal + a->nbytes;
2159 #if !defined(HAVE_FSEEKO) && !defined(fseeko)
2161 #ifdef HAVE_LIMITS_H
2162 # include <limits.h>
2163 #endif
2164 #ifndef LONG_MAX
2165 # define LONG_MAX ((long) ((unsigned long) -1 >> 1))
2166 #endif
2167 #ifndef LONG_MIN
2168 # define LONG_MIN (-1 - LONG_MAX)
2169 #endif
2171 /****************
2172 * A substitute for fseeko, for hosts that don't have it.
2174 static int
2175 fseeko (FILE * stream, off_t newpos, int whence)
2177 while (newpos != (long) newpos)
2179 long pos = newpos < 0 ? LONG_MIN : LONG_MAX;
2180 if (fseek (stream, pos, whence) != 0)
2181 return -1;
2182 newpos -= pos;
2183 whence = SEEK_CUR;
2185 return fseek (stream, (long) newpos, whence);
2187 #endif
2189 /****************
2190 * This is a very limited implementation. It simply discards all internal
2191 * buffering and removes all filters but the first one.
2194 iobuf_seek (iobuf_t a, off_t newpos)
2196 file_filter_ctx_t *b = NULL;
2198 if (a->directfp)
2200 FILE *fp = a->directfp;
2201 if (fseeko (fp, newpos, SEEK_SET))
2203 log_error ("can't seek: %s\n", strerror (errno));
2204 return -1;
2206 clearerr (fp);
2208 else
2210 for (; a; a = a->chain)
2212 if (!a->chain && a->filter == file_filter)
2214 b = a->filter_ov;
2215 break;
2218 if (!a)
2219 return -1;
2220 #ifdef FILE_FILTER_USES_STDIO
2221 if (fseeko (b->fp, newpos, SEEK_SET))
2223 log_error ("can't fseek: %s\n", strerror (errno));
2224 return -1;
2226 #else
2227 #ifdef HAVE_W32_SYSTEM
2228 if (SetFilePointer (b->fp, newpos, NULL, FILE_BEGIN) == 0xffffffff)
2230 log_error ("SetFilePointer failed on handle %p: ec=%d\n",
2231 b->fp, (int) GetLastError ());
2232 return -1;
2234 #else
2235 if (lseek (b->fp, newpos, SEEK_SET) == (off_t) - 1)
2237 log_error ("can't lseek: %s\n", strerror (errno));
2238 return -1;
2240 #endif
2241 #endif
2243 a->d.len = 0; /* discard buffer */
2244 a->d.start = 0;
2245 a->nbytes = 0;
2246 a->nlimit = 0;
2247 a->nofast &= ~1;
2248 a->ntotal = newpos;
2249 a->error = 0;
2250 /* remove filters, but the last */
2251 if (a->chain)
2252 log_debug ("pop_filter called in iobuf_seek - please report\n");
2253 while (a->chain)
2254 pop_filter (a, a->filter, NULL);
2256 return 0;
2264 /****************
2265 * Retrieve the real filename
2267 const char *
2268 iobuf_get_real_fname (iobuf_t a)
2270 if (a->real_fname)
2271 return a->real_fname;
2273 /* the old solution */
2274 for (; a; a = a->chain)
2275 if (!a->chain && a->filter == file_filter)
2277 file_filter_ctx_t *b = a->filter_ov;
2278 return b->print_only_name ? NULL : b->fname;
2281 return NULL;
2285 /****************
2286 * Retrieve the filename
2288 const char *
2289 iobuf_get_fname (iobuf_t a)
2291 for (; a; a = a->chain)
2292 if (!a->chain && a->filter == file_filter)
2294 file_filter_ctx_t *b = a->filter_ov;
2295 return b->fname;
2298 return NULL;
2302 /****************
2303 * enable partial block mode as described in the OpenPGP draft.
2304 * LEN is the first length byte on read, but ignored on writes.
2306 void
2307 iobuf_set_partial_block_mode (iobuf_t a, size_t len)
2309 block_filter_ctx_t *ctx = xcalloc (1, sizeof *ctx);
2311 assert (a->use == 1 || a->use == 2);
2312 ctx->use = a->use;
2313 if (!len)
2315 if (a->use == 1)
2316 log_debug ("pop_filter called in set_partial_block_mode"
2317 " - please report\n");
2318 pop_filter (a, block_filter, NULL);
2320 else
2322 ctx->partial = 1;
2323 ctx->size = 0;
2324 ctx->first_c = len;
2325 iobuf_push_filter (a, block_filter, ctx);
2331 /****************
2332 * Same as fgets() but if the buffer is too short a larger one will
2333 * be allocated up to some limit *max_length.
2334 * A line is considered a byte stream ending in a LF.
2335 * Returns the length of the line. EOF is indicated by a line of
2336 * length zero. The last LF may be missing due to an EOF.
2337 * is max_length is zero on return, the line has been truncated.
2339 * Note: The buffer is allocated with enough space to append a CR,LF,EOL
2341 unsigned int
2342 iobuf_read_line (iobuf_t a, byte ** addr_of_buffer,
2343 unsigned *length_of_buffer, unsigned *max_length)
2345 int c;
2346 char *buffer = (char *)*addr_of_buffer;
2347 unsigned length = *length_of_buffer;
2348 unsigned nbytes = 0;
2349 unsigned maxlen = *max_length;
2350 char *p;
2352 if (!buffer)
2353 { /* must allocate a new buffer */
2354 length = 256;
2355 buffer = xmalloc (length);
2356 *addr_of_buffer = (unsigned char *)buffer;
2357 *length_of_buffer = length;
2360 length -= 3; /* reserve 3 bytes (cr,lf,eol) */
2361 p = buffer;
2362 while ((c = iobuf_get (a)) != -1)
2364 if (nbytes == length)
2365 { /* increase the buffer */
2366 if (length > maxlen)
2367 { /* this is out limit */
2368 /* skip the rest of the line */
2369 while (c != '\n' && (c = iobuf_get (a)) != -1)
2371 *p++ = '\n'; /* always append a LF (we have reserved space) */
2372 nbytes++;
2373 *max_length = 0; /* indicate truncation */
2374 break;
2376 length += 3; /* correct for the reserved byte */
2377 length += length < 1024 ? 256 : 1024;
2378 buffer = xrealloc (buffer, length);
2379 *addr_of_buffer = (unsigned char *)buffer;
2380 *length_of_buffer = length;
2381 length -= 3; /* and reserve again */
2382 p = buffer + nbytes;
2384 *p++ = c;
2385 nbytes++;
2386 if (c == '\n')
2387 break;
2389 *p = 0; /* make sure the line is a string */
2391 return nbytes;
2394 static int
2395 translate_file_handle (int fd, int for_write)
2397 #ifdef HAVE_W32_SYSTEM
2398 # ifdef FILE_FILTER_USES_STDIO
2399 fd = translate_sys2libc_fd (fd, for_write);
2400 # else
2402 int x;
2404 if (fd == 0)
2405 x = (int) GetStdHandle (STD_INPUT_HANDLE);
2406 else if (fd == 1)
2407 x = (int) GetStdHandle (STD_OUTPUT_HANDLE);
2408 else if (fd == 2)
2409 x = (int) GetStdHandle (STD_ERROR_HANDLE);
2410 else
2411 x = fd;
2413 if (x == -1)
2414 log_debug ("GetStdHandle(%d) failed: ec=%d\n",
2415 fd, (int) GetLastError ());
2417 fd = x;
2419 # endif
2420 #endif
2421 return fd;
2425 void
2426 iobuf_skip_rest (iobuf_t a, unsigned long n, int partial)
2428 if ( partial )
2430 for (;;)
2432 if (a->nofast || a->d.start >= a->d.len)
2434 if (iobuf_readbyte (a) == -1)
2436 break;
2439 else
2441 unsigned long count = a->d.len - a->d.start;
2442 a->nbytes += count;
2443 a->d.start = a->d.len;
2447 else
2449 unsigned long remaining = n;
2450 while (remaining > 0)
2452 if (a->nofast || a->d.start >= a->d.len)
2454 if (iobuf_readbyte (a) == -1)
2456 break;
2458 --remaining;
2460 else
2462 unsigned long count = a->d.len - a->d.start;
2463 if (count > remaining)
2465 count = remaining;
2467 a->nbytes += count;
2468 a->d.start += count;
2469 remaining -= count;