sexp-conv.c 28.5 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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
221
222
223
224
225
226
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
321
322
323
324
325
326
327
328
329
    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;

  /* Current token */
  struct nettle_buffer string;
};

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

  nettle_buffer_init(&input->string);
}


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
sexp_push_char(struct sexp_input *input)
{
  assert(input->ctype == SEXP_NORMAL_CHAR);
    
  if (!NETTLE_BUFFER_PUTC(&input->string, input->c))
    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
sexp_get_token_string(struct sexp_input *input)
{
  assert(!input->coding);
  assert(input->ctype == SEXP_NORMAL_CHAR);
  
  if (!TOKEN_CHAR(input->c))
    die("Invalid token.\n");

  do
    {
      sexp_push_char(input);
      sexp_get_char(input);
    }
330
  while (input->ctype == SEXP_NORMAL_CHAR && TOKEN_CHAR(input->c));
Niels Möller's avatar
Niels Möller committed
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
  
  assert (input->string.size);
}

static void
sexp_get_string(struct sexp_input *input)
{
  input->string.size = 0;
  input->token = SEXP_STRING;
  
  switch (input->c)
    {
    case '\"':
      while (sexp_get_quoted_char(input))
	sexp_push_char(input);
      
      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:
	      sexp_push_char(input);
	      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:
      sexp_get_token_string(input);
      break;
    }
}

static void
sexp_get_string_length(struct sexp_input *input, enum sexp_mode mode)
{
  unsigned length;
  
  input->string.size = 0;
  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);
	  sexp_push_char(input);
	}
      
      break;

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

      for (; length; length--)
	if (sexp_get_quoted_char(input))
	  sexp_push_char(input);
	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);
	  sexp_push_char(input);
	}
      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
sexp_get_token(struct sexp_input *input, enum sexp_mode mode)
{
  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);
487
	sexp_get_char(input);
Niels Möller's avatar
Niels Möller committed
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
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
	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':
	    sexp_get_string_length(input, mode);
	    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");

	    sexp_get_string(input);
	    return;
	  }
      }
}

564
565

/* Parsing */
566
struct sexp_parser
567
{
568
  struct sexp_input *input;
569
570
571
572
573
574
575
576
577
578
579
580
581
  enum sexp_mode mode;
  enum sexp_token expected;
  
  /* 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
582
583
584
sexp_parse_init(struct sexp_parser *parser,
		struct sexp_input *input,
		enum sexp_mode mode)
585
{
586
587
588
  parser->input = input;
  parser->mode = mode;
  parser->expected = 0;
589
590
591
592
593

  /* Start counting with 1 for the top level, to make comparisons
   * between transport and level simpler.
   *
   * FIXME: Is that trick ugly? */
594
595
  parser->level = 1;
  parser->transport = 0;
596
597
598
599
}

