sexp-conv.c 30.1 KB
Newer Older
Niels Möller's avatar
Niels Möller committed
1
2
3
4
5
/* sexp-conv.c
 *
 * Conversion tool for handling the different flavours of sexp
 * syntax. */

Niels Möller's avatar
Niels Möller committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* nettle, low-level cryptographics library
 *
 * Copyright (C) 2002 Niels Mller
 *  
 * The nettle library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at your
 * option) any later version.
 * 
 * The nettle library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 * License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with the nettle library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
 * MA 02111-1307, USA.
 */

Niels Möller's avatar
Niels Möller committed
26
27
28
29
30
31
#if HAVE_CONFIG_H
# include "config.h"
#endif

#define BUG_ADDRESS "nettle-bugs@lists.lysator.liu.se"

Niels Möller's avatar
Niels Möller committed
32
33
34
35
36
#include "base16.h"
#include "base64.h"
#include "buffer.h"
#include "nettle-meta.h"

Niels Möller's avatar
Niels Möller committed
37
38
#include "getopt.h"

Niels Möller's avatar
Niels Möller committed
39
40
41
42
43
44
45
#include <assert.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

Niels Möller's avatar
Niels Möller committed
46
static void
Niels Möller's avatar
Niels Möller committed
47
48
49
50
51
52
53
die(const char *format, ...)
#if __GNUC___
     __attribute__((__format__ (__printf__,1, 2)))
     __attribute__((__noreturn__))
#endif
     ;

Niels Möller's avatar
Niels Möller committed
54
static void
Niels Möller's avatar
Niels Möller committed
55
56
57
58
59
60
61
62
63
64
die(const char *format, ...)
{
  va_list args;
  va_start(args, format);
  vfprintf(stderr, format, args);
  va_end(args);

  exit(EXIT_FAILURE);
}

Niels Möller's avatar
Niels Möller committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
static void
werror(const char *format, ...)
#if __GNUC___
     __attribute__((__format__ (__printf__,1, 2)))
     __attribute__((__noreturn__))
#endif
     ;

static void
werror(const char *format, ...)
{
  va_list args;
  va_start(args, format);
  vfprintf(stderr, format, args);
  va_end(args);

  exit(EXIT_FAILURE);
}

Niels Möller's avatar
Niels Möller committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
enum sexp_mode
  {
    SEXP_CANONICAL = 0,
    SEXP_ADVANCED = 1,
    SEXP_TRANSPORT = 2,
  };

/* Special marks in the input stream */
enum sexp_char_type
  {
    SEXP_NORMAL_CHAR = 0,
    SEXP_EOF_CHAR, SEXP_END_CHAR,
  };

enum sexp_token
  {
100
101
102
    /* Zero is used to mean "any token" in sexp_parse. */
    SEXP_STRING = 1,
    SEXP_DISPLAY, /* Constructed by sexp_parse */
Niels Möller's avatar
Niels Möller committed
103
104
    SEXP_LIST_START,
    SEXP_LIST_END,
105
106
107
108
109
110
    SEXP_EOF,

    /* The below types are internal to the input parsing. sexp-parse
     * should never return a token of this type. */
    SEXP_DISPLAY_START,
    SEXP_DISPLAY_END,
Niels Möller's avatar
Niels Möller committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    SEXP_TRANSPORT_START,
    SEXP_CODING_END,
  };


/* Input */

struct sexp_input
{
  FILE *f;

  /* Character stream, consisting of ordinary characters,
   * SEXP_EOF_CHAR, and SEXP_END_CHAR. */
  enum sexp_char_type ctype;
  uint8_t c;
  
  const struct nettle_armor *coding;

  union {
    struct base64_decode_ctx base64;
    struct base16_decode_ctx hex;
  } state;

  /* Terminator for current coding */
  uint8_t terminator;
  
  /* Type of current token */
  enum sexp_token token;
139
#if 0
Niels Möller's avatar
Niels Möller committed
140
141
  /* Current token */
  struct nettle_buffer string;
142
#endif  
Niels Möller's avatar
Niels Möller committed
143
144
145
146
147
148
149
150
};

static void
sexp_input_init(struct sexp_input *input, FILE *f)
{
  input->f = f;
  input->coding = NULL;

151
#if 0
Niels Möller's avatar
Niels Möller committed
152
  nettle_buffer_init(&input->string);
153
#endif
Niels Möller's avatar
Niels Möller committed
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
}


static void
sexp_get_raw_char(struct sexp_input *input)
{
  int c = getc(input->f);
  
  if (c < 0)
    {
      if (ferror(input->f))
	die("Read error: %s\n", strerror(errno));
      
      input->ctype = SEXP_EOF_CHAR;
    }
  else
    {
      input->ctype = SEXP_NORMAL_CHAR;
      input->c = c;
    }
}

static void
sexp_get_char(struct sexp_input *input)
{
  if (input->coding)
    for (;;)
      {
	int done;

	sexp_get_raw_char(input);
	if (input->ctype == SEXP_EOF_CHAR)
	  die("Unexpected end of file in coded data.\n");

	if (input->c == input->terminator)
	  {
	    input->ctype = SEXP_END_CHAR;
	    return;
	  }

	done = 1;

	/* Decodes in place. Should always work, when we decode one
	 * character at a time. */
	if (!input->coding->decode_update(&input->state,
					  &done, &input->c,
					  1, &input->c))
	  die("Invalid coded data.\n");
	
	if (done)
	  return;
      }
  else
    sexp_get_raw_char(input);
}

