Imported Upstream version 2.2.37
[platform/upstream/gpg2.git] / common / name-value.c
1 /* name-value.c - Parser and writer for a name-value format.
2  *      Copyright (C) 2016 g10 Code GmbH
3  *
4  * This file is part of GnuPG.
5  *
6  * This file is free software; you can redistribute it and/or modify
7  * it under the terms of either
8  *
9  *   - the GNU Lesser General Public License as published by the Free
10  *     Software Foundation; either version 3 of the License, or (at
11  *     your option) any later version.
12  *
13  * or
14  *
15  *   - the GNU General Public License as published by the Free
16  *     Software Foundation; either version 2 of the License, or (at
17  *     your option) any later version.
18  *
19  * or both in parallel, as here.
20  *
21  * GnuPG is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program; if not, see <https://www.gnu.org/licenses/>.
28  */
29
30 /*
31  * This module aso provides features for the extended private key
32  * format of gpg-agent.
33  */
34
35 #include <config.h>
36 #include <assert.h>
37 #include <gcrypt.h>
38 #include <gpg-error.h>
39 #include <string.h>
40
41 #include "mischelp.h"
42 #include "strlist.h"
43 #include "util.h"
44 #include "name-value.h"
45
46 struct name_value_container
47 {
48   struct name_value_entry *first;
49   struct name_value_entry *last;
50   unsigned int private_key_mode:1;
51 };
52
53
54 struct name_value_entry
55 {
56   struct name_value_entry *prev;
57   struct name_value_entry *next;
58
59   /* The name.  Comments and blank lines have NAME set to NULL.  */
60   char *name;
61
62   /* The value as stored in the file.  We store it when we parse
63      a file so that we can reproduce it.  */
64   strlist_t raw_value;
65
66   /* The decoded value.  */
67   char *value;
68 };
69
70
71 /* Helper */
72 static inline gpg_error_t
73 my_error_from_syserror (void)
74 {
75   return gpg_err_make (default_errsource, gpg_err_code_from_syserror ());
76 }
77
78
79 static inline gpg_error_t
80 my_error (gpg_err_code_t ec)
81 {
82   return gpg_err_make (default_errsource, ec);
83 }
84
85
86 \f
87
88 /* Allocation and deallocation.  */
89
90 /* Allocate a private key container structure.  */
91 nvc_t
92 nvc_new (void)
93 {
94   return xtrycalloc (1, sizeof (struct name_value_container));
95 }
96
97
98 /* Allocate a private key container structure for use with private keys.  */
99 nvc_t
100 nvc_new_private_key (void)
101 {
102   nvc_t nvc = nvc_new ();
103   if (nvc)
104     nvc->private_key_mode = 1;
105   return nvc;
106 }
107
108
109 static void
110 nve_release (nve_t entry, int private_key_mode)
111 {
112   if (entry == NULL)
113     return;
114
115   xfree (entry->name);
116   if (entry->value && private_key_mode)
117     wipememory (entry->value, strlen (entry->value));
118   xfree (entry->value);
119   if (private_key_mode)
120     free_strlist_wipe (entry->raw_value);
121   else
122     free_strlist (entry->raw_value);
123   xfree (entry);
124 }
125
126
127 /* Release a private key container structure.  */
128 void
129 nvc_release (nvc_t pk)
130 {
131   nve_t e, next;
132
133   if (pk == NULL)
134     return;
135
136   for (e = pk->first; e; e = next)
137     {
138       next = e->next;
139       nve_release (e, pk->private_key_mode);
140     }
141
142   xfree (pk);
143 }
144
145 \f
146
147 /* Dealing with names and values.  */
148
149 /* Check whether the given name is valid.  Valid names start with a
150    letter, end with a colon, and contain only alphanumeric characters
151    and the hyphen.  */
152 static int
153 valid_name (const char *name)
154 {
155   size_t i, len = strlen (name);
156
157   if (! alphap (name) || len == 0 || name[len - 1] != ':')
158     return 0;
159
160   for (i = 1; i < len - 1; i++)
161     if (! alnump (&name[i]) && name[i] != '-')
162       return 0;
163
164   return 1;
165 }
166
167
168 /* Makes sure that ENTRY has a RAW_VALUE.  */
169 static gpg_error_t
170 assert_raw_value (nve_t entry)
171 {
172   gpg_error_t err = 0;
173   size_t len, offset;
174 #define LINELEN 70
175   char buf[LINELEN+3];
176
177   if (entry->raw_value)
178     return 0;
179
180   len = strlen (entry->value);
181   offset = 0;
182   while (len)
183     {
184       size_t amount, linelen = LINELEN;
185
186       /* On the first line we need to subtract space for the name.  */
187       if (entry->raw_value == NULL && strlen (entry->name) < linelen)
188         linelen -= strlen (entry->name);
189
190       /* See if the rest of the value fits in this line.  */
191       if (len <= linelen)
192         amount = len;
193       else
194         {
195           size_t i;
196
197           /* Find a suitable space to break on.  */
198           for (i = linelen - 1; linelen - i < 30; i--)
199             if (ascii_isspace (entry->value[offset+i]))
200               break;
201
202           if (ascii_isspace (entry->value[offset+i]))
203             {
204               /* Found one.  */
205               amount = i;
206             }
207           else
208             {
209               /* Just induce a hard break.  */
210               amount = linelen;
211             }
212         }
213
214       snprintf (buf, sizeof buf, " %.*s\n", (int) amount,
215                 &entry->value[offset]);
216       if (append_to_strlist_try (&entry->raw_value, buf) == NULL)
217         {
218           err = my_error_from_syserror ();
219           goto leave;
220         }
221
222       offset += amount;
223       len -= amount;
224     }
225
226  leave:
227   if (err)
228     {
229       free_strlist_wipe (entry->raw_value);
230       entry->raw_value = NULL;
231     }
232
233   return err;
234 #undef LINELEN
235 }
236
237
238 /* Computes the length of the value encoded as continuation.  If
239    *SWALLOW_WS is set, all whitespace at the beginning of S is
240    swallowed.  If START is given, a pointer to the beginning of the
241    value is stored there.  */
242 static size_t
243 continuation_length (const char *s, int *swallow_ws, const char **start)
244 {
245   size_t len;
246
247   if (*swallow_ws)
248     {
249       /* The previous line was a blank line and we inserted a newline.
250          Swallow all whitespace at the beginning of this line.  */
251       while (ascii_isspace (*s))
252         s++;
253     }
254   else
255     {
256       /* Iff a continuation starts with more than one space, it
257          encodes a space.  */
258       if (ascii_isspace (*s))
259         s++;
260     }
261
262   /* Strip whitespace at the end.  */
263   len = strlen (s);
264   while (len > 0 && ascii_isspace (s[len-1]))
265     len--;
266
267   if (len == 0)
268     {
269       /* Blank lines encode newlines.  */
270       len = 1;
271       s = "\n";
272       *swallow_ws = 1;
273     }
274   else
275     *swallow_ws = 0;
276
277   if (start)
278     *start = s;
279
280   return len;
281 }
282
283
284 /* Makes sure that ENTRY has a VALUE.  */
285 static gpg_error_t
286 assert_value (nve_t entry)
287 {
288   size_t len;
289   int swallow_ws;
290   strlist_t s;
291   char *p;
292
293   if (entry->value)
294     return 0;
295
296   len = 0;
297   swallow_ws = 0;
298   for (s = entry->raw_value; s; s = s->next)
299     len += continuation_length (s->d, &swallow_ws, NULL);
300
301   /* Add one for the terminating zero.  */
302   len += 1;
303
304   entry->value = p = xtrymalloc (len);
305   if (entry->value == NULL)
306     return my_error_from_syserror ();
307
308   swallow_ws = 0;
309   for (s = entry->raw_value; s; s = s->next)
310     {
311       const char *start;
312       size_t l = continuation_length (s->d, &swallow_ws, &start);
313
314       memcpy (p, start, l);
315       p += l;
316     }
317
318   *p++ = 0;
319   assert (p - entry->value == len);
320
321   return 0;
322 }
323
324
325 /* Get the name.  */
326 char *
327 nve_name (nve_t pke)
328 {
329   return pke->name;
330 }
331
332
333 /* Get the value.  */
334 char *
335 nve_value (nve_t pke)
336 {
337   if (assert_value (pke))
338     return NULL;
339   return pke->value;
340 }
341
342 \f
343
344 /* Adding and modifying values.  */
345
346 /* Add (NAME, VALUE, RAW_VALUE) to PK.  NAME may be NULL for comments
347    and blank lines.  At least one of VALUE and RAW_VALUE must be
348    given.  If PRESERVE_ORDER is not given, entries with the same name
349    are grouped.  NAME, VALUE and RAW_VALUE is consumed.  */
350 static gpg_error_t
351 _nvc_add (nvc_t pk, char *name, char *value, strlist_t raw_value,
352           int preserve_order)
353 {
354   gpg_error_t err = 0;
355   nve_t e;
356
357   assert (value || raw_value);
358
359   if (name && ! valid_name (name))
360     {
361       err = my_error (GPG_ERR_INV_NAME);
362       goto leave;
363     }
364
365   if (name
366       && pk->private_key_mode
367       && !ascii_strcasecmp (name, "Key:")
368       && nvc_lookup (pk, "Key:"))
369     {
370       err = my_error (GPG_ERR_INV_NAME);
371       goto leave;
372     }
373
374   e = xtrycalloc (1, sizeof *e);
375   if (e == NULL)
376     {
377       err = my_error_from_syserror ();
378       goto leave;
379     }
380
381   e->name = name;
382   e->value = value;
383   e->raw_value = raw_value;
384
385   if (pk->first)
386     {
387       nve_t last;
388
389       if (preserve_order || name == NULL)
390         last = pk->last;
391       else
392         {
393           /* See if there is already an entry with NAME.  */
394           last = nvc_lookup (pk, name);
395
396           /* If so, find the last in that block.  */
397           if (last)
398             {
399               while (last->next)
400                 {
401                   nve_t next = last->next;
402
403                   if (next->name && ascii_strcasecmp (next->name, name) == 0)
404                     last = next;
405                   else
406                     break;
407                 }
408             }
409           else /* Otherwise, just find the last entry.  */
410             last = pk->last;
411         }
412
413       if (last->next)
414         {
415           e->prev = last;
416           e->next = last->next;
417           last->next = e;
418           e->next->prev = e;
419         }
420       else
421         {
422           e->prev = last;
423           last->next = e;
424           pk->last = e;
425         }
426     }
427   else
428     pk->first = pk->last = e;
429
430  leave:
431   if (err)
432     {
433       xfree (name);
434       if (value)
435         wipememory (value, strlen (value));
436       xfree (value);
437       free_strlist_wipe (raw_value);
438     }
439
440   return err;
441 }
442
443
444 /* Add (NAME, VALUE) to PK.  If an entry with NAME already exists, it
445    is not updated but the new entry is appended.  */
446 gpg_error_t
447 nvc_add (nvc_t pk, const char *name, const char *value)
448 {
449   char *k, *v;
450
451   k = xtrystrdup (name);
452   if (k == NULL)
453     return my_error_from_syserror ();
454
455   v = xtrystrdup (value);
456   if (v == NULL)
457     {
458       xfree (k);
459       return my_error_from_syserror ();
460     }
461
462   return _nvc_add (pk, k, v, NULL, 0);
463 }
464
465
466 /* Add (NAME, VALUE) to PK.  If an entry with NAME already exists, it
467    is updated with VALUE.  If multiple entries with NAME exist, the
468    first entry is updated.  */
469 gpg_error_t
470 nvc_set (nvc_t pk, const char *name, const char *value)
471 {
472   nve_t e;
473
474   if (! valid_name (name))
475     return GPG_ERR_INV_NAME;
476
477   e = nvc_lookup (pk, name);
478   if (e)
479     return nve_set (e, value);
480   else
481     return nvc_add (pk, name, value);
482 }
483
484
485 /* Update entry E to VALUE.  */
486 gpg_error_t
487 nve_set (nve_t e, const char *value)
488 {
489   char *v;
490
491   if (!e)
492     return GPG_ERR_INV_ARG;
493
494   v = xtrystrdup (value? value:"");
495   if (!v)
496     return my_error_from_syserror ();
497
498   free_strlist_wipe (e->raw_value);
499   e->raw_value = NULL;
500   if (e->value)
501     wipememory (e->value, strlen (e->value));
502   xfree (e->value);
503   e->value = v;
504
505   return 0;
506 }
507
508
509 /* Delete the given entry from PK.  */
510 void
511 nvc_delete (nvc_t pk, nve_t entry)
512 {
513   if (entry->prev)
514     entry->prev->next = entry->next;
515   else
516     pk->first = entry->next;
517
518   if (entry->next)
519     entry->next->prev = entry->prev;
520   else
521     pk->last = entry->prev;
522
523   nve_release (entry, pk->private_key_mode);
524 }
525
526 /* Delete the entries with NAME from PK.  */
527 void
528 nvc_delete_named (nvc_t pk, const char *name)
529 {
530   nve_t e;
531
532   if (!valid_name (name))
533     return;
534
535   while ((e = nvc_lookup (pk, name)))
536     nvc_delete (pk, e);
537 }
538
539
540 \f
541
542 /* Lookup and iteration.  */
543
544 /* Get the first non-comment entry.  */
545 nve_t
546 nvc_first (nvc_t pk)
547 {
548   nve_t entry;
549   for (entry = pk->first; entry; entry = entry->next)
550     if (entry->name)
551       return entry;
552   return NULL;
553 }
554
555
556 /* Get the first entry with the given name.  */
557 nve_t
558 nvc_lookup (nvc_t pk, const char *name)
559 {
560   nve_t entry;
561   for (entry = pk->first; entry; entry = entry->next)
562     if (entry->name && ascii_strcasecmp (entry->name, name) == 0)
563       return entry;
564   return NULL;
565 }
566
567
568 /* Get the next non-comment entry.  */
569 nve_t
570 nve_next (nve_t entry)
571 {
572   for (entry = entry->next; entry; entry = entry->next)
573     if (entry->name)
574       return entry;
575   return NULL;
576 }
577
578
579 /* Get the next entry with the given name.  */
580 nve_t
581 nve_next_value (nve_t entry, const char *name)
582 {
583   for (entry = entry->next; entry; entry = entry->next)
584     if (entry->name && ascii_strcasecmp (entry->name, name) == 0)
585       return entry;
586   return NULL;
587 }
588
589
590 /* Return the string for the first entry in NVC with NAME.  If an
591  * entry with NAME is missing in NVC or its value is the empty string
592  * NULL is returned.  Note that the returned string is a pointer
593  * into NVC.  */
594 const char *
595 nvc_get_string (nvc_t nvc, const char *name)
596 {
597   nve_t item;
598
599   if (!nvc)
600     return NULL;
601   item = nvc_lookup (nvc, name);
602   if (!item)
603     return NULL;
604   return nve_value (item);
605 }
606
607
608 /* Return true if NAME exists and its value is true; that is either
609  * "yes", "true", or a decimal value unequal to 0.  */
610 int
611 nvc_get_boolean (nvc_t nvc, const char *name)
612 {
613   nve_t item;
614   const char *s;
615
616   if (!nvc)
617     return 0;
618   item = nvc_lookup (nvc, name);
619   if (!item)
620     return 0;
621   s = nve_value (item);
622   if (s && (atoi (s)
623             || !ascii_strcasecmp (s, "yes")
624             || !ascii_strcasecmp (s, "true")))
625     return 1;
626   return 0;
627 }
628
629 \f
630
631 /* Private key handling.  */
632
633 /* Get the private key.  */
634 gpg_error_t
635 nvc_get_private_key (nvc_t pk, gcry_sexp_t *retsexp)
636 {
637   gpg_error_t err;
638   nve_t e;
639
640   e = pk->private_key_mode? nvc_lookup (pk, "Key:") : NULL;
641   if (e == NULL)
642     return my_error (GPG_ERR_MISSING_KEY);
643
644   err = assert_value (e);
645   if (err)
646     return err;
647
648   return gcry_sexp_sscan (retsexp, NULL, e->value, strlen (e->value));
649 }
650
651
652 /* Set the private key.  */
653 gpg_error_t
654 nvc_set_private_key (nvc_t pk, gcry_sexp_t sexp)
655 {
656   gpg_error_t err;
657   char *raw, *clean, *p;
658   size_t len, i;
659
660   if (!pk->private_key_mode)
661     return my_error (GPG_ERR_MISSING_KEY);
662
663   len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_ADVANCED, NULL, 0);
664
665   raw = xtrymalloc (len);
666   if (raw == NULL)
667     return my_error_from_syserror ();
668
669   clean = xtrymalloc (len);
670   if (clean == NULL)
671     {
672       xfree (raw);
673       return my_error_from_syserror ();
674     }
675
676   gcry_sexp_sprint (sexp, GCRYSEXP_FMT_ADVANCED, raw, len);
677
678   /* Strip any whitespace at the end.  */
679   i = strlen (raw) - 1;
680   while (i && ascii_isspace (raw[i]))
681     {
682       raw[i] = 0;
683       i--;
684     }
685
686   /* Replace any newlines with spaces, remove superfluous whitespace.  */
687   len = strlen (raw);
688   for (p = clean, i = 0; i < len; i++)
689     {
690       char c = raw[i];
691
692       /* Collapse contiguous and superfluous spaces.  */
693       if (ascii_isspace (c) && i > 0
694           && (ascii_isspace (raw[i-1]) || raw[i-1] == '(' || raw[i-1] == ')'))
695         continue;
696
697       if (c == '\n')
698         c = ' ';
699
700       *p++ = c;
701     }
702   *p = 0;
703
704   err = nvc_set (pk, "Key:", clean);
705   xfree (raw);
706   xfree (clean);
707   return err;
708 }
709
710 \f
711
712 /* Parsing and serialization.  */
713
714 static gpg_error_t
715 do_nvc_parse (nvc_t *result, int *errlinep, estream_t stream,
716               int for_private_key)
717 {
718   gpg_error_t err = 0;
719   gpgrt_ssize_t len;
720   char *buf = NULL;
721   size_t buf_len = 0;
722   char *name = NULL;
723   strlist_t raw_value = NULL;
724
725   *result = for_private_key? nvc_new_private_key () : nvc_new ();
726   if (*result == NULL)
727     return my_error_from_syserror ();
728
729   if (errlinep)
730     *errlinep = 0;
731   while ((len = es_read_line (stream, &buf, &buf_len, NULL)) > 0)
732     {
733       char *p;
734       if (errlinep)
735         *errlinep += 1;
736
737       /* Skip any whitespace.  */
738       for (p = buf; *p && ascii_isspace (*p); p++)
739         /* Do nothing.  */;
740
741       if (name && (spacep (buf) || *p == 0))
742         {
743           /* A continuation.  */
744           if (append_to_strlist_try (&raw_value, buf) == NULL)
745             {
746               err = my_error_from_syserror ();
747               goto leave;
748             }
749           continue;
750         }
751
752       /* No continuation.  Add the current entry if any.  */
753       if (raw_value)
754         {
755           err = _nvc_add (*result, name, NULL, raw_value, 1);
756           name = NULL;
757           if (err)
758             goto leave;
759         }
760
761       /* And prepare for the next one.  */
762       name = NULL;
763       raw_value = NULL;
764
765       if (*p != 0 && *p != '#')
766         {
767           char *colon, *value, tmp;
768
769           colon = strchr (buf, ':');
770           if (colon == NULL)
771             {
772               err = my_error (GPG_ERR_INV_VALUE);
773               goto leave;
774             }
775
776           value = colon + 1;
777           tmp = *value;
778           *value = 0;
779           name = xtrystrdup (p);
780           *value = tmp;
781
782           if (name == NULL)
783             {
784               err = my_error_from_syserror ();
785               goto leave;
786             }
787
788           if (append_to_strlist_try (&raw_value, value) == NULL)
789             {
790               err = my_error_from_syserror ();
791               goto leave;
792             }
793           continue;
794         }
795
796       if (append_to_strlist_try (&raw_value, buf) == NULL)
797         {
798           err = my_error_from_syserror ();
799           goto leave;
800         }
801     }
802   if (len < 0)
803     {
804       err = gpg_error_from_syserror ();
805       goto leave;
806     }
807
808   /* Add the final entry.  */
809   if (raw_value)
810     err = _nvc_add (*result, name, NULL, raw_value, 1);
811
812  leave:
813   gpgrt_free (buf);
814   if (err)
815     {
816       nvc_release (*result);
817       *result = NULL;
818     }
819
820   return err;
821 }
822
823
824 /* Parse STREAM and return a newly allocated name value container
825    structure in RESULT.  If ERRLINEP is given, the line number the
826    parser was last considering is stored there.  */
827 gpg_error_t
828 nvc_parse (nvc_t *result, int *errlinep, estream_t stream)
829 {
830   return do_nvc_parse (result, errlinep, stream, 0);
831 }
832
833
834 /* Parse STREAM and return a newly allocated name value container
835    structure in RESULT - assuming the extended private key format.  If
836    ERRLINEP is given, the line number the parser was last considering
837    is stored there.  */
838 gpg_error_t
839 nvc_parse_private_key (nvc_t *result, int *errlinep, estream_t stream)
840 {
841   return do_nvc_parse (result, errlinep, stream, 1);
842 }
843
844
845 /* Helper fpr nvc_write.  */
846 static gpg_error_t
847 write_one_entry (nve_t entry, estream_t stream)
848 {
849   gpg_error_t err;
850   strlist_t sl;
851
852   if (entry->name)
853     es_fputs (entry->name, stream);
854
855   err = assert_raw_value (entry);
856   if (err)
857     return err;
858
859   for (sl = entry->raw_value; sl; sl = sl->next)
860     es_fputs (sl->d, stream);
861
862   if (es_ferror (stream))
863     return my_error_from_syserror ();
864
865   return 0;
866 }
867
868
869 /* Write a representation of PK to STREAM.  */
870 gpg_error_t
871 nvc_write (nvc_t pk, estream_t stream)
872 {
873   gpg_error_t err = 0;
874   nve_t entry;
875   nve_t keyentry = NULL;
876
877   for (entry = pk->first; entry; entry = entry->next)
878     {
879       if (pk->private_key_mode
880           && entry->name && !ascii_strcasecmp (entry->name, "Key:"))
881         {
882           if (!keyentry)
883             keyentry = entry;
884           continue;
885         }
886
887       err = write_one_entry (entry, stream);
888       if (err)
889         return err;
890     }
891
892   /* In private key mode we write the Key always last.  */
893   if (keyentry)
894     err = write_one_entry (keyentry, stream);
895
896   return err;
897 }