/* Get next token, and check that it is of the expected kind. */
static void
600
sexp_check_token(struct sexp_parser *parser,
601
602
		 enum sexp_token token)
{
603
604
  sexp_get_token(parser->input,
		 parser->transport ? SEXP_CANONICAL : parser->mode);
605

606
607
  /* FIXME: Handle token == 0 meaning any. */ 
  if (parser->input->token != token)
608
609
610
611
612
613
614
615
616
617
618
    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
619
sexp_parse(struct sexp_parser *parser)
620
621
622
{
  for (;;)
    {
623
624
625
626
      if (!parser->expected)
	sexp_get_token(parser->input,
		       parser->transport ? SEXP_CANONICAL : parser->mode);
      else
627
	{
628
629
	  sexp_check_token(parser, parser->expected);
	  parser->expected = 0;
630
	  
631
632
633
634
635
636
637
638
	  if (parser->input->token == SEXP_STRING)
	    /* Nothing special */
	    ;
	  else
	    {
	      assert(parser->input->token == SEXP_CODING_END);
	      assert(parser->transport);
	      assert(parser->level == parser->transport);
639

640
641
	      parser->level--;
	      parser->transport = 0;
642

643
644
	      continue;
	    }
645
	}
646
647
	    
      switch(parser->input->token)
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
	{
	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");
	    
	  if (parser->level == parser->transport)
	    parser->expected = SEXP_CODING_END;
	  return;
    
	case SEXP_EOF:
	  if (parser->level > 1)
	    die("Unexpected end of file.\n");
	  return;

	case SEXP_LIST_START:
	  parser->level++;
	  return;

	case SEXP_DISPLAY_START:
671
672
673
	  sexp_check_token(parser, SEXP_STRING);
	  sexp_check_token(parser, SEXP_DISPLAY_END);
	  parser->input->token = SEXP_DISPLAY;
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
	  parser->expected = SEXP_STRING;
	  return;

	case SEXP_STRING:
	  if (parser->level == parser->transport)
	    parser->expected = SEXP_CODING_END;
	  return;

	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
699
700
701
702
703
704
705
706


/* Output routines */

struct sexp_output
{
  FILE *f;

Niels Möller's avatar
Niels Möller committed
707
708
  unsigned line_width;
  
Niels Möller's avatar
Niels Möller committed
709
710
  const struct nettle_armor *coding;
  unsigned coding_indent;
Niels Möller's avatar
Niels Möller committed
711

712
713
  int prefer_hex;
  
Niels Möller's avatar
Niels Möller committed
714
715
  const struct nettle_hash *hash;
  void *ctx;
Niels Möller's avatar
Niels Möller committed
716
717
718
719
720
721
722
723
724
725
  
  union {
    struct base64_decode_ctx base64;
    /* NOTE: There's no context for hex encoding */
  } state;
  
  unsigned pos;
};

static void
726
727
sexp_output_init(struct sexp_output *output, FILE *f,
		 unsigned width, int prefer_hex)
Niels Möller's avatar
Niels Möller committed
728
729
{
  output->f = f;
Niels Möller's avatar
Niels Möller committed
730
  output->line_width = width;
Niels Möller's avatar
Niels Möller committed
731
  output->coding = NULL;
732
  output->prefer_hex = prefer_hex;
Niels Möller's avatar
Niels Möller committed
733
734
735
  output->hash = NULL;
  output->ctx = NULL;
  
Niels Möller's avatar
Niels Möller committed
736
737
738
  output->pos = 0;
}

Niels Möller's avatar
Niels Möller committed
739
740
741
742
743
744
745
746
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787

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
788
789
790
	  if (output->line_width
	      && output->pos >= output->line_width
	      && output->pos >= (output->coding_indent + 10))
Niels Möller's avatar
Niels Möller committed
791
792
793
794
795
	    sexp_put_newline(output, output->coding_indent);
	  
	  sexp_put_raw_char(output, encoded[i]);
	}
    }
Niels Möller's avatar
Niels Möller committed
796
797
  else if (output->hash)
    output->hash->update(output->ctx, 1, &c);
Niels Möller's avatar
Niels Möller committed
798
799
800
801
802
803
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
  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
832
		    const struct nettle_armor *coding)
Niels Möller's avatar
Niels Möller committed
833
834
835
836
837
838
839
840
841
842
{
  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
843
sexp_put_code_end(struct sexp_output *output)
Niels Möller's avatar
Niels Möller committed
844
845
846
847
848
849
850
851
852
853
854
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
{
  /* 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, '"');
	}
922
      else 
Niels Möller's avatar
Niels Möller committed
923
	{
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
	  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
940
	  sexp_put_data(output, string->size, string->contents);
Niels Möller's avatar
Niels Möller committed
941
	  sexp_put_code_end(output);
942
	  sexp_put_char(output, delimiter);
Niels Möller's avatar
Niels Möller committed
943
944
945
946
947
948
949
950
951
952
	}
    }
  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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
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);
}

Niels Möller's avatar
Niels Möller committed
968

969
/* Conversion functions. */
Niels Möller's avatar
Niels Möller committed
970
971
972


static void
973
sexp_convert_list(struct sexp_input *input, struct sexp_parser *parser,
Niels Möller's avatar
Niels Möller committed
974
975
976
977
978
979
980
		  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
981
sexp_convert_item(struct sexp_input *input, struct sexp_parser *parser,
Niels Möller's avatar
Niels Möller committed
982
983
984
985
986
		  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
987
988
      sexp_put_char(output, '{');
      sexp_put_code_start(output, &nettle_base64);
989
      sexp_convert_item(input, parser, output, SEXP_CANONICAL, 0);
Niels Möller's avatar
Niels Möller committed
990
991
      sexp_put_code_end(output);
      sexp_put_char(output, '}');
Niels Möller's avatar
Niels Möller committed
992
993
994
995
    }
  else switch(input->token)
    {
    case SEXP_LIST_END:
996
      die("Unmatched end of list.\n");
Niels Möller's avatar
Niels Möller committed
997
998
999
1000
1001
1002
    case SEXP_EOF:
      die("Unexpected end of file.\n");
    case SEXP_CODING_END:
      die("Unexpected end of coding.\n");

    case SEXP_LIST_START:
1003
      sexp_convert_list(input, parser, output, mode_out, indent);
Niels Möller's avatar
Niels Möller committed
1004
1005
1006
1007
1008
1009
      break;
      
    case SEXP_STRING:
      sexp_put_string(output, mode_out, &input->string);
      break;

1010
    case SEXP_DISPLAY:
Niels Möller's avatar
Niels Möller committed
1011
      sexp_put_char(output, '[');
1012
      sexp_put_string(output, mode_out, &input->string);
Niels Möller's avatar
Niels Möller committed
1013
      sexp_put_char(output, ']');
1014
      sexp_parse(parser);
1015
1016
      assert(input->token == SEXP_STRING);
      sexp_put_string(output, mode_out, &input->string);      
Niels Möller's avatar
Niels Möller committed
1017
      break;
1018

Niels Möller's avatar
Niels Möller committed
1019
    default:
1020
1021
      /* Internal error */
      abort();
Niels Möller's avatar
Niels Möller committed
1022
1023
1024
1025
    }
}

static void
1026
sexp_convert_list(struct sexp_input *input, struct sexp_parser *parser,
Niels Möller's avatar
Niels Möller committed
1027
1028
1029
1030
1031
1032
1033
1034
1035
		  struct sexp_output *output, enum sexp_mode mode_out,
		  unsigned indent)
{
  unsigned item;

  sexp_put_char(output, '(');
  
  for (item = 0;; item++)
    {
1036
      sexp_parse(parser);
Niels Möller's avatar
Niels Möller committed
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056

      if (input->token == SEXP_LIST_END)
	{
	  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);
	}

1057
      sexp_convert_item(input, parser, output, mode_out, indent);
Niels Möller's avatar
Niels Möller committed
1058
1059
1060
1061
1062
1063
1064
    }
}



/* Argument parsing and main program */

Niels Möller's avatar
Niels Möller committed
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
/* 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;
1108
  int prefer_hex;
Niels Möller's avatar
Niels Möller committed
1109
1110
1111
1112
1113
1114
1115
  int once;
  unsigned width;
  const struct nettle_hash *hash;
};

enum { OPT_ONCE = 300, OPT_HASH };

Niels Möller's avatar
Niels Möller committed
1116
1117
1118
1119
1120
1121
1122
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
1123
1124
1125
static void
parse_options(struct conv_options *o,
	      int argc, char **argv)
Niels Möller's avatar
Niels Möller committed
1126
{  
Niels Möller's avatar
Niels Möller committed
1127
  o->mode = SEXP_ADVANCED;
1128
  o->prefer_hex = 0;
Niels Möller's avatar
Niels Möller committed
1129
1130
1131
  o->once = 0;
  o->hash = NULL;
  o->width = 72;
Niels Möller's avatar
Niels Möller committed
1132
  
Niels Möller's avatar
Niels Möller committed
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
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
  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
1170

Niels Möller's avatar
Niels Möller committed
1171
1172
1173
	case 'w':
	  {
	    char *end;
1174
1175
1176
1177
1178
	    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
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
	    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;
1190
1191
1192
1193
1194
	  else if (match_argument(optarg, "hex"))
	    {
	      o->mode = SEXP_ADVANCED;
	      o->prefer_hex = 1;
	    }
Niels Möller's avatar
Niels Möller committed
1195
1196
1197
1198
1199
1200
1201
	  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
1202
	
Niels Möller's avatar
Niels Möller committed
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
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
	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"
1238
		 "                            variants: advanced, hex, transport, canonical\n"
Niels Möller's avatar
Niels Möller committed
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
		 "       --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
1251

Niels Möller's avatar
Niels Möller committed
1252
1253
1254
1255
1256
int
main(int argc, char **argv)
{
  struct conv_options options;
  struct sexp_input input;
1257
  struct sexp_parser parser;
Niels Möller's avatar
Niels Möller committed
1258
  struct sexp_output output;
Niels Möller's avatar
Niels Möller committed
1259
  
Niels Möller's avatar
Niels Möller committed
1260
  parse_options(&options, argc, argv);
Niels Möller's avatar
Niels Möller committed
1261

Niels Möller's avatar
Niels Möller committed
1262
  sexp_input_init(&input, stdin);
1263
  sexp_parse_init(&parser, &input, SEXP_ADVANCED);
1264
1265
  sexp_output_init(&output, stdout,
		   options.width, options.prefer_hex);
Niels Möller's avatar
Niels Möller committed
1266

Niels Möller's avatar
Niels Möller committed
1267
1268
1269
1270
1271
1272
  if (options.hash)
    sexp_output_hash_init(&output,
			  options.hash,
			  alloca(options.hash->context_size));
  
  sexp_get_char(&input);
1273
  
1274
  sexp_parse(&parser);
1275
  
Niels Möller's avatar
Niels Möller committed
1276
1277
1278
1279
1280
1281
1282
1283
1284
  if (input.token == SEXP_EOF)
    {
      if (options.once)
	die("sexp-conv: No input expression.\n");
      return EXIT_SUCCESS;
    }
  
  do 
    {
1285
      sexp_convert_item(&input, &parser, &output, options.mode, 0);
Niels Möller's avatar
Niels Möller committed
1286
1287
1288
1289
1290
      if (options.hash)
	sexp_put_digest(&output);
      else if (options.mode != SEXP_CANONICAL)
	sexp_put_newline(&output, 0);
	  
1291
      sexp_parse(&parser);
Niels Möller's avatar
Niels Möller committed
1292
1293
1294
1295
1296
1297
    }
  while (!options.once && input.token != SEXP_EOF);
  
  if (fflush(output.f) < 0)
    die("Final fflush failed: %s.\n", strerror(errno));
  
Niels Möller's avatar
Niels Möller committed
1298
1299
  return EXIT_SUCCESS;
}