static uint8_t
sexp_next_char(struct sexp_input *input)
{
  sexp_get_char(input);
  if (input->ctype != SEXP_NORMAL_CHAR)
    die("Unexpected end of file.\n");

  return input->c;
}

static void
221
222
sexp_push_char(struct sexp_input *input,
	       struct nettle_buffer *string)
Niels Möller's avatar
Niels Möller committed
223
224
225
{
  assert(input->ctype == SEXP_NORMAL_CHAR);
    
226
  if (!NETTLE_BUFFER_PUTC(string, input->c))
Niels Möller's avatar
Niels Möller committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
    die("Virtual memory exhasuted.\n");
}

static void
sexp_input_start_coding(struct sexp_input *input,
			const struct nettle_armor *coding,
			uint8_t terminator)
{
  assert(!input->coding);
  
  input->coding = coding;
  input->coding->decode_init(&input->state);
  input->terminator = terminator;
}

static void
sexp_input_end_coding(struct sexp_input *input)
{
  assert(input->coding);

  if (!input->coding->decode_final(&input->state))
    die("Invalid coded data.\n");
  
  input->coding = NULL;
}


/* Return 0 at end-of-string */
static int
sexp_get_quoted_char(struct sexp_input *input)
{
  sexp_next_char(input);

  for (;;)
    switch (input->c)
      {
      default:
	return 1;
      case '\"':
	return 0;
      case '\\':
	sexp_next_char(input);
	
	switch (input->c)
	  {
	  case 'b': input->c = '\b'; return 1;
	  case 't': input->c = '\t'; return 1;
	  case 'n': input->c = '\n'; return 1;
	  case 'f': input->c = '\f'; return 1;
	  case 'r': input->c = '\r'; return 1;
	  case '\\': input->c = '\\'; return 1;
	  case 'o':
	  case 'x':
	    /* FIXME: Not implemnted */
	    abort();
	  case '\n':
	    if (sexp_next_char(input) == '\r')
	      sexp_next_char(input);

	    break;
	  case '\r':
	    if (sexp_next_char(input) == '\n')
	      sexp_next_char(input);

	    break;
	  }
	return 1;
      }
}


static const char
token_chars[0x80] =
  {
    /* 0, ... 0x1f */
    0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
/* SPC ! " # $ % & ' ( ) * + , - . / */
    0,0,0,0,0,0,0,0, 0,0,1,1,0,1,1,1,
 /* 0 1 2 3 4 5 6 7  8 9 : ; < = > ? */
    1,1,1,1,1,1,1,1, 1,1,1,0,0,1,0,0,
    /* @ A ... O */
    0,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,	
    /* P ...             Z [ \] ^ _ */
    1,1,1,1,1,1,1,1, 1,1,1,0,0,0,0,1,
    /* ` a, ... o */
    0,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,	
    /* p ...             z { | } ~ DEL */
    1,1,1,1,1,1,1,1, 1,1,1,0,0,0,0,0,
  };

#define TOKEN_CHAR(c) ((c) < 0x80 && token_chars[(c)])

static void
321
322
sexp_get_token_string(struct sexp_input *input,
	       struct nettle_buffer *string)
Niels Möller's avatar
Niels Möller committed
323
324
325
326
327
328
329
330
331
{
  assert(!input->coding);
  assert(input->ctype == SEXP_NORMAL_CHAR);
  
  if (!TOKEN_CHAR(input->c))
    die("Invalid token.\n");

  do
    {
332
      sexp_push_char(input, string);
Niels Möller's avatar
Niels Möller committed
333
334
      sexp_get_char(input);
    }
335
  while (input->ctype == SEXP_NORMAL_CHAR && TOKEN_CHAR(input->c));
Niels Möller's avatar
Niels Möller committed
336
  
337
  assert (string->size);
Niels Möller's avatar
Niels Möller committed
338
339
340
}

static void
341
342
sexp_get_string(struct sexp_input *input,
		struct nettle_buffer *string)
Niels Möller's avatar
Niels Möller committed
343
{
344
  nettle_buffer_reset(string);
Niels Möller's avatar
Niels Möller committed
345
346
347
348
349
350
  input->token = SEXP_STRING;
  
  switch (input->c)
    {
    case '\"':
      while (sexp_get_quoted_char(input))
351
	sexp_push_char(input, string);
Niels Möller's avatar
Niels Möller committed
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
      
      sexp_get_char(input);
      break;
      
    case '#':
      sexp_input_start_coding(input, &nettle_base16, '#');
      goto decode;

    case '|':
      sexp_input_start_coding(input, &nettle_base64, '|');

    decode:
      for (;;)
	{
	  sexp_get_char(input);
	  switch (input->ctype)
	    {
	    case SEXP_NORMAL_CHAR:
370
	      sexp_push_char(input, string);
Niels Möller's avatar
Niels Möller committed
371
372
373
374
375
376
377
378
379
380
381
382
383
	      break;
	    case SEXP_EOF_CHAR:
	      die("Unexpected end of file in coded string.\n");
	    case SEXP_END_CHAR:
	      sexp_input_end_coding(input);
	      sexp_get_char(input);
	      return;
	    }
	}

      break;

    default:
384
      sexp_get_token_string(input, string);
Niels Möller's avatar
Niels Möller committed
385
386
387
388
389
      break;
    }
}

static void
390
391
sexp_get_string_length(struct sexp_input *input, enum sexp_mode mode,
		       struct nettle_buffer *string)
