]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netgraph/ng_parse.c
bhnd(9): Fix a few mandoc related issues
[FreeBSD/FreeBSD.git] / sys / netgraph / ng_parse.c
1 /*
2  * ng_parse.c
3  */
4
5 /*-
6  * Copyright (c) 1999 Whistle Communications, Inc.
7  * All rights reserved.
8  * 
9  * Subject to the following obligations and disclaimer of warranty, use and
10  * redistribution of this software, in source or object code forms, with or
11  * without modifications are expressly permitted by Whistle Communications;
12  * provided, however, that:
13  * 1. Any and all reproductions of the source or object code must include the
14  *    copyright notice above and the following disclaimer of warranties; and
15  * 2. No rights are granted, in any manner or form, to use Whistle
16  *    Communications, Inc. trademarks, including the mark "WHISTLE
17  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
18  *    such appears in the above copyright notice or in the software.
19  * 
20  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
21  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
22  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
23  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
25  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
26  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
27  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
28  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
29  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
30  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
31  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
32  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
36  * OF SUCH DAMAGE.
37  *
38  * Author: Archie Cobbs <archie@freebsd.org>
39  *
40  * $Whistle: ng_parse.c,v 1.3 1999/11/29 01:43:48 archie Exp $
41  * $FreeBSD$
42  */
43
44 #include <sys/types.h>
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/errno.h>
49 #include <sys/limits.h>
50 #include <sys/malloc.h>
51 #include <sys/mbuf.h>
52 #include <sys/ctype.h>
53
54 #include <machine/stdarg.h>
55
56 #include <net/ethernet.h>
57
58 #include <netinet/in.h>
59
60 #include <netgraph/ng_message.h>
61 #include <netgraph/netgraph.h>
62 #include <netgraph/ng_parse.h>
63
64 #ifdef NG_SEPARATE_MALLOC
65 static MALLOC_DEFINE(M_NETGRAPH_PARSE, "netgraph_parse", "netgraph parse info");
66 #else
67 #define M_NETGRAPH_PARSE M_NETGRAPH
68 #endif
69
70 /* Compute alignment for primitive integral types */
71 struct int16_temp {
72         char    x;
73         int16_t y;
74 };
75
76 struct int32_temp {
77         char    x;
78         int32_t y;
79 };
80
81 struct int64_temp {
82         char    x;
83         int64_t y;
84 };
85
86 #define INT8_ALIGNMENT          1
87 #define INT16_ALIGNMENT         ((size_t)&((struct int16_temp *)0)->y)
88 #define INT32_ALIGNMENT         ((size_t)&((struct int32_temp *)0)->y)
89 #define INT64_ALIGNMENT         ((size_t)&((struct int64_temp *)0)->y)
90
91 /* Output format for integral types */
92 #define INT_UNSIGNED            0
93 #define INT_SIGNED              1
94 #define INT_HEX                 2
95
96 /* Type of composite object: struct, array, or fixedarray */
97 enum comptype {
98         CT_STRUCT,
99         CT_ARRAY,
100         CT_FIXEDARRAY,
101 };
102
103 /* Composite types helper functions */
104 static int      ng_parse_composite(const struct ng_parse_type *type,
105                         const char *s, int *off, const u_char *start,
106                         u_char *const buf, int *buflen, enum comptype ctype);
107 static int      ng_unparse_composite(const struct ng_parse_type *type,
108                         const u_char *data, int *off, char *cbuf, int cbuflen,
109                         enum comptype ctype);
110 static int      ng_get_composite_elem_default(const struct ng_parse_type *type,
111                         int index, const u_char *start, u_char *buf,
112                         int *buflen, enum comptype ctype);
113 static int      ng_get_composite_len(const struct ng_parse_type *type,
114                         const u_char *start, const u_char *buf,
115                         enum comptype ctype);
116 static const    struct ng_parse_type *ng_get_composite_etype(const struct
117                         ng_parse_type *type, int index, enum comptype ctype);
118 static int      ng_parse_get_elem_pad(const struct ng_parse_type *type,
119                         int index, enum comptype ctype, int posn);
120
121 /* Parsing helper functions */
122 static int      ng_parse_skip_value(const char *s, int off, int *lenp);
123 static int      ng_parse_append(char **cbufp, int *cbuflenp,
124                         const char *fmt, ...);
125
126 /* Poor man's virtual method calls */
127 #define METHOD(t,m)     (ng_get_ ## m ## _method(t))
128 #define INVOKE(t,m)     (*METHOD(t,m))
129
130 static ng_parse_t       *ng_get_parse_method(const struct ng_parse_type *t);
131 static ng_unparse_t     *ng_get_unparse_method(const struct ng_parse_type *t);
132 static ng_getDefault_t  *ng_get_getDefault_method(const
133                                 struct ng_parse_type *t);
134 static ng_getAlign_t    *ng_get_getAlign_method(const struct ng_parse_type *t);
135
136 #define ALIGNMENT(t)    (METHOD(t, getAlign) == NULL ? \
137                                 0 : INVOKE(t, getAlign)(t))
138
139 /************************************************************************
140                         PUBLIC FUNCTIONS
141  ************************************************************************/
142
143 /*
144  * Convert an ASCII string to binary according to the supplied type descriptor
145  */
146 int
147 ng_parse(const struct ng_parse_type *type,
148         const char *string, int *off, u_char *buf, int *buflen)
149 {
150         return INVOKE(type, parse)(type, string, off, buf, buf, buflen);
151 }
152
153 /*
154  * Convert binary to an ASCII string according to the supplied type descriptor
155  */
156 int
157 ng_unparse(const struct ng_parse_type *type,
158         const u_char *data, char *cbuf, int cbuflen)
159 {
160         int off = 0;
161
162         return INVOKE(type, unparse)(type, data, &off, cbuf, cbuflen);
163 }
164
165 /*
166  * Fill in the default value according to the supplied type descriptor
167  */
168 int
169 ng_parse_getDefault(const struct ng_parse_type *type, u_char *buf, int *buflen)
170 {
171         ng_getDefault_t *const func = METHOD(type, getDefault);
172
173         if (func == NULL)
174                 return (EOPNOTSUPP);
175         return (*func)(type, buf, buf, buflen);
176 }
177
178 /************************************************************************
179                         STRUCTURE TYPE
180  ************************************************************************/
181
182 static int
183 ng_struct_parse(const struct ng_parse_type *type,
184         const char *s, int *off, const u_char *const start,
185         u_char *const buf, int *buflen)
186 {
187         return ng_parse_composite(type, s, off, start, buf, buflen, CT_STRUCT);
188 }
189
190 static int
191 ng_struct_unparse(const struct ng_parse_type *type,
192         const u_char *data, int *off, char *cbuf, int cbuflen)
193 {
194         return ng_unparse_composite(type, data, off, cbuf, cbuflen, CT_STRUCT);
195 }
196
197 static int
198 ng_struct_getDefault(const struct ng_parse_type *type,
199         const u_char *const start, u_char *buf, int *buflen)
200 {
201         int off = 0;
202
203         return ng_parse_composite(type,
204             "{}", &off, start, buf, buflen, CT_STRUCT);
205 }
206
207 static int
208 ng_struct_getAlign(const struct ng_parse_type *type)
209 {
210         const struct ng_parse_struct_field *field;
211         int align = 0;
212
213         for (field = type->info; field->name != NULL; field++) {
214                 int falign = ALIGNMENT(field->type);
215
216                 if (falign > align)
217                         align = falign;
218         }
219         return align;
220 }
221
222 const struct ng_parse_type ng_parse_struct_type = {
223         NULL,
224         NULL,
225         NULL,
226         ng_struct_parse,
227         ng_struct_unparse,
228         ng_struct_getDefault,
229         ng_struct_getAlign
230 };
231
232 /************************************************************************
233                         FIXED LENGTH ARRAY TYPE
234  ************************************************************************/
235
236 static int
237 ng_fixedarray_parse(const struct ng_parse_type *type,
238         const char *s, int *off, const u_char *const start,
239         u_char *const buf, int *buflen)
240 {
241         return ng_parse_composite(type,
242             s, off, start, buf, buflen, CT_FIXEDARRAY);
243 }
244
245 static int
246 ng_fixedarray_unparse(const struct ng_parse_type *type,
247         const u_char *data, int *off, char *cbuf, int cbuflen)
248 {
249         return ng_unparse_composite(type,
250                 data, off, cbuf, cbuflen, CT_FIXEDARRAY);
251 }
252
253 static int
254 ng_fixedarray_getDefault(const struct ng_parse_type *type,
255         const u_char *const start, u_char *buf, int *buflen)
256 {
257         int off = 0;
258
259         return ng_parse_composite(type,
260             "[]", &off, start, buf, buflen, CT_FIXEDARRAY);
261 }
262
263 static int
264 ng_fixedarray_getAlign(const struct ng_parse_type *type)
265 {
266         const struct ng_parse_fixedarray_info *fi = type->info;
267
268         return ALIGNMENT(fi->elementType);
269 }
270
271 const struct ng_parse_type ng_parse_fixedarray_type = {
272         NULL,
273         NULL,
274         NULL,
275         ng_fixedarray_parse,
276         ng_fixedarray_unparse,
277         ng_fixedarray_getDefault,
278         ng_fixedarray_getAlign
279 };
280
281 /************************************************************************
282                         VARIABLE LENGTH ARRAY TYPE
283  ************************************************************************/
284
285 static int
286 ng_array_parse(const struct ng_parse_type *type,
287         const char *s, int *off, const u_char *const start,
288         u_char *const buf, int *buflen)
289 {
290         return ng_parse_composite(type, s, off, start, buf, buflen, CT_ARRAY);
291 }
292
293 static int
294 ng_array_unparse(const struct ng_parse_type *type,
295         const u_char *data, int *off, char *cbuf, int cbuflen)
296 {
297         return ng_unparse_composite(type, data, off, cbuf, cbuflen, CT_ARRAY);
298 }
299
300 static int
301 ng_array_getDefault(const struct ng_parse_type *type,
302         const u_char *const start, u_char *buf, int *buflen)
303 {
304         int off = 0;
305
306         return ng_parse_composite(type,
307             "[]", &off, start, buf, buflen, CT_ARRAY);
308 }
309
310 static int
311 ng_array_getAlign(const struct ng_parse_type *type)
312 {
313         const struct ng_parse_array_info *ai = type->info;
314
315         return ALIGNMENT(ai->elementType);
316 }
317
318 const struct ng_parse_type ng_parse_array_type = {
319         NULL,
320         NULL,
321         NULL,
322         ng_array_parse,
323         ng_array_unparse,
324         ng_array_getDefault,
325         ng_array_getAlign
326 };
327
328 /************************************************************************
329                                 INT8 TYPE
330  ************************************************************************/
331
332 static int
333 ng_int8_parse(const struct ng_parse_type *type,
334         const char *s, int *off, const u_char *const start,
335         u_char *const buf, int *buflen)
336 {
337         long val;
338         int8_t val8;
339         char *eptr;
340
341         val = strtol(s + *off, &eptr, 0);
342         if (val < (int8_t)0x80 || val > (u_int8_t)0xff || eptr == s + *off)
343                 return (EINVAL);
344         *off = eptr - s;
345         val8 = (int8_t)val;
346         bcopy(&val8, buf, sizeof(int8_t));
347         *buflen = sizeof(int8_t);
348         return (0);
349 }
350
351 static int
352 ng_int8_unparse(const struct ng_parse_type *type,
353         const u_char *data, int *off, char *cbuf, int cbuflen)
354 {
355         const char *fmt;
356         int fval;
357         int error;
358         int8_t val;
359
360         bcopy(data + *off, &val, sizeof(int8_t));
361         switch ((intptr_t)type->info) {
362         case INT_SIGNED:
363                 fmt = "%d";
364                 fval = val;
365                 break;
366         case INT_UNSIGNED:
367                 fmt = "%u";
368                 fval = (u_int8_t)val;
369                 break;
370         case INT_HEX:
371                 fmt = "0x%x";
372                 fval = (u_int8_t)val;
373                 break;
374         default:
375                 panic("%s: unknown type", __func__);
376         }
377         if ((error = ng_parse_append(&cbuf, &cbuflen, fmt, fval)) != 0)
378                 return (error);
379         *off += sizeof(int8_t);
380         return (0);
381 }
382
383 static int
384 ng_int8_getDefault(const struct ng_parse_type *type,
385         const u_char *const start, u_char *buf, int *buflen)
386 {
387         int8_t val;
388
389         if (*buflen < sizeof(int8_t))
390                 return (ERANGE);
391         val = 0;
392         bcopy(&val, buf, sizeof(int8_t));
393         *buflen = sizeof(int8_t);
394         return (0);
395 }
396
397 static int
398 ng_int8_getAlign(const struct ng_parse_type *type)
399 {
400         return INT8_ALIGNMENT;
401 }
402
403 const struct ng_parse_type ng_parse_int8_type = {
404         NULL,
405         (void *)INT_SIGNED,
406         NULL,
407         ng_int8_parse,
408         ng_int8_unparse,
409         ng_int8_getDefault,
410         ng_int8_getAlign
411 };
412
413 const struct ng_parse_type ng_parse_uint8_type = {
414         &ng_parse_int8_type,
415         (void *)INT_UNSIGNED
416 };
417
418 const struct ng_parse_type ng_parse_hint8_type = {
419         &ng_parse_int8_type,
420         (void *)INT_HEX
421 };
422
423 /************************************************************************
424                                 INT16 TYPE
425  ************************************************************************/
426
427 static int
428 ng_int16_parse(const struct ng_parse_type *type,
429         const char *s, int *off, const u_char *const start,
430         u_char *const buf, int *buflen)
431 {
432         long val;
433         int16_t val16;
434         char *eptr;
435
436         val = strtol(s + *off, &eptr, 0);
437         if (val < (int16_t)0x8000
438             || val > (u_int16_t)0xffff || eptr == s + *off)
439                 return (EINVAL);
440         *off = eptr - s;
441         val16 = (int16_t)val;
442         bcopy(&val16, buf, sizeof(int16_t));
443         *buflen = sizeof(int16_t);
444         return (0);
445 }
446
447 static int
448 ng_int16_unparse(const struct ng_parse_type *type,
449         const u_char *data, int *off, char *cbuf, int cbuflen)
450 {
451         const char *fmt;
452         int fval;
453         int error;
454         int16_t val;
455
456         bcopy(data + *off, &val, sizeof(int16_t));
457         switch ((intptr_t)type->info) {
458         case INT_SIGNED:
459                 fmt = "%d";
460                 fval = val;
461                 break;
462         case INT_UNSIGNED:
463                 fmt = "%u";
464                 fval = (u_int16_t)val;
465                 break;
466         case INT_HEX:
467                 fmt = "0x%x";
468                 fval = (u_int16_t)val;
469                 break;
470         default:
471                 panic("%s: unknown type", __func__);
472         }
473         if ((error = ng_parse_append(&cbuf, &cbuflen, fmt, fval)) != 0)
474                 return (error);
475         *off += sizeof(int16_t);
476         return (0);
477 }
478
479 static int
480 ng_int16_getDefault(const struct ng_parse_type *type,
481         const u_char *const start, u_char *buf, int *buflen)
482 {
483         int16_t val;
484
485         if (*buflen < sizeof(int16_t))
486                 return (ERANGE);
487         val = 0;
488         bcopy(&val, buf, sizeof(int16_t));
489         *buflen = sizeof(int16_t);
490         return (0);
491 }
492
493 static int
494 ng_int16_getAlign(const struct ng_parse_type *type)
495 {
496         return INT16_ALIGNMENT;
497 }
498
499 const struct ng_parse_type ng_parse_int16_type = {
500         NULL,
501         (void *)INT_SIGNED,
502         NULL,
503         ng_int16_parse,
504         ng_int16_unparse,
505         ng_int16_getDefault,
506         ng_int16_getAlign
507 };
508
509 const struct ng_parse_type ng_parse_uint16_type = {
510         &ng_parse_int16_type,
511         (void *)INT_UNSIGNED
512 };
513
514 const struct ng_parse_type ng_parse_hint16_type = {
515         &ng_parse_int16_type,
516         (void *)INT_HEX
517 };
518
519 /************************************************************************
520                                 INT32 TYPE
521  ************************************************************************/
522
523 static int
524 ng_int32_parse(const struct ng_parse_type *type,
525         const char *s, int *off, const u_char *const start,
526         u_char *const buf, int *buflen)
527 {
528         long val;                       /* assumes long is at least 32 bits */
529         int32_t val32;
530         char *eptr;
531
532         if ((intptr_t)type->info == INT_SIGNED)
533                 val = strtol(s + *off, &eptr, 0);
534         else
535                 val = strtoul(s + *off, &eptr, 0);
536         if (val < (int32_t)0x80000000
537             || val > (u_int32_t)0xffffffff || eptr == s + *off)
538                 return (EINVAL);
539         *off = eptr - s;
540         val32 = (int32_t)val;
541         bcopy(&val32, buf, sizeof(int32_t));
542         *buflen = sizeof(int32_t);
543         return (0);
544 }
545
546 static int
547 ng_int32_unparse(const struct ng_parse_type *type,
548         const u_char *data, int *off, char *cbuf, int cbuflen)
549 {
550         const char *fmt;
551         long fval;
552         int error;
553         int32_t val;
554
555         bcopy(data + *off, &val, sizeof(int32_t));
556         switch ((intptr_t)type->info) {
557         case INT_SIGNED:
558                 fmt = "%ld";
559                 fval = val;
560                 break;
561         case INT_UNSIGNED:
562                 fmt = "%lu";
563                 fval = (u_int32_t)val;
564                 break;
565         case INT_HEX:
566                 fmt = "0x%lx";
567                 fval = (u_int32_t)val;
568                 break;
569         default:
570                 panic("%s: unknown type", __func__);
571         }
572         if ((error = ng_parse_append(&cbuf, &cbuflen, fmt, fval)) != 0)
573                 return (error);
574         *off += sizeof(int32_t);
575         return (0);
576 }
577
578 static int
579 ng_int32_getDefault(const struct ng_parse_type *type,
580         const u_char *const start, u_char *buf, int *buflen)
581 {
582         int32_t val;
583
584         if (*buflen < sizeof(int32_t))
585                 return (ERANGE);
586         val = 0;
587         bcopy(&val, buf, sizeof(int32_t));
588         *buflen = sizeof(int32_t);
589         return (0);
590 }
591
592 static int
593 ng_int32_getAlign(const struct ng_parse_type *type)
594 {
595         return INT32_ALIGNMENT;
596 }
597
598 const struct ng_parse_type ng_parse_int32_type = {
599         NULL,
600         (void *)INT_SIGNED,
601         NULL,
602         ng_int32_parse,
603         ng_int32_unparse,
604         ng_int32_getDefault,
605         ng_int32_getAlign
606 };
607
608 const struct ng_parse_type ng_parse_uint32_type = {
609         &ng_parse_int32_type,
610         (void *)INT_UNSIGNED
611 };
612
613 const struct ng_parse_type ng_parse_hint32_type = {
614         &ng_parse_int32_type,
615         (void *)INT_HEX
616 };
617
618 /************************************************************************
619                                 INT64 TYPE
620  ************************************************************************/
621
622 static int
623 ng_int64_parse(const struct ng_parse_type *type,
624         const char *s, int *off, const u_char *const start,
625         u_char *const buf, int *buflen)
626 {
627         quad_t val;
628         int64_t val64;
629         char *eptr;
630
631         val = strtoq(s + *off, &eptr, 0);
632         if (eptr == s + *off)
633                 return (EINVAL);
634         *off = eptr - s;
635         val64 = (int64_t)val;
636         bcopy(&val64, buf, sizeof(int64_t));
637         *buflen = sizeof(int64_t);
638         return (0);
639 }
640
641 static int
642 ng_int64_unparse(const struct ng_parse_type *type,
643         const u_char *data, int *off, char *cbuf, int cbuflen)
644 {
645         const char *fmt;
646         long long fval;
647         int64_t val;
648         int error;
649
650         bcopy(data + *off, &val, sizeof(int64_t));
651         switch ((intptr_t)type->info) {
652         case INT_SIGNED:
653                 fmt = "%lld";
654                 fval = val;
655                 break;
656         case INT_UNSIGNED:
657                 fmt = "%llu";
658                 fval = (u_int64_t)val;
659                 break;
660         case INT_HEX:
661                 fmt = "0x%llx";
662                 fval = (u_int64_t)val;
663                 break;
664         default:
665                 panic("%s: unknown type", __func__);
666         }
667         if ((error = ng_parse_append(&cbuf, &cbuflen, fmt, fval)) != 0)
668                 return (error);
669         *off += sizeof(int64_t);
670         return (0);
671 }
672
673 static int
674 ng_int64_getDefault(const struct ng_parse_type *type,
675         const u_char *const start, u_char *buf, int *buflen)
676 {
677         int64_t val;
678
679         if (*buflen < sizeof(int64_t))
680                 return (ERANGE);
681         val = 0;
682         bcopy(&val, buf, sizeof(int64_t));
683         *buflen = sizeof(int64_t);
684         return (0);
685 }
686
687 static int
688 ng_int64_getAlign(const struct ng_parse_type *type)
689 {
690         return INT64_ALIGNMENT;
691 }
692
693 const struct ng_parse_type ng_parse_int64_type = {
694         NULL,
695         (void *)INT_SIGNED,
696         NULL,
697         ng_int64_parse,
698         ng_int64_unparse,
699         ng_int64_getDefault,
700         ng_int64_getAlign
701 };
702
703 const struct ng_parse_type ng_parse_uint64_type = {
704         &ng_parse_int64_type,
705         (void *)INT_UNSIGNED
706 };
707
708 const struct ng_parse_type ng_parse_hint64_type = {
709         &ng_parse_int64_type,
710         (void *)INT_HEX
711 };
712
713 /************************************************************************
714                                 STRING TYPE
715  ************************************************************************/
716
717 static int
718 ng_string_parse(const struct ng_parse_type *type,
719         const char *s, int *off, const u_char *const start,
720         u_char *const buf, int *buflen)
721 {
722         char *sval;
723         int len;
724         int slen;
725
726         if ((sval = ng_get_string_token(s, off, &len, &slen)) == NULL)
727                 return (EINVAL);
728         *off += len;
729         bcopy(sval, buf, slen + 1);
730         free(sval, M_NETGRAPH_PARSE);
731         *buflen = slen + 1;
732         return (0);
733 }
734
735 static int
736 ng_string_unparse(const struct ng_parse_type *type,
737         const u_char *data, int *off, char *cbuf, int cbuflen)
738 {
739         const char *const raw = (const char *)data + *off;
740         char *const s = ng_encode_string(raw, strlen(raw));
741         int error;
742
743         if (s == NULL)
744                 return (ENOMEM);
745         if ((error = ng_parse_append(&cbuf, &cbuflen, "%s", s)) != 0) {
746                 free(s, M_NETGRAPH_PARSE);
747                 return (error);
748         }
749         *off += strlen(raw) + 1;
750         free(s, M_NETGRAPH_PARSE);
751         return (0);
752 }
753
754 static int
755 ng_string_getDefault(const struct ng_parse_type *type,
756         const u_char *const start, u_char *buf, int *buflen)
757 {
758
759         if (*buflen < 1)
760                 return (ERANGE);
761         buf[0] = (u_char)'\0';
762         *buflen = 1;
763         return (0);
764 }
765
766 const struct ng_parse_type ng_parse_string_type = {
767         NULL,
768         NULL,
769         NULL,
770         ng_string_parse,
771         ng_string_unparse,
772         ng_string_getDefault,
773         NULL
774 };
775
776 /************************************************************************
777                         FIXED BUFFER STRING TYPE
778  ************************************************************************/
779
780 static int
781 ng_fixedstring_parse(const struct ng_parse_type *type,
782         const char *s, int *off, const u_char *const start,
783         u_char *const buf, int *buflen)
784 {
785         const struct ng_parse_fixedstring_info *const fi = type->info;
786         char *sval;
787         int len;
788         int slen;
789
790         if ((sval = ng_get_string_token(s, off, &len, &slen)) == NULL)
791                 return (EINVAL);
792         if (slen + 1 > fi->bufSize) {
793                 free(sval, M_NETGRAPH_PARSE);
794                 return (E2BIG);
795         }
796         *off += len;
797         bcopy(sval, buf, slen);
798         free(sval, M_NETGRAPH_PARSE);
799         bzero(buf + slen, fi->bufSize - slen);
800         *buflen = fi->bufSize;
801         return (0);
802 }
803
804 static int
805 ng_fixedstring_unparse(const struct ng_parse_type *type,
806         const u_char *data, int *off, char *cbuf, int cbuflen)
807 {
808         const struct ng_parse_fixedstring_info *const fi = type->info;
809         int error, temp = *off;
810
811         if ((error = ng_string_unparse(type, data, &temp, cbuf, cbuflen)) != 0)
812                 return (error);
813         *off += fi->bufSize;
814         return (0);
815 }
816
817 static int
818 ng_fixedstring_getDefault(const struct ng_parse_type *type,
819         const u_char *const start, u_char *buf, int *buflen)
820 {
821         const struct ng_parse_fixedstring_info *const fi = type->info;
822
823         if (*buflen < fi->bufSize)
824                 return (ERANGE);
825         bzero(buf, fi->bufSize);
826         *buflen = fi->bufSize;
827         return (0);
828 }
829
830 const struct ng_parse_type ng_parse_fixedstring_type = {
831         NULL,
832         NULL,
833         NULL,
834         ng_fixedstring_parse,
835         ng_fixedstring_unparse,
836         ng_fixedstring_getDefault,
837         NULL
838 };
839
840 const struct ng_parse_fixedstring_info ng_parse_nodebuf_info = {
841         NG_NODESIZ
842 };
843 const struct ng_parse_type ng_parse_nodebuf_type = {
844         &ng_parse_fixedstring_type,
845         &ng_parse_nodebuf_info
846 };
847
848 const struct ng_parse_fixedstring_info ng_parse_hookbuf_info = {
849         NG_HOOKSIZ
850 };
851 const struct ng_parse_type ng_parse_hookbuf_type = {
852         &ng_parse_fixedstring_type,
853         &ng_parse_hookbuf_info
854 };
855
856 const struct ng_parse_fixedstring_info ng_parse_pathbuf_info = {
857         NG_PATHSIZ
858 };
859 const struct ng_parse_type ng_parse_pathbuf_type = {
860         &ng_parse_fixedstring_type,
861         &ng_parse_pathbuf_info
862 };
863
864 const struct ng_parse_fixedstring_info ng_parse_typebuf_info = {
865         NG_TYPESIZ
866 };
867 const struct ng_parse_type ng_parse_typebuf_type = {
868         &ng_parse_fixedstring_type,
869         &ng_parse_typebuf_info
870 };
871
872 const struct ng_parse_fixedstring_info ng_parse_cmdbuf_info = {
873         NG_CMDSTRSIZ
874 };
875 const struct ng_parse_type ng_parse_cmdbuf_type = {
876         &ng_parse_fixedstring_type,
877         &ng_parse_cmdbuf_info
878 };
879
880 /************************************************************************
881                         EXPLICITLY SIZED STRING TYPE
882  ************************************************************************/
883
884 static int
885 ng_sizedstring_parse(const struct ng_parse_type *type,
886         const char *s, int *off, const u_char *const start,
887         u_char *const buf, int *buflen)
888 {
889         char *sval;
890         int len;
891         int slen;
892
893         if ((sval = ng_get_string_token(s, off, &len, &slen)) == NULL)
894                 return (EINVAL);
895         if (slen > USHRT_MAX) {
896                 free(sval, M_NETGRAPH_PARSE);
897                 return (EINVAL);
898         }
899         *off += len;
900         *((u_int16_t *)buf) = (u_int16_t)slen;
901         bcopy(sval, buf + 2, slen);
902         free(sval, M_NETGRAPH_PARSE);
903         *buflen = 2 + slen;
904         return (0);
905 }
906
907 static int
908 ng_sizedstring_unparse(const struct ng_parse_type *type,
909         const u_char *data, int *off, char *cbuf, int cbuflen)
910 {
911         const char *const raw = (const char *)data + *off + 2;
912         const int slen = *((const u_int16_t *)(data + *off));
913         char *const s = ng_encode_string(raw, slen);
914         int error;
915
916         if (s == NULL)
917                 return (ENOMEM);
918         if ((error = ng_parse_append(&cbuf, &cbuflen, "%s", s)) != 0) {
919                 free(s, M_NETGRAPH_PARSE);
920                 return (error);
921         }
922         free(s, M_NETGRAPH_PARSE);
923         *off += slen + 2;
924         return (0);
925 }
926
927 static int
928 ng_sizedstring_getDefault(const struct ng_parse_type *type,
929         const u_char *const start, u_char *buf, int *buflen)
930 {
931         if (*buflen < 2)
932                 return (ERANGE);
933         bzero(buf, 2);
934         *buflen = 2;
935         return (0);
936 }
937
938 const struct ng_parse_type ng_parse_sizedstring_type = {
939         NULL,
940         NULL,
941         NULL,
942         ng_sizedstring_parse,
943         ng_sizedstring_unparse,
944         ng_sizedstring_getDefault,
945         NULL
946 };
947
948 /************************************************************************
949                         IP ADDRESS TYPE
950  ************************************************************************/
951
952 static int
953 ng_ipaddr_parse(const struct ng_parse_type *type,
954         const char *s, int *off, const u_char *const start,
955         u_char *const buf, int *buflen)
956 {
957         int i, error;
958
959         for (i = 0; i < 4; i++) {
960                 if ((error = ng_int8_parse(&ng_parse_int8_type,
961                     s, off, start, buf + i, buflen)) != 0)
962                         return (error);
963                 if (i < 3 && s[*off] != '.')
964                         return (EINVAL);
965                 (*off)++;
966         }
967         *buflen = 4;
968         return (0);
969 }
970
971 static int
972 ng_ipaddr_unparse(const struct ng_parse_type *type,
973         const u_char *data, int *off, char *cbuf, int cbuflen)
974 {
975         struct in_addr ip;
976         int error;
977
978         bcopy(data + *off, &ip, sizeof(ip));
979         if ((error = ng_parse_append(&cbuf, &cbuflen, "%d.%d.%d.%d",
980             ((u_char *)&ip)[0], ((u_char *)&ip)[1],
981             ((u_char *)&ip)[2], ((u_char *)&ip)[3])) != 0)
982                 return (error);
983         *off += sizeof(ip);
984         return (0);
985 }
986
987 static int
988 ng_ipaddr_getDefault(const struct ng_parse_type *type,
989         const u_char *const start, u_char *buf, int *buflen)
990 {
991         struct in_addr ip = { 0 };
992
993         if (*buflen < sizeof(ip))
994                 return (ERANGE);
995         bcopy(&ip, buf, sizeof(ip));
996         *buflen = sizeof(ip);
997         return (0);
998 }
999
1000 const struct ng_parse_type ng_parse_ipaddr_type = {
1001         NULL,
1002         NULL,
1003         NULL,
1004         ng_ipaddr_parse,
1005         ng_ipaddr_unparse,
1006         ng_ipaddr_getDefault,
1007         ng_int32_getAlign
1008 };
1009
1010 /************************************************************************
1011                         ETHERNET ADDRESS TYPE
1012  ************************************************************************/
1013
1014 static int
1015 ng_enaddr_parse(const struct ng_parse_type *type,
1016         const char *s, int *const off, const u_char *const start,
1017         u_char *const buf, int *const buflen)
1018 {
1019         char *eptr;
1020         u_long val;
1021         int i;
1022
1023         if (*buflen < ETHER_ADDR_LEN)
1024                 return (ERANGE);
1025         for (i = 0; i < ETHER_ADDR_LEN; i++) {
1026                 val = strtoul(s + *off, &eptr, 16);
1027                 if (val > 0xff || eptr == s + *off)
1028                         return (EINVAL);
1029                 buf[i] = (u_char)val;
1030                 *off = (eptr - s);
1031                 if (i < ETHER_ADDR_LEN - 1) {
1032                         if (*eptr != ':')
1033                                 return (EINVAL);
1034                         (*off)++;
1035                 }
1036         }
1037         *buflen = ETHER_ADDR_LEN;
1038         return (0);
1039 }
1040
1041 static int
1042 ng_enaddr_unparse(const struct ng_parse_type *type,
1043         const u_char *data, int *off, char *cbuf, int cbuflen)
1044 {
1045         int len;
1046
1047         len = snprintf(cbuf, cbuflen, "%02x:%02x:%02x:%02x:%02x:%02x",
1048             data[*off], data[*off + 1], data[*off + 2],
1049             data[*off + 3], data[*off + 4], data[*off + 5]);
1050         if (len >= cbuflen)
1051                 return (ERANGE);
1052         *off += ETHER_ADDR_LEN;
1053         return (0);
1054 }
1055
1056 const struct ng_parse_type ng_parse_enaddr_type = {
1057         NULL,
1058         NULL,
1059         NULL,
1060         ng_enaddr_parse,
1061         ng_enaddr_unparse,
1062         NULL,
1063         0
1064 };
1065
1066 /************************************************************************
1067                         BYTE ARRAY TYPE
1068  ************************************************************************/
1069
1070 /* Get the length of a byte array */
1071 static int
1072 ng_parse_bytearray_subtype_getLength(const struct ng_parse_type *type,
1073         const u_char *start, const u_char *buf)
1074 {
1075         ng_parse_array_getLength_t *const getLength = type->private;
1076
1077         return (*getLength)(type, start, buf);
1078 }
1079
1080 /* Byte array element type is hex int8 */
1081 static const struct ng_parse_array_info ng_parse_bytearray_subtype_info = {
1082         &ng_parse_hint8_type,
1083         &ng_parse_bytearray_subtype_getLength,
1084         NULL
1085 };
1086 static const struct ng_parse_type ng_parse_bytearray_subtype = {
1087         &ng_parse_array_type,
1088         &ng_parse_bytearray_subtype_info
1089 };
1090
1091 static int
1092 ng_bytearray_parse(const struct ng_parse_type *type,
1093         const char *s, int *off, const u_char *const start,
1094         u_char *const buf, int *buflen)
1095 {
1096         char *str;
1097         int toklen;
1098         int slen;
1099
1100         /* We accept either an array of bytes or a string constant */
1101         if ((str = ng_get_string_token(s, off, &toklen, &slen)) != NULL) {
1102                 ng_parse_array_getLength_t *const getLength = type->info;
1103                 int arraylen;
1104
1105                 arraylen = (*getLength)(type, start, buf);
1106                 if (arraylen > *buflen) {
1107                         free(str, M_NETGRAPH_PARSE);
1108                         return (ERANGE);
1109                 }
1110                 if (slen > arraylen) {
1111                         free(str, M_NETGRAPH_PARSE);
1112                         return (E2BIG);
1113                 }
1114                 bcopy(str, buf, slen);
1115                 bzero(buf + slen, arraylen - slen);
1116                 free(str, M_NETGRAPH_PARSE);
1117                 *off += toklen;
1118                 *buflen = arraylen;
1119                 return (0);
1120         } else {
1121                 struct ng_parse_type subtype;
1122
1123                 subtype = ng_parse_bytearray_subtype;
1124                 subtype.private = __DECONST(void *, type->info);
1125                 return ng_array_parse(&subtype, s, off, start, buf, buflen);
1126         }
1127 }
1128
1129 static int
1130 ng_bytearray_unparse(const struct ng_parse_type *type,
1131         const u_char *data, int *off, char *cbuf, int cbuflen)
1132 {
1133         struct ng_parse_type subtype;
1134
1135         subtype = ng_parse_bytearray_subtype;
1136         subtype.private = __DECONST(void *, type->info);
1137         return ng_array_unparse(&subtype, data, off, cbuf, cbuflen);
1138 }
1139
1140 static int
1141 ng_bytearray_getDefault(const struct ng_parse_type *type,
1142         const u_char *const start, u_char *buf, int *buflen)
1143 {
1144         struct ng_parse_type subtype;
1145
1146         subtype = ng_parse_bytearray_subtype;
1147         subtype.private = __DECONST(void *, type->info);
1148         return ng_array_getDefault(&subtype, start, buf, buflen);
1149 }
1150
1151 const struct ng_parse_type ng_parse_bytearray_type = {
1152         NULL,
1153         NULL,
1154         NULL,
1155         ng_bytearray_parse,
1156         ng_bytearray_unparse,
1157         ng_bytearray_getDefault,
1158         NULL
1159 };
1160
1161 /************************************************************************
1162                         STRUCT NG_MESG TYPE
1163  ************************************************************************/
1164
1165 /* Get msg->header.arglen when "buf" is pointing to msg->data */
1166 static int
1167 ng_parse_ng_mesg_getLength(const struct ng_parse_type *type,
1168         const u_char *start, const u_char *buf)
1169 {
1170         const struct ng_mesg *msg;
1171
1172         msg = (const struct ng_mesg *)(buf - sizeof(*msg));
1173         return msg->header.arglen;
1174 }
1175
1176 /* Type for the variable length data portion of a struct ng_mesg */
1177 static const struct ng_parse_type ng_msg_data_type = {
1178         &ng_parse_bytearray_type,
1179         &ng_parse_ng_mesg_getLength
1180 };
1181
1182 /* Type for the entire struct ng_mesg header with data section */
1183 static const struct ng_parse_struct_field ng_parse_ng_mesg_type_fields[]
1184         = NG_GENERIC_NG_MESG_INFO(&ng_msg_data_type);
1185 const struct ng_parse_type ng_parse_ng_mesg_type = {
1186         &ng_parse_struct_type,
1187         &ng_parse_ng_mesg_type_fields,
1188 };
1189
1190 /************************************************************************
1191                         COMPOSITE HELPER ROUTINES
1192  ************************************************************************/
1193
1194 /*
1195  * Convert a structure or array from ASCII to binary
1196  */
1197 static int
1198 ng_parse_composite(const struct ng_parse_type *type, const char *s,
1199         int *off, const u_char *const start, u_char *const buf, int *buflen,
1200         const enum comptype ctype)
1201 {
1202         const int num = ng_get_composite_len(type, start, buf, ctype);
1203         int nextIndex = 0;              /* next implicit array index */
1204         u_int index;                    /* field or element index */
1205         int *foff;                      /* field value offsets in string */
1206         int align, len, blen, error = 0;
1207
1208         /* Initialize */
1209         foff = malloc(num * sizeof(*foff), M_NETGRAPH_PARSE, M_NOWAIT | M_ZERO);
1210         if (foff == NULL) {
1211                 error = ENOMEM;
1212                 goto done;
1213         }
1214
1215         /* Get opening brace/bracket */
1216         if (ng_parse_get_token(s, off, &len)
1217             != (ctype == CT_STRUCT ? T_LBRACE : T_LBRACKET)) {
1218                 error = EINVAL;
1219                 goto done;
1220         }
1221         *off += len;
1222
1223         /* Get individual element value positions in the string */
1224         for (;;) {
1225                 enum ng_parse_token tok;
1226
1227                 /* Check for closing brace/bracket */
1228                 tok = ng_parse_get_token(s, off, &len);
1229                 if (tok == (ctype == CT_STRUCT ? T_RBRACE : T_RBRACKET)) {
1230                         *off += len;
1231                         break;
1232                 }
1233
1234                 /* For arrays, the 'name' (ie, index) is optional, so
1235                    distinguish name from values by seeing if the next
1236                    token is an equals sign */
1237                 if (ctype != CT_STRUCT) {
1238                         u_long ul;
1239                         int len2, off2;
1240                         char *eptr;
1241
1242                         /* If an opening brace/bracket, index is implied */
1243                         if (tok == T_LBRACE || tok == T_LBRACKET) {
1244                                 index = nextIndex++;
1245                                 goto gotIndex;
1246                         }
1247
1248                         /* Might be an index, might be a value, either way... */
1249                         if (tok != T_WORD) {
1250                                 error = EINVAL;
1251                                 goto done;
1252                         }
1253
1254                         /* If no equals sign follows, index is implied */
1255                         off2 = *off + len;
1256                         if (ng_parse_get_token(s, &off2, &len2) != T_EQUALS) {
1257                                 index = nextIndex++;
1258                                 goto gotIndex;
1259                         }
1260
1261                         /* Index was specified explicitly; parse it */
1262                         ul = strtoul(s + *off, &eptr, 0);
1263                         if (ul == ULONG_MAX || eptr - (s + *off) != len) {
1264                                 error = EINVAL;
1265                                 goto done;
1266                         }
1267                         index = (u_int)ul;
1268                         nextIndex = index + 1;
1269                         *off += len + len2;
1270                 } else {                        /* a structure field */
1271                         const struct ng_parse_struct_field *const
1272                             fields = type->info;
1273
1274                         /* Find the field by name (required) in field list */
1275                         if (tok != T_WORD) {
1276                                 error = EINVAL;
1277                                 goto done;
1278                         }
1279                         for (index = 0; index < num; index++) {
1280                                 const struct ng_parse_struct_field *const
1281                                     field = &fields[index];
1282
1283                                 if (strncmp(&s[*off], field->name, len) == 0
1284                                     && field->name[len] == '\0')
1285                                         break;
1286                         }
1287                         if (index == num) {
1288                                 error = ENOENT;
1289                                 goto done;
1290                         }
1291                         *off += len;
1292
1293                         /* Get equals sign */
1294                         if (ng_parse_get_token(s, off, &len) != T_EQUALS) {
1295                                 error = EINVAL;
1296                                 goto done;
1297                         }
1298                         *off += len;
1299                 }
1300 gotIndex:
1301
1302                 /* Check array index */
1303                 if (index >= num) {
1304                         error = E2BIG;
1305                         goto done;
1306                 }
1307
1308                 /* Save value's position and skip over it for now */
1309                 if (foff[index] != 0) {
1310                         error = EALREADY;               /* duplicate */
1311                         goto done;
1312                 }
1313                 while (isspace(s[*off]))
1314                         (*off)++;
1315                 foff[index] = *off;
1316                 if ((error = ng_parse_skip_value(s, *off, &len)) != 0)
1317                         goto done;
1318                 *off += len;
1319         }
1320
1321         /* Now build binary structure from supplied values and defaults */
1322         for (blen = index = 0; index < num; index++) {
1323                 const struct ng_parse_type *const
1324                     etype = ng_get_composite_etype(type, index, ctype);
1325                 int k, pad, vlen;
1326
1327                 /* Zero-pad any alignment bytes */
1328                 pad = ng_parse_get_elem_pad(type, index, ctype, blen);
1329                 for (k = 0; k < pad; k++) {
1330                         if (blen >= *buflen) {
1331                                 error = ERANGE;
1332                                 goto done;
1333                         }
1334                         buf[blen++] = 0;
1335                 }
1336
1337                 /* Get value */
1338                 vlen = *buflen - blen;
1339                 if (foff[index] == 0) {         /* use default value */
1340                         error = ng_get_composite_elem_default(type, index,
1341                             start, buf + blen, &vlen, ctype);
1342                 } else {                        /* parse given value */
1343                         *off = foff[index];
1344                         error = INVOKE(etype, parse)(etype,
1345                             s, off, start, buf + blen, &vlen);
1346                 }
1347                 if (error != 0)
1348                         goto done;
1349                 blen += vlen;
1350         }
1351
1352         /* Make total composite structure size a multiple of its alignment */
1353         if ((align = ALIGNMENT(type)) != 0) {
1354                 while (blen % align != 0) {
1355                         if (blen >= *buflen) {
1356                                 error = ERANGE;
1357                                 goto done;
1358                         }
1359                         buf[blen++] = 0;
1360                 }
1361         }
1362
1363         /* Done */
1364         *buflen = blen;
1365 done:
1366         if (foff != NULL)
1367                 free(foff, M_NETGRAPH_PARSE);
1368         return (error);
1369 }
1370
1371 /*
1372  * Convert an array or structure from binary to ASCII
1373  */
1374 static int
1375 ng_unparse_composite(const struct ng_parse_type *type, const u_char *data,
1376         int *off, char *cbuf, int cbuflen, const enum comptype ctype)
1377 {
1378         const struct ng_mesg *const hdr
1379             = (const struct ng_mesg *)(data - sizeof(*hdr));
1380         const int num = ng_get_composite_len(type, data, data + *off, ctype);
1381         const int workSize = 20 * 1024;         /* XXX hard coded constant */
1382         int nextIndex = 0, didOne = 0;
1383         int error, index;
1384         u_char *workBuf;
1385
1386         /* Get workspace for checking default values */
1387         workBuf = malloc(workSize, M_NETGRAPH_PARSE, M_NOWAIT);
1388         if (workBuf == NULL)
1389                 return (ENOMEM);
1390
1391         /* Opening brace/bracket */
1392         if ((error = ng_parse_append(&cbuf, &cbuflen, "%c",
1393             (ctype == CT_STRUCT) ? '{' : '[')) != 0)
1394                 goto fail;
1395
1396         /* Do each item */
1397         for (index = 0; index < num; index++) {
1398                 const struct ng_parse_type *const
1399                     etype = ng_get_composite_etype(type, index, ctype);
1400
1401                 /* Skip any alignment pad bytes */
1402                 *off += ng_parse_get_elem_pad(type, index, ctype, *off);
1403
1404                 /*
1405                  * See if element is equal to its default value; skip if so.
1406                  * Copy struct ng_mesg header for types that peek into it.
1407                  */
1408                 if (sizeof(*hdr) + *off < workSize) {
1409                         int tempsize = workSize - sizeof(*hdr) - *off;
1410
1411                         bcopy(hdr, workBuf, sizeof(*hdr) + *off);
1412                         if (ng_get_composite_elem_default(type, index, workBuf
1413                               + sizeof(*hdr), workBuf + sizeof(*hdr) + *off,
1414                               &tempsize, ctype) == 0
1415                             && bcmp(workBuf + sizeof(*hdr) + *off,
1416                               data + *off, tempsize) == 0) {
1417                                 *off += tempsize;
1418                                 continue;
1419                         }
1420                 }
1421
1422                 /* Print name= */
1423                 if ((error = ng_parse_append(&cbuf, &cbuflen, " ")) != 0)
1424                         goto fail;
1425                 if (ctype != CT_STRUCT) {
1426                         if (index != nextIndex) {
1427                                 nextIndex = index;
1428                                 if ((error = ng_parse_append(&cbuf,
1429                                     &cbuflen, "%d=", index)) != 0)
1430                                         goto fail;
1431                         }
1432                         nextIndex++;
1433                 } else {
1434                         const struct ng_parse_struct_field *const
1435                             fields = type->info;
1436
1437                         if ((error = ng_parse_append(&cbuf,
1438                             &cbuflen, "%s=", fields[index].name)) != 0)
1439                                 goto fail;
1440                 }
1441
1442                 /* Print value */
1443                 if ((error = INVOKE(etype, unparse)
1444                     (etype, data, off, cbuf, cbuflen)) != 0) {
1445                         free(workBuf, M_NETGRAPH_PARSE);
1446                         return (error);
1447                 }
1448                 cbuflen -= strlen(cbuf);
1449                 cbuf += strlen(cbuf);
1450                 didOne = 1;
1451         }
1452
1453         /* Closing brace/bracket */
1454         error = ng_parse_append(&cbuf, &cbuflen, "%s%c",
1455             didOne ? " " : "", (ctype == CT_STRUCT) ? '}' : ']');
1456
1457 fail:
1458         /* Clean up after failure */
1459         free(workBuf, M_NETGRAPH_PARSE);
1460         return (error);
1461 }
1462
1463 /*
1464  * Generate the default value for an element of an array or structure
1465  * Returns EOPNOTSUPP if default value is unspecified.
1466  */
1467 static int
1468 ng_get_composite_elem_default(const struct ng_parse_type *type,
1469         int index, const u_char *const start, u_char *buf, int *buflen,
1470         const enum comptype ctype)
1471 {
1472         const struct ng_parse_type *etype;
1473         ng_getDefault_t *func;
1474
1475         switch (ctype) {
1476         case CT_STRUCT:
1477                 break;
1478         case CT_ARRAY:
1479             {
1480                 const struct ng_parse_array_info *const ai = type->info;
1481
1482                 if (ai->getDefault != NULL) {
1483                         return (*ai->getDefault)(type,
1484                             index, start, buf, buflen);
1485                 }
1486                 break;
1487             }
1488         case CT_FIXEDARRAY:
1489             {
1490                 const struct ng_parse_fixedarray_info *const fi = type->info;
1491
1492                 if (*fi->getDefault != NULL) {
1493                         return (*fi->getDefault)(type,
1494                             index, start, buf, buflen);
1495                 }
1496                 break;
1497             }
1498         default:
1499             panic("%s", __func__);
1500         }
1501
1502         /* Default to element type default */
1503         etype = ng_get_composite_etype(type, index, ctype);
1504         func = METHOD(etype, getDefault);
1505         if (func == NULL)
1506                 return (EOPNOTSUPP);
1507         return (*func)(etype, start, buf, buflen);
1508 }
1509
1510 /*
1511  * Get the number of elements in a struct, variable or fixed array.
1512  */
1513 static int
1514 ng_get_composite_len(const struct ng_parse_type *type,
1515         const u_char *const start, const u_char *buf,
1516         const enum comptype ctype)
1517 {
1518         switch (ctype) {
1519         case CT_STRUCT:
1520             {
1521                 const struct ng_parse_struct_field *const fields = type->info;
1522                 int numFields = 0;
1523
1524                 for (numFields = 0; ; numFields++) {
1525                         const struct ng_parse_struct_field *const
1526                                 fi = &fields[numFields];
1527
1528                         if (fi->name == NULL)
1529                                 break;
1530                 }
1531                 return (numFields);
1532             }
1533         case CT_ARRAY:
1534             {
1535                 const struct ng_parse_array_info *const ai = type->info;
1536
1537                 return (*ai->getLength)(type, start, buf);
1538             }
1539         case CT_FIXEDARRAY:
1540             {
1541                 const struct ng_parse_fixedarray_info *const fi = type->info;
1542
1543                 return fi->length;
1544             }
1545         default:
1546             panic("%s", __func__);
1547         }
1548         return (0);
1549 }
1550
1551 /*
1552  * Return the type of the index'th element of a composite structure
1553  */
1554 static const struct ng_parse_type *
1555 ng_get_composite_etype(const struct ng_parse_type *type,
1556         int index, const enum comptype ctype)
1557 {
1558         const struct ng_parse_type *etype = NULL;
1559
1560         switch (ctype) {
1561         case CT_STRUCT:
1562             {
1563                 const struct ng_parse_struct_field *const fields = type->info;
1564
1565                 etype = fields[index].type;
1566                 break;
1567             }
1568         case CT_ARRAY:
1569             {
1570                 const struct ng_parse_array_info *const ai = type->info;
1571
1572                 etype = ai->elementType;
1573                 break;
1574             }
1575         case CT_FIXEDARRAY:
1576             {
1577                 const struct ng_parse_fixedarray_info *const fi = type->info;
1578
1579                 etype = fi->elementType;
1580                 break;
1581             }
1582         default:
1583             panic("%s", __func__);
1584         }
1585         return (etype);
1586 }
1587
1588 /*
1589  * Get the number of bytes to skip to align for the next
1590  * element in a composite structure.
1591  */
1592 static int
1593 ng_parse_get_elem_pad(const struct ng_parse_type *type,
1594         int index, enum comptype ctype, int posn)
1595 {
1596         const struct ng_parse_type *const
1597             etype = ng_get_composite_etype(type, index, ctype);
1598         int align;
1599
1600         /* Get element's alignment, and possibly override */
1601         align = ALIGNMENT(etype);
1602         if (ctype == CT_STRUCT) {
1603                 const struct ng_parse_struct_field *const fields = type->info;
1604
1605                 if (fields[index].alignment != 0)
1606                         align = fields[index].alignment;
1607         }
1608
1609         /* Return number of bytes to skip to align */
1610         return (align ? (align - (posn % align)) % align : 0);
1611 }
1612
1613 /************************************************************************
1614                         PARSING HELPER ROUTINES
1615  ************************************************************************/
1616
1617 /*
1618  * Append to a fixed length string buffer.
1619  */
1620 static int
1621 ng_parse_append(char **cbufp, int *cbuflenp, const char *fmt, ...)
1622 {
1623         va_list args;
1624         int len;
1625
1626         va_start(args, fmt);
1627         len = vsnprintf(*cbufp, *cbuflenp, fmt, args);
1628         va_end(args);
1629         if (len >= *cbuflenp)
1630                 return ERANGE;
1631         *cbufp += len;
1632         *cbuflenp -= len;
1633
1634         return (0);
1635 }
1636
1637 /*
1638  * Skip over a value
1639  */
1640 static int
1641 ng_parse_skip_value(const char *s, int off0, int *lenp)
1642 {
1643         int len, nbracket, nbrace;
1644         int off = off0;
1645
1646         len = nbracket = nbrace = 0;
1647         do {
1648                 switch (ng_parse_get_token(s, &off, &len)) {
1649                 case T_LBRACKET:
1650                         nbracket++;
1651                         break;
1652                 case T_LBRACE:
1653                         nbrace++;
1654                         break;
1655                 case T_RBRACKET:
1656                         if (nbracket-- == 0)
1657                                 return (EINVAL);
1658                         break;
1659                 case T_RBRACE:
1660                         if (nbrace-- == 0)
1661                                 return (EINVAL);
1662                         break;
1663                 case T_EOF:
1664                         return (EINVAL);
1665                 default:
1666                         break;
1667                 }
1668                 off += len;
1669         } while (nbracket > 0 || nbrace > 0);
1670         *lenp = off - off0;
1671         return (0);
1672 }
1673
1674 /*
1675  * Find the next token in the string, starting at offset *startp.
1676  * Returns the token type, with *startp pointing to the first char
1677  * and *lenp the length.
1678  */
1679 enum ng_parse_token
1680 ng_parse_get_token(const char *s, int *startp, int *lenp)
1681 {
1682         char *t;
1683         int i;
1684
1685         while (isspace(s[*startp]))
1686                 (*startp)++;
1687         switch (s[*startp]) {
1688         case '\0':
1689                 *lenp = 0;
1690                 return T_EOF;
1691         case '{':
1692                 *lenp = 1;
1693                 return T_LBRACE;
1694         case '}':
1695                 *lenp = 1;
1696                 return T_RBRACE;
1697         case '[':
1698                 *lenp = 1;
1699                 return T_LBRACKET;
1700         case ']':
1701                 *lenp = 1;
1702                 return T_RBRACKET;
1703         case '=':
1704                 *lenp = 1;
1705                 return T_EQUALS;
1706         case '"':
1707                 if ((t = ng_get_string_token(s, startp, lenp, NULL)) == NULL)
1708                         return T_ERROR;
1709                 free(t, M_NETGRAPH_PARSE);
1710                 return T_STRING;
1711         default:
1712                 for (i = *startp + 1; s[i] != '\0' && !isspace(s[i])
1713                     && s[i] != '{' && s[i] != '}' && s[i] != '['
1714                     && s[i] != ']' && s[i] != '=' && s[i] != '"'; i++)
1715                         ;
1716                 *lenp = i - *startp;
1717                 return T_WORD;
1718         }
1719 }
1720
1721 /*
1722  * Get a string token, which must be enclosed in double quotes.
1723  * The normal C backslash escapes are recognized.
1724  */
1725 char *
1726 ng_get_string_token(const char *s, int *startp, int *lenp, int *slenp)
1727 {
1728         char *cbuf, *p;
1729         int start, off;
1730         int slen;
1731
1732         while (isspace(s[*startp]))
1733                 (*startp)++;
1734         start = *startp;
1735         if (s[*startp] != '"')
1736                 return (NULL);
1737         cbuf = malloc(strlen(s + start), M_NETGRAPH_PARSE, M_NOWAIT);
1738         if (cbuf == NULL)
1739                 return (NULL);
1740         strcpy(cbuf, s + start + 1);
1741         for (slen = 0, off = 1, p = cbuf; *p != '\0'; slen++, off++, p++) {
1742                 if (*p == '"') {
1743                         *p = '\0';
1744                         *lenp = off + 1;
1745                         if (slenp != NULL)
1746                                 *slenp = slen;
1747                         return (cbuf);
1748                 } else if (p[0] == '\\' && p[1] != '\0') {
1749                         int x, k;
1750                         char *v;
1751
1752                         strcpy(p, p + 1);
1753                         v = p;
1754                         switch (*p) {
1755                         case 't':
1756                                 *v = '\t';
1757                                 off++;
1758                                 continue;
1759                         case 'n':
1760                                 *v = '\n';
1761                                 off++;
1762                                 continue;
1763                         case 'r':
1764                                 *v = '\r';
1765                                 off++;
1766                                 continue;
1767                         case 'v':
1768                                 *v =  '\v';
1769                                 off++;
1770                                 continue;
1771                         case 'f':
1772                                 *v =  '\f';
1773                                 off++;
1774                                 continue;
1775                         case '"':
1776                                 *v =  '"';
1777                                 off++;
1778                                 continue;
1779                         case '0': case '1': case '2': case '3':
1780                         case '4': case '5': case '6': case '7':
1781                                 for (x = k = 0;
1782                                     k < 3 && *v >= '0' && *v <= '7'; v++) {
1783                                         x = (x << 3) + (*v - '0');
1784                                         off++;
1785                                 }
1786                                 *--v = (char)x;
1787                                 break;
1788                         case 'x':
1789                                 for (v++, x = k = 0;
1790                                     k < 2 && isxdigit(*v); v++) {
1791                                         x = (x << 4) + (isdigit(*v) ?
1792                                               (*v - '0') :
1793                                               (tolower(*v) - 'a' + 10));
1794                                         off++;
1795                                 }
1796                                 *--v = (char)x;
1797                                 break;
1798                         default:
1799                                 continue;
1800                         }
1801                         strcpy(p, v);
1802                 }
1803         }
1804         free(cbuf, M_NETGRAPH_PARSE);
1805         return (NULL);          /* no closing quote */
1806 }
1807
1808 /*
1809  * Encode a string so it can be safely put in double quotes.
1810  * Caller must free the result. Exactly "slen" characters
1811  * are encoded.
1812  */
1813 char *
1814 ng_encode_string(const char *raw, int slen)
1815 {
1816         char *cbuf;
1817         int off = 0;
1818         int i;
1819
1820         cbuf = malloc(strlen(raw) * 4 + 3, M_NETGRAPH_PARSE, M_NOWAIT);
1821         if (cbuf == NULL)
1822                 return (NULL);
1823         cbuf[off++] = '"';
1824         for (i = 0; i < slen; i++, raw++) {
1825                 switch (*raw) {
1826                 case '\t':
1827                         cbuf[off++] = '\\';
1828                         cbuf[off++] = 't';
1829                         break;
1830                 case '\f':
1831                         cbuf[off++] = '\\';
1832                         cbuf[off++] = 'f';
1833                         break;
1834                 case '\n':
1835                         cbuf[off++] = '\\';
1836                         cbuf[off++] = 'n';
1837                         break;
1838                 case '\r':
1839                         cbuf[off++] = '\\';
1840                         cbuf[off++] = 'r';
1841                         break;
1842                 case '\v':
1843                         cbuf[off++] = '\\';
1844                         cbuf[off++] = 'v';
1845                         break;
1846                 case '"':
1847                 case '\\':
1848                         cbuf[off++] = '\\';
1849                         cbuf[off++] = *raw;
1850                         break;
1851                 default:
1852                         if (*raw < 0x20 || *raw > 0x7e) {
1853                                 off += sprintf(cbuf + off,
1854                                     "\\x%02x", (u_char)*raw);
1855                                 break;
1856                         }
1857                         cbuf[off++] = *raw;
1858                         break;
1859                 }
1860         }
1861         cbuf[off++] = '"';
1862         cbuf[off] = '\0';
1863         return (cbuf);
1864 }
1865
1866 /************************************************************************
1867                         VIRTUAL METHOD LOOKUP
1868  ************************************************************************/
1869
1870 static ng_parse_t *
1871 ng_get_parse_method(const struct ng_parse_type *t)
1872 {
1873         while (t != NULL && t->parse == NULL)
1874                 t = t->supertype;
1875         return (t ? t->parse : NULL);
1876 }
1877
1878 static ng_unparse_t *
1879 ng_get_unparse_method(const struct ng_parse_type *t)
1880 {
1881         while (t != NULL && t->unparse == NULL)
1882                 t = t->supertype;
1883         return (t ? t->unparse : NULL);
1884 }
1885
1886 static ng_getDefault_t *
1887 ng_get_getDefault_method(const struct ng_parse_type *t)
1888 {
1889         while (t != NULL && t->getDefault == NULL)
1890                 t = t->supertype;
1891         return (t ? t->getDefault : NULL);
1892 }
1893
1894 static ng_getAlign_t *
1895 ng_get_getAlign_method(const struct ng_parse_type *t)
1896 {
1897         while (t != NULL && t->getAlign == NULL)
1898                 t = t->supertype;
1899         return (t ? t->getAlign : NULL);
1900 }