]> the.earth.li Git - onak.git/blob - key-store.c
0.6.3 release
[onak.git] / key-store.c
1 /*
2  * key-store.c - High level routines to load + save OpenPGP packets/keys
3  *
4  * This program is free software: you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License as published by the Free
6  * Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
11  * more details.
12  *
13  * You should have received a copy of the GNU General Public License along with
14  * this program.  If not, see <https://www.gnu.org/licenses/>.
15  */
16
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <unistd.h>
20
21 #include "build-config.h"
22
23 #include "armor.h"
24 #include "charfuncs.h"
25 #include "key-store.h"
26 #include "keystructs.h"
27 #include "onak.h"
28 #include "parsekey.h"
29
30 /**
31  *      onak_read_openpgp_file - Reads a set of OpenPGP packets from a file
32  *      @file: The file to open and read
33  *      @packets: The returned packet list
34  *
35  *      This function opens the supplied file and tries to parse it as a set
36  *      of OpenPGP packets. It will attempt to autodetect if the file is ASCII
37  *      armored, or binary packets, and adapt accordingly. The packets read are
38  *      returned in the packets parameter. It is the callers responsbility to
39  *      free the packet memory when it is no longe required, e.g. using
40  *      free_packet_list.
41  *
42  *      Returns a status code indicating any error.
43  */
44 onak_status_t onak_read_openpgp_file(const char *file,
45                 struct openpgp_packet_list **packets)
46 {
47         onak_status_t res;
48         int fd, ret;
49         char c;
50
51         fd = open(file, O_RDONLY);
52         if (fd < 0) {
53                 return (errno == ENOENT) ? ONAK_E_NOT_FOUND : ONAK_E_IO_ERROR;
54         }
55
56         /* Peek at the first byte in the file */
57         ret = read(fd, &c, 1);
58         if (ret != 1) {
59                 return ONAK_E_IO_ERROR;
60         }
61         lseek(fd, 0, SEEK_SET);
62
63         /*
64          * A binary OpenPGP packet will have the top bit set on its first byte,
65          * so we use that to determine if we should try to process the stream
66          * as binary or ASCII armored data.
67          */
68         if (c & 0x80) {
69                 res = read_openpgp_stream(file_fetchchar, &fd,
70                          packets, 0);
71         } else {
72                 res = dearmor_openpgp_stream(file_fetchchar, &fd, packets);
73         }
74
75         return res;
76 }