Niels Möller's avatar
Niels Möller committed
392
393
{
  unsigned length;
394
395

  nettle_buffer_reset(string);
Niels Möller's avatar
Niels Möller committed
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
  input->token = SEXP_STRING;
  
  length = input->c - '0';
  
  if (!length)
    /* There must be no more digits */
    sexp_next_char(input);

  else
    {
      assert(length < 10);
      /* Get rest of digits */
      for (;;)
	{
	  sexp_next_char(input);
	  
	  if (input->c < '0' || input->c > '9')
	    break;
	  
	  /* FIXME: Check for overflow? */
	  length = length * 10 + input->c - '0';
	}
    }

  switch(input->c)
    {
    case ':':
      /* Verbatim */
      for (; length; length--)
	{
	  sexp_next_char(input);
427
	  sexp_push_char(input, string);
Niels Möller's avatar
Niels Möller committed
428
429
430
431
432
433
434
435
436
437
	}
      
      break;

    case '"':
      if (mode != SEXP_ADVANCED)
	die("Encountered quoted string in canonical mode.\n");

      for (; length; length--)
	if (sexp_get_quoted_char(input))
438
	  sexp_push_char(input, string);
Niels Möller's avatar
Niels Möller committed
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
	else
	  die("Unexpected end of string.\n");
      
      if (sexp_get_quoted_char(input))
	die("Quoted string longer than expected.\n");

      break;
      
    case '#':
      sexp_input_start_coding(input, &nettle_base16, '#');
      goto decode;

    case '|':
      sexp_input_start_coding(input, &nettle_base64, '|');

    decode:
      for (; length; length--)
	{
	  sexp_next_char(input);
458
	  sexp_push_char(input, string);
Niels Möller's avatar
Niels Möller committed
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
	}
      sexp_get_char(input);
      if (input->ctype != SEXP_END_CHAR)
	die("Coded string too long.\n");

      sexp_input_end_coding(input);
      
      break;
      
    default:
      die("Invalid string.\n");
    }

  /* Skip the ending character. */
  sexp_get_char(input);  
}

/* When called, input->c should be the first character of the current
 * token.
 *
 * When returning, input->c should be the first character of the next
 * token. */
static void
482
483
sexp_get_token(struct sexp_input *input, enum sexp_mode mode,
	       struct nettle_buffer *string)
Niels Möller's avatar
Niels Möller committed
484
485
486
487
488
489
490
491
492
493
494
{
  for(;;)
    switch(input->ctype)
      {
      case SEXP_EOF_CHAR:
	input->token = SEXP_EOF;
	return;

      case SEXP_END_CHAR:
	input->token = SEXP_CODING_END;
	sexp_input_end_coding(input);
495
	sexp_get_char(input);
Niels Möller's avatar
Niels Möller committed
496
497
498
499
500
501
502
	return;

      case SEXP_NORMAL_CHAR:
	switch(input->c)
	  {
	  case '0': case '1': case '2': case '3': case '4':
	  case '5': case '6': case '7': case '8': case '9':
503
	    sexp_get_string_length(input, mode, string);
Niels Möller's avatar
Niels Möller committed
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
	    return;
	  
	  case '(':
	    input->token = SEXP_LIST_START;
	    sexp_get_char(input);
	    return;
	  
	  case ')':
	    input->token = SEXP_LIST_END;
	    sexp_get_char(input);
	    return;

	  case '[':
	    input->token = SEXP_DISPLAY_START;
	    sexp_get_char(input);
	    return;

	  case ']':
	    input->token = SEXP_DISPLAY_END;
	    sexp_get_char(input);
	    return;

	  case '{':
	    if (mode == SEXP_CANONICAL)
	      die("Unexpected transport data in canonical mode.\n");
	    
	    sexp_input_start_coding(input, &nettle_base64, '}');
	    sexp_get_char(input);

	    input->token = SEXP_TRANSPORT_START;
	    
	    return;
	  
	  case ' ':  /* SPC, TAB, LF, CR */
	  case '\t':
	  case '\n':
	  case '\r':
	    if (mode == SEXP_CANONICAL)
	      die("Whitespace encountered in canonical mode.\n");

	    sexp_get_char(input);
	    break;

	  case ';': /* Comments */
	    if (mode == SEXP_CANONICAL)
	      die("Comment encountered in canonical mode.\n");

	    do
	      {
		sexp_get_raw_char(input);
		if (input->ctype != SEXP_NORMAL_CHAR)
		  return;
	      }
	    while (input->c != '\n');
	  
	    break;
	  
	  default:
	    /* Ought to be a string */
	    if (mode != SEXP_ADVANCED)
	      die("Encountered advanced string in canonical mode.\n");

566
	    sexp_get_string(input, string);
Niels Möller's avatar
Niels Möller committed
567
568
569
570
571
	    return;
	  }
      }
}

572

573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595

struct sexp_compound_token
{
  enum sexp_token type;
  struct nettle_buffer display;
  struct nettle_buffer string;  
};

static void
sexp_compound_token_init(struct sexp_compound_token *token)
{
  token->type = 0;
  nettle_buffer_init(&token->display);
  nettle_buffer_init(&token->string);
}

static void
sexp_compound_token_clear(struct sexp_compound_token *token)
{
  nettle_buffer_clear(&token->display);
  nettle_buffer_clear(&token->string);
}

