chiark / gitweb /
pubkeys: Move path and lno into a struct cloc
[secnet.git] / pubkeys.fl.pl
1 #!/usr/bin/perl -w
2 # -*- C -*-
3 #
4 # secnet - pubkeys.fl.pl
5 #
6 # This file is part of secnet.
7 # See README for full list of copyright holders.
8 #
9 # secnet is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13
14 # secnet is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 # General Public License for more details.
18
19 # You should have received a copy of the GNU General Public License
20 # version 3 along with secnet; if not, see
21 # https://www.gnu.org/licenses/gpl.html.
22
23 # We process __DATA__ of this file first through the perl code,
24 # and then through flex.  We do it like this because directives
25 # with positional arguments are otherwise rather tedious to specify
26 # in flex.  Of course we could have used bison too but this seems
27 # better overall.
28
29 use strict;
30
31 our $do = '';
32 our $co = '';
33 our $kw;
34 our $kwid;
35 our @next_kw;
36 our $in_s;
37 our $data_off;
38
39 our %subst = (GRPIDSZ => 4, SERIALSZ => 4);
40
41 our $last_lno = -1;
42 sub lineno (;$$) {
43     my ($always, $delta) = @_;
44     my $o = '';
45     $delta //= 0;
46     if ($always || $. != $last_lno+1) {
47         $o .= sprintf "#line %d \"%s\"\n", $delta+$data_off+$., $0;
48     }
49     $last_lno = $.;
50     $o;
51 }
52
53 while (<DATA>) {
54         last if m/^\%\%\s*$/;
55         if (m/^!SUBSTCHECKS\s*$/) {
56                 foreach (keys %subst) {
57                         $do .= <<END
58 #if $_ != $subst{$_}
59 # error $_ value disagrees between pubkeys.fl.pl and C headers
60 #endif
61 END
62                 }
63                 next;
64         }
65         $do .= lineno();
66         $do .= $_;
67 }
68
69 sub inst ($) {
70         $do .= "%x $_[0]\n";
71         "<$_[0]>";
72 }
73
74 while (<DATA>) {
75     s#\{!2(\w+)\}# '{'.(2 * ($subst{$1}//die "$1 ?")).'}' #ge;
76     if (m/^!(KEYWORD|KWALIAS) ([-0-9a-z]+)(\s*\{.*\})?$/) {
77         my $kwt=$2;
78         if ($1 eq 'KEYWORD') {
79             die if $kw;
80             $kw = $kwt;
81         } else {
82             die if @next_kw;
83             die unless $kw;
84         }
85         my $xact = $3 // '';
86         $kwid = $kw; $kwid =~ y/-/_/;
87         $in_s = "HK_${kwid}";
88         $co .= "{L}$kwt { BEGIN($in_s); $xact }\n";
89         next;
90     }
91     if (m/^!ARG (\w+) (\S.*\S) \{\s*$/) {
92         die unless $kw;
93         die if @next_kw;
94         $co .= inst("$in_s")."{S} { BEGIN(D_${kwid}_$1); }\n";
95         $co .= inst("D_${kwid}_$1")."$2 {\n";
96         $in_s = "HA_${kwid}_$1";
97         $co .= "\tBEGIN($in_s);\n";
98         @next_kw = ($kw);
99         $co .= lineno(1,1);
100         next;
101     }
102     if (m/^!\}\s*$/) {
103         die unless @next_kw;
104         $co .= lineno(1,0);
105         $co .= "}\n";
106         $kw = shift @next_kw;
107         next;
108     }
109     if (m/^!FINAL \{\s*$/) {
110         die unless $kw;
111         die if @next_kw;
112         $co .= inst("FIN_$kwid")."\\n { BEGIN(0); c->loc.line++; }\n";
113         $co .= inst("$in_s")."{L}/\\n {\n";
114         $co .= "\tBEGIN(FIN_$kwid);\n";
115         $co .= lineno(1,1);
116         @next_kw = (undef);
117         next;
118     }
119     if (m/^!/) {
120         die;
121     }
122     $co .= $_;
123     if (m/^\%\%\s*$/) {
124         $co .= lineno(1,1);
125     }
126 }
127
128 print $do, "%%\n", $co or die $!;
129
130 BEGIN { $data_off = __LINE__ + 1; }
131 __DATA__
132
133 L       [ \t]*
134 S       [ \t]+
135 BASE91S []-~!#-&(-[]+
136 %x SKIPNL
137
138 %option yylineno
139 %option noyywrap
140 %option batch
141 %option 8bit
142 %option nodefault
143 %option never-interactive
144
145 %option prefix="pkyy"
146
147 %option warn
148
149 %{
150
151 #include "secnet.h"
152 #include "pubkeys.h"
153 #include "util.h"
154 #include "unaligned.h"
155 #include "base91s/base91.h"
156
157 !SUBSTCHECKS
158
159 struct pubkeyset_context {
160     /* filled in during setup: */
161     struct cloc loc; /* line is runtime */
162     struct log_if *log;
163     struct buffer_if *data_buf;
164     struct peer_keyset *building;
165     /* runtime: */
166     bool_t had_serial;
167     bool_t fallback_skip;
168     const struct sigscheme_info *scheme;
169     uint8_t grpid[GRPIDSZ];
170     serialt serial;
171 };
172
173 static struct pubkeyset_context c[1];
174
175 #define LI (c->log)
176 #define HEX2BIN(v,l) ({                                                 \
177         int32_t outlen;                                                 \
178         bool_t ok=hex_decode((v), ((l)), &outlen, yytext, False);       \
179         assert(ok);                                                     \
180         assert(outlen==((l)));                                          \
181     })
182 #define HEX2BIN_ARRAY(v) HEX2BIN((v),sizeof((v)))
183 #define DOSKIPQ ({                                      \
184         BEGIN(SKIPNL);                                  \
185         break;                                          \
186     })
187 #define DOSKIP(m) ({                                    \
188         slilog(LI,M_INFO,"%s:%d: " m, c->loc.file, c->loc.line);        \
189         DOSKIPQ;                                        \
190     })
191 #define FAIL(m) do{                                     \
192         slilog(LI,M_ERR,"%s:%d: " m, c->loc.file, c->loc.line); \
193         return -1;                                      \
194     }while(0)
195
196 %}
197
198 %%
199
200 !KEYWORD pkg  { c->fallback_skip=0; }
201 !KWALIAS pkgf { c->fallback_skip=!!c->building->nkeys; }
202 !ARG id [0-9a-f]{!2GRPIDSZ} {
203     HEX2BIN_ARRAY(c->grpid);
204 !}
205 !FINAL {
206 !}
207 !KEYWORD pub
208 !ARG algo [-0-9a-z]+ {
209     if (c->fallback_skip) DOSKIP("fallback not needed");
210     c->scheme = sigscheme_lookup(yytext);
211     if (!c->scheme) DOSKIP("unknown pk algorithm");
212 !}
213 !ARG data {BASE91S} {
214     /* baseE91 and thus base91s can sometimes store 14 bits per
215      * character pair, so the max decode ratio is 14/16. */
216     size_t maxl = base91s_decode_maxlen(yyleng);
217     buffer_init(c->data_buf,0);
218     if (buf_remaining_space(c->data_buf) < maxl) DOSKIP("pk data too long");
219     struct base91s b91;
220     base91s_init(&b91);
221     size_t l = base91s_decode(&b91, yytext, yyleng, c->data_buf->start);
222     l += base91s_decode_end(&b91, c->data_buf->start + l);
223     assert(l <= maxl);
224     buf_append(c->data_buf,l);
225 !}
226 !FINAL {
227     if (c->building->nkeys >= MAX_SIG_KEYS) DOSKIP("too many public keys");
228     struct sigpubkey_if *pubkey;
229     bool_t ok=c->scheme->loadpub(c->scheme,c->data_buf,
230                                  &pubkey,c->log);
231     if (!ok) break;
232     memcpy(c->building->keys[c->building->nkeys].id.b,
233            c->grpid,
234            GRPIDSZ);
235     assert(ALGIDSZ==1); /* otherwise need htons or htonl or something */
236     c->building->keys[c->building->nkeys].id.b[GRPIDSZ]=
237       c->scheme->algid;
238     c->building->keys[c->building->nkeys++].pubkey=pubkey;
239 !}
240
241 !KEYWORD serial
242 !ARG id [0-9a-f]{!2SERIALSZ} {
243     if (c->had_serial) FAIL("`serial' repeated");
244     c->had_serial = 1;
245     uint8_t sb[SERIALSZ];
246     HEX2BIN_ARRAY(sb);
247     c->serial=get_uint32(sb);
248 !}
249 !FINAL {
250 !}
251
252 {L}[-0-9a-z]+ {
253     DOSKIP("unknown directive");
254 }
255
256 {L}\# {
257     BEGIN(SKIPNL);
258 }
259 {L}\n {
260     c->loc.line++;
261 }
262
263 <SKIPNL>.*\n {
264     c->loc.line++;
265     BEGIN(0);
266 }
267
268 <INITIAL><<EOF>>        { return 0; }
269
270 <*>. { FAIL("syntax error"); }
271 <*>\n { FAIL("syntax error - unexpected newline"); }
272 <<EOF>> { FAIL("syntax error - unexpected eof"); }
273
274 %%
275
276 extern struct peer_keyset *
277 keyset_load(const char *path, struct buffer_if *data_buf,
278             struct log_if *log, int logcl_enoent) {
279     assert(!c->building);
280     c->log=log;
281     c->loc.file=path;
282     pkyyin = fopen(path, "r");
283     if (!pkyyin) {
284         slilog(LI,
285                errno==ENOENT ? logcl_enoent : M_ERR,
286                "could not open keyset file %s: %s",
287                path,strerror(errno));
288         goto err;
289     }
290
291     pkyyrestart(pkyyin);
292     BEGIN(0);
293     c->data_buf=data_buf;
294     NEW(c->building);
295     c->building->nkeys=0;
296     c->building->refcount=1;
297     c->fallback_skip=0;
298     c->had_serial=0;
299     c->loc.line=1;
300     FILLZERO(c->grpid);
301     FILLZERO(c->serial);
302     int r=pkyylex();
303     if (r) goto err_bad;
304
305     if (!c->had_serial) {
306         slilog(LI,M_ERR,"missing serial number in %s",path);
307         goto err_bad;
308     }
309     if (!c->building->nkeys) {
310         slilog(LI,M_ERR,"no useable keys in %s",path);
311         goto err_bad;
312     }
313     fclose(pkyyin);
314     struct peer_keyset *built=c->building;
315     c->building=0;
316     return built;
317
318  err_bad:
319     errno=EBADMSG;
320  err:
321     if (c->building) { free(c->building); c->building=0; }
322     if (pkyyin) { fclose(pkyyin); pkyyin=0; }
323     return 0;
324 }
325