* parse-packet.c (dump_sig_subpkt, parse_signature), build-packet.c
[gnupg.git] / kbx / keybox-file.c
blobfc932147828e4996e3c10028a783f409b99b908b
1 /* keybox-file.c - file oeprations
2 * Copyright (C) 2001, 2003 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
21 #include <config.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <errno.h>
27 #include "keybox-defs.h"
29 /* Read a block at the current postion and return it in r_blob.
30 r_blob may be NULL to simply skip the current block */
31 int
32 _keybox_read_blob (KEYBOXBLOB *r_blob, FILE *fp)
34 char *image;
35 size_t imagelen = 0;
36 int c1, c2, c3, c4, type;
37 int rc;
38 off_t off;
40 again:
41 *r_blob = NULL;
42 off = ftello (fp);
43 if (off == (off_t)-1)
44 return gpg_error (gpg_err_code_from_errno (errno));
46 if ((c1 = getc (fp)) == EOF
47 || (c2 = getc (fp)) == EOF
48 || (c3 = getc (fp)) == EOF
49 || (c4 = getc (fp)) == EOF
50 || (type = getc (fp)) == EOF)
52 if ( c1 == EOF && !ferror (fp) )
53 return -1; /* eof */
54 return gpg_error (gpg_err_code_from_errno (errno));
57 imagelen = (c1 << 24) | (c2 << 16) | (c3 << 8 ) | c4;
58 if (imagelen > 500000) /* sanity check */
59 return gpg_error (GPG_ERR_TOO_LARGE);
61 if (imagelen < 5)
62 return gpg_error (GPG_ERR_TOO_SHORT);
64 if (!type)
66 /* special treatment for empty blobs. */
67 if (fseek (fp, imagelen-5, SEEK_CUR))
68 return gpg_error (gpg_err_code_from_errno (errno));
69 goto again;
72 image = xtrymalloc (imagelen);
73 if (!image)
74 return gpg_error (gpg_err_code_from_errno (errno));
76 image[0] = c1; image[1] = c2; image[2] = c3; image[3] = c4; image[4] = type;
77 if (fread (image+5, imagelen-5, 1, fp) != 1)
79 gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno));
80 xfree (image);
81 return tmperr;
84 rc = r_blob? _keybox_new_blob (r_blob, image, imagelen, off) : 0;
85 if (rc || !r_blob)
86 xfree (image);
87 return rc;
91 /* Write the block to the current file position */
92 int
93 _keybox_write_blob (KEYBOXBLOB blob, FILE *fp)
95 const char *image;
96 size_t length;
98 image = _keybox_get_blob_image (blob, &length);
99 if (fwrite (image, length, 1, fp) != 1)
100 return gpg_error (gpg_err_code_from_errno (errno));
101 return 0;