596
/* Parsing */
597
struct sexp_parser
598
{
599
  struct sexp_input *input;
600
601
  enum sexp_mode mode;
  enum sexp_token expected;
602

603
#if 0
604
  struct sexp_compound_token token;
605
#endif
606
607
608
609
610
611
612
613
614
615
  /* Nesting level of lists. Transport encoding counts as one
   * level of nesting. */
  unsigned level;

  /* The nesting level where the transport encoding occured.
   * Zero if we're not currently using tranport encoding. */
  unsigned transport;
};

static void
616
617
618
sexp_parse_init(struct sexp_parser *parser,
		struct sexp_input *input,
		enum sexp_mode mode)
619
{
620
621
622
  parser->input = input;
  parser->mode = mode;
  parser->expected = 0;
623

624
#if 0
625
  sexp_compound_token_init(&parser->token);
626
627
#endif
  
628
629
630
631
  /* Start counting with 1 for the top level, to make comparisons
   * between transport and level simpler.
   *
   * FIXME: Is that trick ugly? */
632
633
  parser->level = 1;
  parser->transport = 0;
634
635
636
637
}

/* Get next token, and check that it is of the expected kind. */
static void
638
sexp_check_token(struct sexp_parser *parser,
639
640
		 enum sexp_token token,
		 struct nettle_buffer *string)
641
{
642
  sexp_get_token(parser->input,
643
		 parser->transport ? SEXP_CANONICAL : parser->mode,
644
		 string);
645

646
  if (token && parser->input->token != token)
647
648
649
650
651
652
653
654
655
656
657
    die("Syntax error.\n");
}

/* Performs further processing of the input, in particular display
 * types and transport decoding.
 *
 * This is complicated a little by the requirement that a
 * transport-encoded block, {xxxxx}, must include exactly one
 * expression. We check at the end of strings and list whether or not
 * we should expect a SEXP_CODING_END as the next token. */
static void
658
659
sexp_parse(struct sexp_parser *parser,
	   struct sexp_compound_token *token)
660
661
662
{
  for (;;)
    {
663
664
665
666
667
668
      sexp_get_token(parser->input,
		     parser->transport ? SEXP_CANONICAL : parser->mode,
		     &token->string);
#if 0
      sexp_check_token(parser, parser->expected,
		       &token->string);
669
670

      if (parser->expected)
671
	{
672
	  parser->expected = 0;
673
	  
674
	  if (parser->input->token == SEXP_STRING)
675
676
	    /* XXX */
	    token->type = SEXP_DISPLAY
677
678
679
680
681
682
	    ;
	  else
	    {
	      assert(parser->input->token == SEXP_CODING_END);
	      assert(parser->transport);
	      assert(parser->level == parser->transport);
683

684
685
	      parser->level--;
	      parser->transport = 0;
686

687
688
	      continue;
	    }
689
	}
690
#endif 
691
      switch(parser->input->token)
692
693
694
695
696
697
698
699
	{
	case SEXP_LIST_END:
	  if (parser->level == parser->transport)
	    die("Unmatched end of list in transport encoded data.\n");
	  parser->level--;

	  if (!parser->level)
	    die("Unmatched end of list.\n");
700
701
702
703

	  token->type = SEXP_LIST_END;

	check_transport_end:
704
	  if (parser->level == parser->transport)
705
706
707
708
709
710
711
712
	    {
	      sexp_check_token(parser, SEXP_CODING_END, &token->string);
	      assert(parser->transport);
	      assert(parser->level == parser->transport);

	      parser->level--;
	      parser->transport = 0;
	    }
713
714
715
716
717
	  return;
    
	case SEXP_EOF:
	  if (parser->level > 1)
	    die("Unexpected end of file.\n");
718
719

	  token->type = SEXP_EOF;
720
721
722
723
	  return;

	case SEXP_LIST_START:
	  parser->level++;
724
	  token->type = SEXP_LIST_START;
725
726
727
	  return;

	case SEXP_DISPLAY_START:
728
729
730
731
732
733
	  sexp_check_token(parser, SEXP_STRING, &token->display);
	  sexp_check_token(parser, SEXP_DISPLAY_END, &token->display);
	  sexp_check_token(parser, SEXP_STRING, &token->string);

	  token->type = SEXP_DISPLAY;
	  goto check_transport_end;
734
735

	case SEXP_STRING:
736
737
	  token->type = SEXP_STRING;
	  goto check_transport_end;
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755

	case SEXP_TRANSPORT_START:
	  if (parser->mode == SEXP_CANONICAL)
	    die("Base64 not allowed in canonical mode.\n");
	  parser->level++;
	  parser->transport = parser->level;

	  continue;

	case SEXP_CODING_END:
	  die("Unexpected end of transport encoding.\n");
	  
	default:
	  /* Internal error. */
	  abort();
	}
    }
}
Niels Möller's avatar
Niels Möller committed
756
757
758
759
760
761
762
763


/* Output routines */

struct sexp_output
{
  FILE *f;

Niels Möller's avatar
Niels Möller committed
764
765
  unsigned line_width;
  
Niels Möller's avatar
Niels Möller committed
766
767
  const struct nettle_armor *coding;
  unsigned coding_indent;
Niels Möller's avatar
Niels Möller committed
768

769
770
  int prefer_hex;
  
Niels Möller's avatar
Niels Möller committed
771
772
  const struct nettle_hash *hash;
  void *ctx;
Niels Möller's avatar
Niels Möller committed
773
774
775
776
777
778
779
780
781
782
  
  union {
    struct base64_decode_ctx base64;
    /* NOTE: There's no context for hex encoding */
  } state;
  
  unsigned pos;
};

static void
783
784
sexp_output_init(struct sexp_output *output, FILE *f,
		 unsigned width, int prefer_hex)
Niels Möller's avatar
Niels Möller committed
785
786
{
  output->f = f;
Niels Möller's avatar
Niels Möller committed
787
  output->line_width = width;
Niels Möller's avatar
Niels Möller committed
788
  output->coding = NULL;
789
  output->prefer_hex = prefer_hex;
Niels Möller's avatar
Niels Möller committed
790
791
792
  output->hash = NULL;
  output->ctx = NULL;
  
Niels Möller's avatar
Niels Möller committed
793
794
795
  output->pos = 0;
}

Niels Möller's avatar
Niels Möller committed
796
797
798
799
800
801
802
803
static void
sexp_output_hash_init(struct sexp_output *output,
		      const struct nettle_hash *hash, void *ctx)
{
  output->hash = hash;
  output->ctx = ctx;
  hash->init(ctx);
}
Niels Möller's avatar
Niels Möller committed
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844

static void
sexp_put_raw_char(struct sexp_output *output, uint8_t c)
{
  output->pos++;
  if (putc(c, output->f) < 0)
    die("Write failed: %s\n", strerror(errno));
}

static void 
sexp_put_newline(struct sexp_output *output,
		 unsigned indent)
{
  unsigned i;

  sexp_put_raw_char(output, '\n');
  output->pos = 0;
  
  for(i = 0; i < indent; i++)
    sexp_put_raw_char(output, ' ');
  
  output->pos = indent;
}

static void
sexp_put_char(struct sexp_output *output, uint8_t c)
{
  if (output->coding)
    {
      /* Two is enough for both hex and base64. */
      uint8_t encoded[2];
      unsigned done;

      unsigned i;
      
      done = output->coding->encode_update(&output->state, encoded,
					   1, &c);
      assert(done <= sizeof(encoded));
      
      for (i = 0; i<done; i++)
	{
Niels Möller's avatar
Niels Möller committed
845
846
847
	  if (output->line_width
	      && output->pos >= output->line_width
	      && output->pos >= (output->coding_indent + 10))
Niels Möller's avatar
Niels Möller committed
848
849
850
851
852
	    sexp_put_newline(output, output->coding_indent);
	  
	  sexp_put_raw_char(output, encoded[i]);
	}
    }
Niels Möller's avatar
Niels Möller committed
853
854
  else if (output->hash)
    output->hash->update(output->ctx, 1, &c);
Niels Möller's avatar
Niels Möller committed
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
  else
    sexp_put_raw_char(output, c);
}

static void
sexp_put_data(struct sexp_output *output,
	      unsigned length, const uint8_t *data)
{
  unsigned i;

  for (i = 0; i<length; i++)
    sexp_put_char(output, data[i]);
}

static void
sexp_put_length(struct sexp_output *output, 
		unsigned length)
{
  unsigned digit = 1;

  for (;;)
    {
      unsigned next = digit * 10;
      if (next > length)
	break;
      digit = next;
    }

  for (; digit; length %= digit, digit /= 10)
    sexp_put_char(output, '0' + length / digit);
}

static void
sexp_put_code_start(struct sexp_output *output,
Niels Möller's avatar
Niels Möller committed
889
		    const struct nettle_armor *coding)
Niels Möller's avatar
Niels Möller committed
890
891
892
893
894
895
896
897
898
899
{
  assert(!output->coding);
  
  output->coding_indent = output->pos;
  
  output->coding = coding;
  output->coding->encode_init(&output->state);
}

static void
Niels Möller's avatar
Niels Möller committed
900
sexp_put_code_end(struct sexp_output *output)
Niels Möller's avatar
Niels Möller committed
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
{
  /* Enough for both hex and base64 */
  uint8_t encoded[BASE64_ENCODE_FINAL_LENGTH];
  unsigned done;

  assert(output->coding);

  done = output->coding->encode_final(&output->state, encoded);

  assert(done <= sizeof(encoded));
  
  output->coding = NULL;

  sexp_put_data(output, done, encoded);
}

static void
sexp_put_string(struct sexp_output *output, enum sexp_mode mode,
		struct nettle_buffer *string)
{
  if (!string->size)
    sexp_put_data(output, 2,
		  (mode == SEXP_ADVANCED) ? "\"\"": "0:");

  else if (mode == SEXP_ADVANCED)
    {
      unsigned i;
      int token = (string->contents[0] < '0' || string->contents[0] > '9');
      int quote_friendly = 1;
      static const char escape_names[0x10] =
	{ 0,0,0,0,0,0,0,0, 'b','t','n',0,'f','r',0,0 };

      for (i = 0; i<string->size; i++)
	{
	  uint8_t c = string->contents[i];
	  
	  if (token & !TOKEN_CHAR(c))
	    token = 0;
	  
	  if (quote_friendly)
	    {
	      if (c >= 0x7f)
		quote_friendly = 0;
	      else if (c < 0x20 && !escape_names[c])
		quote_friendly = 0;
	    }
	}
      
      if (token)
	sexp_put_data(output, string->size, string->contents);

      else if (quote_friendly)
	{
	  sexp_put_char(output, '"');

	  for (i = 0; i<string->size; i++)
	    {
	      int escape = 0;
	      uint8_t c = string->contents[i];

	      assert(c < 0x7f);
	      
	      if (c == '\\' || c == '"')
		escape = 1;
	      else if (c < 0x20)
		{
		  escape = 1;
		  c = escape_names[c];
		  assert(c);
		}
	      if (escape)
		sexp_put_char(output, '\\');

	      sexp_put_char(output, c);
	    }
	  
	  sexp_put_char(output, '"');
	}
979
      else 
Niels Möller's avatar
Niels Möller committed
980
	{
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
	  uint8_t delimiter;
	  const struct nettle_armor *coding;
	  
	  if (output->prefer_hex)
	    {
	      delimiter = '#';
	      coding = &nettle_base16;
	    }
	  else
	    {
	      delimiter = '|';
	      coding = &nettle_base64;
	    }
	  
	  sexp_put_char(output, delimiter);
	  sexp_put_code_start(output, coding);
Niels Möller's avatar
Niels Möller committed
997
	  sexp_put_data(output, string->size, string->contents);
Niels Möller's avatar
Niels Möller committed
998
	  sexp_put_code_end(output);
999
	  sexp_put_char(output, delimiter);
Niels Möller's avatar
Niels Möller committed
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
	}
    }
  else
    {
      sexp_put_length(output, string->size);
      sexp_put_char(output, ':');
      sexp_put_data(output, string->size, string->contents);
    }
}

Niels Möller's avatar
Niels Möller committed
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
static void
sexp_put_digest(struct sexp_output *output)
{
  uint8_t *digest;
  
  assert(output->hash);

  digest = alloca(output->hash->digest_size);
  output->hash->digest(output->ctx, output->hash->digest_size, digest);

  sexp_put_code_start(output, &nettle_base16);
  sexp_put_data(output, output->hash->digest_size, digest);
  sexp_put_code_end(output);
}

1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
#if 0
enum sexp_expr_result
  {
    sexp_expr_ok,
    sexp_expr_eol,
    sexp_expr_eof,
  };

static enum sexp_token
sexp_put_expression(struct sexp_output *output, enum sexp_mode mode_out,
		    unsigned indent,
		    struct sexp_parser *parser)
{
  sexp_parse(parser);
  if (parser->input->token == SEXP_EOF)
    return SEXP_EOF;
  if (parser->input->)
    ;
}
#endif
		    

Niels Möller's avatar
Niels Möller committed
1047

1048
/* Conversion functions. */
Niels Möller's avatar
Niels Möller committed
1049
1050
1051


static void
1052
1053
sexp_convert_list(struct sexp_parser *parser,
		  struct sexp_compound_token *token,
Niels Möller's avatar
Niels Möller committed
1054
1055
1056
1057
1058
1059
1060
		  struct sexp_output *output, enum sexp_mode mode_out,
		  unsigned indent);

/* Should be called with input->token being the first token of the
 * expression, to be converted, and return with input->token being the
 * last token of the expression. */
static void
1061
1062
sexp_convert_item(struct sexp_parser *parser,
		  struct sexp_compound_token *token,
Niels Möller's avatar
Niels Möller committed
1063
1064
1065
1066
1067
		  struct sexp_output *output, enum sexp_mode mode_out,
		  unsigned indent)
{
  if (mode_out == SEXP_TRANSPORT)
    {
Niels Möller's avatar
Niels Möller committed
1068
1069
      sexp_put_char(output, '{');
      sexp_put_code_start(output, &nettle_base64);
1070
      sexp_convert_item(parser, token, output, SEXP_CANONICAL, 0);
Niels Möller's avatar
Niels Möller committed
1071
1072
      sexp_put_code_end(output);
      sexp_put_char(output, '}');
Niels Möller's avatar
Niels Möller committed
1073
    }
1074
  else switch(token->type)
Niels Möller's avatar
Niels Möller committed
1075
1076
    {
    case SEXP_LIST_END:
1077
      die("Unmatched end of list.\n");
Niels Möller's avatar
Niels Möller committed
1078
1079
1080
1081
1082
1083
    case SEXP_EOF:
      die("Unexpected end of file.\n");
    case SEXP_CODING_END:
      die("Unexpected end of coding.\n");

    case SEXP_LIST_START:
1084
      sexp_convert_list(parser, token, output, mode_out, indent);
Niels Möller's avatar
Niels Möller committed
1085
1086
1087
      break;
      
    case SEXP_STRING:
1088
      sexp_put_string(output, mode_out, &token->string);
Niels Möller's avatar
Niels Möller committed
1089
1090
      break;

1091
    case SEXP_DISPLAY:
Niels Möller's avatar
Niels Möller committed
1092
      sexp_put_char(output, '[');
1093
      sexp_put_string(output, mode_out, &token->display);
Niels Möller's avatar
Niels Möller committed
1094
      sexp_put_char(output, ']');
1095
      sexp_put_string(output, mode_out, &token->string);      
Niels Möller's avatar
Niels Möller committed
1096
      break;
1097

Niels Möller's avatar
Niels Möller committed
1098
    default:
1099
1100
      /* Internal error */
      abort();
Niels Möller's avatar
Niels Möller committed
1101
1102
1103
1104
    }
}

static void
1105
1106
sexp_convert_list(struct sexp_parser *parser,
		  struct sexp_compound_token *token,
Niels Möller's avatar
Niels Möller committed
1107
1108
1109
1110
1111
1112
1113
1114
1115
		  struct sexp_output *output, enum sexp_mode mode_out,
		  unsigned indent)
{
  unsigned item;

  sexp_put_char(output, '(');
  
  for (item = 0;; item++)
    {
1116
      sexp_parse(parser, token);
Niels Möller's avatar
Niels Möller committed
1117

1118
      if (token->type == SEXP_LIST_END)
Niels Möller's avatar
Niels Möller committed
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
	{
	  sexp_put_char(output, ')');
	  return;
	}

      if (mode_out == SEXP_ADVANCED)
	{
	  /* FIXME: Adapt pretty printing to handle a big first
	   * element. */
	  if (item == 1)
	    {
	      sexp_put_char(output, ' ');
	      indent = output->pos;
	    }
	  else if (item > 1)
	    sexp_put_newline(output, indent);
	}

1137
      sexp_convert_item(parser, token, output, mode_out, indent);
Niels Möller's avatar
Niels Möller committed
1138
1139
1140
1141
1142
1143
1144
    }
}



/* Argument parsing and main program */

Niels Möller's avatar
Niels Möller committed
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
/* The old lsh sexp-conv program took the following options:
 *
 * Usage: sexp-conv [OPTION...]
 *             Conversion: sexp-conv [options] <INPUT-SEXP >OUTPUT
 *   or:  sexp-conv [OPTION...]
 *             Fingerprinting: sexp-conv --raw-hash [ --hash=ALGORITHM ]
 *             <PUBLIC-KEY
 * Reads an s-expression on stdin, and outputs the same s-expression on stdout,
 * possibly using a different encoding. By default, output uses the advanced
 * encoding. 
 * 
 *       --hash=Algorithm       Hash algorithm (default sha1).
 *       --once                 Process exactly one s-expression.
 *       --raw-hash             Output the hash for the canonical representation
 *                              of the object, in hexadecimal.
 *       --replace=Substitution An expression `/before/after/' replaces all
 *                              occurances of the atom `before' with `after'. The
 *                              delimiter `/' can be any single character.
 *       --select=Operator      Select a subexpression (e.g `caddr') for
 *                              processing.
 *       --spki-hash            Output an SPKI hash for the object.
 *       --debug                Print huge amounts of debug information
 *       --log-file=File name   Append messages to this file.
 *   -q, --quiet                Suppress all warnings and diagnostic messages
 *       --trace                Detailed trace
 *   -v, --verbose              Verbose diagnostic messages
 * 
 *  Valid sexp-formats are transport, canonical, advanced, and international.
 * 
 *  Valid sexp-formats are transport, canonical, advanced, advanced-hex and
 *  international.
 *   -f, --output-format=format Variant of the s-expression syntax to generate.
 *   -i, --input-format=format  Variant of the s-expression syntax to accept.
 * 
 *   -?, --help                 Give this help list
 *       --usage                Give a short usage message
 *   -V, --version              Print program version
 */ 

struct conv_options
{
  /* Output mode */
  enum sexp_mode mode;
1188
  int prefer_hex;
Niels Möller's avatar
Niels Möller committed
1189
1190
1191
1192
1193
1194
1195
  int once;
  unsigned width;
  const struct nettle_hash *hash;
};

enum { OPT_ONCE = 300, OPT_HASH };

Niels Möller's avatar
Niels Möller committed
1196
1197
1198
1199
1200
1201
1202
static int
match_argument(const char *given, const char *name)
{
  /* FIXME: Allow abbreviations */
  return !strcmp(given, name);
}

Niels Möller's avatar
Niels Möller committed
1203
1204
1205
static void
parse_options(struct conv_options *o,
	      int argc, char **argv)
Niels Möller's avatar
Niels Möller committed
1206
{  
Niels Möller's avatar
Niels Möller committed
1207
  o->mode = SEXP_ADVANCED;
1208
  o->prefer_hex = 0;
Niels Möller's avatar
Niels Möller committed
1209
1210
1211
  o->once = 0;
  o->hash = NULL;
  o->width = 72;
Niels Möller's avatar
Niels Möller committed
1212
  
Niels Möller's avatar
Niels Möller committed
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
  for (;;)
    {
      static const struct nettle_hash *hashes[] =
	{ &nettle_md5, &nettle_sha1, &nettle_sha256, NULL };
  
      static const struct option options[] =
	{
	  /* Name, args, flag, val */
	  { "help", no_argument, NULL, '?' },
	  { "version", no_argument, NULL, 'V' },
	  { "once", no_argument, NULL, OPT_ONCE },
	  { "syntax", required_argument, NULL, 's' },
	  { "hash", optional_argument, NULL, OPT_HASH },
	  { "width", required_argument, NULL, 'w' },
#if 0
	  /* Not yet implemented */
	  { "replace", required_argument, NULL, OPT_REPLACE },
	  { "select", required_argument, NULL, OPT_SELECT },
	  { "spki-hash", optional_argument, NULL, OPT_SPKI_HASH },
#endif
	  { NULL, 0, NULL, 0 }
	};
      int c;
      int option_index = 0;
      unsigned i;
     
      c = getopt_long(argc, argv, "V?s:w:", options, &option_index);

      switch (c)
	{
	default:
	  abort();
	  
	case -1:
	  if (optind != argc)
	    die("sexp-conv: Command line takes no arguments, only options.\n");
	  return;
Niels Möller's avatar
Niels Möller committed
1250

Niels Möller's avatar
Niels Möller committed
1251
1252
1253
	case 'w':
	  {
	    char *end;
1254
1255
1256
1257
1258
	    int width = strtol(optarg, &end , 0);
	    if (!*optarg || *end || width < 0)
	      die("sexp-conv: Invalid width `%s'.\n", optarg);

	    o->width = width;
Niels Möller's avatar
Niels Möller committed
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
	    break;
	  }
	case 's':
	  if (o->hash)
	    werror("sexp-conv: Combining --hash and -s usually makes no sense.\n");
	  if (match_argument(optarg, "advanced"))
	    o->mode = SEXP_ADVANCED;
	  else if (match_argument(optarg, "transport"))
	    o->mode = SEXP_TRANSPORT;
	  else if (match_argument(optarg, "canonical"))
	    o->mode = SEXP_CANONICAL;
1270
1271
1272
1273
1274
	  else if (match_argument(optarg, "hex"))
	    {
	      o->mode = SEXP_ADVANCED;
	      o->prefer_hex = 1;
	    }
Niels Möller's avatar
Niels Möller committed
1275
1276
1277
1278
1279
1280
1281
	  else
	    die("Available syntax variants: advanced, transport, canonical\n");
	  break;

	case OPT_ONCE:
	  o->once = 1;
	  break;
Niels Möller's avatar
Niels Möller committed
1282
	
Niels Möller's avatar
Niels Möller committed
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
	case OPT_HASH:
	  o->mode = SEXP_CANONICAL;
	  if (!optarg)
	    o->hash = &nettle_sha1;
	  else
	    for (i = 0;; i++)
	      {
		if (!hashes[i])
		  die("sexp_conv: Unknown hash algorithm `%s'\n",
		      optarg);
	      
		if (match_argument(optarg, hashes[i]->name))
		  {
		    o->hash = hashes[i];
		    break;
		  }
	      }
	  break;
	       
	case '?':
	  printf("Usage: sexp-conv [OPTION...]\n"
		 "  Conversion:     sexp-conv [OPTION...] <INPUT-SEXP\n"
		 "  Fingerprinting: sexp-conv --hash=HASH <INPUT-SEXP\n\n"
		 "Reads an s-expression on stdin, and outputs the same\n"
		 "sexp on stdout, possibly with a different syntax.\n\n"
		 "       --hash[=ALGORITHM]   Outputs only the hash of the expression.\n"
		 "                            Available hash algorithms:\n"
		 "                            ");
	  for(i = 0; hashes[i]; i++)
	    {
	      if (i) printf(", ");
	      printf("%s", hashes[i]->name);
	    }
	  printf(" (default is sha1).\n"
		 "   -s, --syntax=SYNTAX      The syntax used for the output. Available\n"
1318
		 "                            variants: advanced, hex, transport, canonical\n"
Niels Möller's avatar
Niels Möller committed
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
		 "       --once               Process only the first s-expression.\n"
		 "   -w, --width=WIDTH        Linewidth for base64 encoded data.\n"
		 "                            Zero means no limit.\n\n"
		 "Report bugs to " BUG_ADDRESS ".\n");
	  exit(EXIT_SUCCESS);

	case 'V':
	  printf("sexp-conv (" PACKAGE_STRING ")\n");
	  exit (EXIT_SUCCESS);
	}
    }
}
Niels Möller's avatar
Niels Möller committed
1331

Niels Möller's avatar
Niels Möller committed
1332
1333
1334
1335
1336
int
main(int argc, char **argv)
{
  struct conv_options options;
  struct sexp_input input;
1337
  struct sexp_parser parser;
1338
  struct sexp_compound_token token;
Niels Möller's avatar
Niels Möller committed
1339
  struct sexp_output output;
Niels Möller's avatar
Niels Möller committed
1340
  
Niels Möller's avatar
Niels Möller committed
1341
  parse_options(&options, argc, argv);
Niels Möller's avatar
Niels Möller committed
1342

Niels Möller's avatar
Niels Möller committed
1343
  sexp_input_init(&input, stdin);
1344
  sexp_parse_init(&parser, &input, SEXP_ADVANCED);
1345
  sexp_compound_token_init(&token);
1346
1347
  sexp_output_init(&output, stdout,
		   options.width, options.prefer_hex);
Niels Möller's avatar
Niels Möller committed
1348

Niels Möller's avatar
Niels Möller committed
1349
1350
1351
1352
1353
1354
  if (options.hash)
    sexp_output_hash_init(&output,
			  options.hash,
			  alloca(options.hash->context_size));
  
  sexp_get_char(&input);
1355
  
1356
  sexp_parse(&parser, &token);
1357
  
1358
  if (token.type == SEXP_EOF)
Niels Möller's avatar
Niels Möller committed
1359
1360
1361
1362
1363
1364
1365
1366
    {
      if (options.once)
	die("sexp-conv: No input expression.\n");
      return EXIT_SUCCESS;
    }
  
  do 
    {
1367
      sexp_convert_item(&parser, &token, &output, options.mode, 0);
Niels Möller's avatar
Niels Möller committed
1368
1369
1370
1371
1372
      if (options.hash)
	sexp_put_digest(&output);
      else if (options.mode != SEXP_CANONICAL)
	sexp_put_newline(&output, 0);
	  
1373
      sexp_parse(&parser, &token);
Niels Möller's avatar
Niels Möller committed
1374
    }
1375
  while (!options.once && token.type != SEXP_EOF);
Niels Möller's avatar
Niels Möller committed
1376
1377
1378
1379
  
  if (fflush(output.f) < 0)
    die("Final fflush failed: %s.\n", strerror(errno));
  
Niels Möller's avatar
Niels Möller committed
1380
1381
  return EXIT_SUCCESS;
}