sexp-conv.c 24.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
#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
12
13
14
15
16
#include "base16.h"
#include "base64.h"
#include "buffer.h"
#include "nettle-meta.h"

Niels Möller's avatar
Niels Möller committed
17
18
#include "getopt.h"

Niels Möller's avatar
Niels Möller committed
19
20
21
22
23
24
25
#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
26
static void
Niels Möller's avatar
Niels Möller committed
27
28
29
30
31
32
33
die(const char *format, ...)
#if __GNUC___
     __attribute__((__format__ (__printf__,1, 2)))
     __attribute__((__noreturn__))
#endif
     ;

Niels Möller's avatar
Niels Möller committed
34
static void
Niels Möller's avatar
Niels Möller committed
35
36
37
38
39
40
41
42
43
44
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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
330
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
487
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
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
  {
    SEXP_STRING,
    SEXP_DISPLAY_START,
    SEXP_DISPLAY_END,
    SEXP_LIST_START,
    SEXP_LIST_END,
    SEXP_TRANSPORT_START,
    SEXP_CODING_END,
    SEXP_EOF,
  };


/* 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);
    }
  while (TOKEN_CHAR(input->c));
  
  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);
	sexp_next_char(input);
	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;
	  }
      }
}



/* Output routines */

struct sexp_output
{
  FILE *f;

Niels Möller's avatar
Niels Möller committed
547
548
  unsigned line_width;
  
Niels Möller's avatar
Niels Möller committed
549
550
  const struct nettle_armor *coding;
  unsigned coding_indent;
Niels Möller's avatar
Niels Möller committed
551
552
553

  const struct nettle_hash *hash;
  void *ctx;
Niels Möller's avatar
Niels Möller committed
554
555
556
557
558
559
560
561
562
563
  
  union {
    struct base64_decode_ctx base64;
    /* NOTE: There's no context for hex encoding */
  } state;
  
  unsigned pos;
};

static void
Niels Möller's avatar
Niels Möller committed
564
sexp_output_init(struct sexp_output *output, FILE *f, unsigned width)
Niels Möller's avatar
Niels Möller committed
565
566
{
  output->f = f;
Niels Möller's avatar
Niels Möller committed
567
  output->line_width = width;
Niels Möller's avatar
Niels Möller committed
568
  output->coding = NULL;
Niels Möller's avatar
Niels Möller committed
569
570
571
  output->hash = NULL;
  output->ctx = NULL;
  
Niels Möller's avatar
Niels Möller committed
572
573
574
  output->pos = 0;
}

Niels Möller's avatar
Niels Möller committed
575
576
577
578
579
580
581
582
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623

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
624
625
626
	  if (output->line_width
	      && output->pos >= output->line_width
	      && output->pos >= (output->coding_indent + 10))
Niels Möller's avatar
Niels Möller committed
627
628
629
630
631
	    sexp_put_newline(output, output->coding_indent);
	  
	  sexp_put_raw_char(output, encoded[i]);
	}
    }
Niels Möller's avatar
Niels Möller committed
632
633
  else if (output->hash)
    output->hash->update(output->ctx, 1, &c);
Niels Möller's avatar
Niels Möller committed
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
  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
668
		    const struct nettle_armor *coding)
Niels Möller's avatar
Niels Möller committed
669
670
671
672
673
674
675
676
677
678
{
  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
679
sexp_put_code_end(struct sexp_output *output)
Niels Möller's avatar
Niels Möller committed
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
{
  /* 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, '"');
	}
      else
	{
Niels Möller's avatar
Niels Möller committed
760
761
	  sexp_put_char(output, '|');
	  sexp_put_code_start(output, &nettle_base64);
Niels Möller's avatar
Niels Möller committed
762
	  sexp_put_data(output, string->size, string->contents);
Niels Möller's avatar
Niels Möller committed
763
764
	  sexp_put_code_end(output);
	  sexp_put_char(output, '|');
Niels Möller's avatar
Niels Möller committed
765
766
767
768
769
770
771
772
773
774
	}
    }
  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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
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
790
791
792
793
794
795
796
797
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

/* Parsing and conversion functions. */

static void
sexp_convert_string(struct sexp_input *input, enum sexp_mode mode_in,
		    struct sexp_output *output, enum sexp_mode mode_out)
{
  sexp_get_token(input, mode_in);
  if (input->token == SEXP_STRING)
    sexp_put_string(output, mode_out, &input->string);
  else
    die("Invalid string.\n");
}


static void
sexp_convert_list(struct sexp_input *input, enum sexp_mode mode_in,
		  struct sexp_output *output, enum sexp_mode mode_out,
		  unsigned indent);

static void
sexp_skip_token(struct sexp_input *input, enum sexp_mode mode,
		enum sexp_token token)
{
  sexp_get_token(input, mode);

  if (input->token != token)
    die("Syntax error.\n");
}

/* 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
sexp_convert_item(struct sexp_input *input, enum sexp_mode mode_in,
		  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
830
831
      sexp_put_char(output, '{');
      sexp_put_code_start(output, &nettle_base64);
Niels Möller's avatar
Niels Möller committed
832
      sexp_convert_item(input, mode_in, output, SEXP_CANONICAL, 0);
Niels Möller's avatar
Niels Möller committed
833
834
      sexp_put_code_end(output);
      sexp_put_char(output, '}');
Niels Möller's avatar
Niels Möller committed
835
836
837
838
839
840
841
842
843
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
    }
  else switch(input->token)
    {
    case SEXP_LIST_END:
      die("Unmatched end of list.\n");      
    case SEXP_EOF:
      die("Unexpected end of file.\n");
    case SEXP_CODING_END:
      die("Unexpected end of coding.\n");

    case SEXP_LIST_START:
      sexp_convert_list(input, mode_in, output, mode_out, indent);
      break;
      
    case SEXP_STRING:
      sexp_put_string(output, mode_out, &input->string);
      break;

    case SEXP_DISPLAY_START:
      sexp_put_char(output, '[');
      sexp_convert_string(input, mode_in, output, mode_out);
      sexp_skip_token(input, mode_in, SEXP_DISPLAY_END);
      sexp_put_char(output, ']');
      sexp_convert_string(input, mode_in, output, mode_out);
      break;
      
    case SEXP_TRANSPORT_START:
      if (mode_in == SEXP_CANONICAL)
	die("Base64 not allowed in canonical mode.\n");
      else
	{
	  sexp_get_token(input, SEXP_CANONICAL);
	  sexp_convert_item(input, SEXP_CANONICAL, output, mode_out, indent);
	  sexp_skip_token(input, SEXP_CANONICAL, SEXP_CODING_END);
	  
	  break;
	}

    default:
      die("Syntax error.\n");
    }
}

static void
sexp_convert_list(struct sexp_input *input, enum sexp_mode mode_in,
		  struct sexp_output *output, enum sexp_mode mode_out,
		  unsigned indent)
{
  unsigned item;

  sexp_put_char(output, '(');
  
  for (item = 0;; item++)
    {
      sexp_get_token(input, mode_in);

      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);
	}

      sexp_convert_item(input, mode_in, output, mode_out, indent);
    }
}



/* Argument parsing and main program */

Niels Möller's avatar
Niels Möller committed
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
/* 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;
  int once;
  unsigned width;
  const struct nettle_hash *hash;
};

enum { OPT_ONCE = 300, OPT_HASH };

Niels Möller's avatar
Niels Möller committed
968
969
970
971
972
973
974
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
975
976
977
static void
parse_options(struct conv_options *o,
	      int argc, char **argv)
Niels Möller's avatar
Niels Möller committed
978
{  
Niels Möller's avatar
Niels Möller committed
979
980
981
982
  o->mode = SEXP_ADVANCED;
  o->once = 0;
  o->hash = NULL;
  o->width = 72;
Niels Möller's avatar
Niels Möller committed
983
  
Niels Möller's avatar
Niels Möller committed
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
  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
1021

Niels Möller's avatar
Niels Möller committed
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
	case 'w':
	  {
	    char *end;
	    o->width = strtol(optarg, &end , 0);
	    if (!*optarg || *end || o->width < 0)
	      die("sexp-conv: Invalid width `%s'.\n",
		  optarg);
	    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;
	  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
1047
	
Niels Möller's avatar
Niels Möller committed
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
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
	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"
		 "                            variants: advanced, transport, canonical\n"
		 "       --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
1096

Niels Möller's avatar
Niels Möller committed
1097
1098
1099
1100
1101
1102
int
main(int argc, char **argv)
{
  struct conv_options options;
  struct sexp_input input;
  struct sexp_output output;
Niels Möller's avatar
Niels Möller committed
1103
  
Niels Möller's avatar
Niels Möller committed
1104
  parse_options(&options, argc, argv);
Niels Möller's avatar
Niels Möller committed
1105

Niels Möller's avatar
Niels Möller committed
1106
1107
  sexp_input_init(&input, stdin);
  sexp_output_init(&output, stdout, options.width);
Niels Möller's avatar
Niels Möller committed
1108

Niels Möller's avatar
Niels Möller committed
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
  if (options.hash)
    sexp_output_hash_init(&output,
			  options.hash,
			  alloca(options.hash->context_size));
  
  sexp_get_char(&input);
  sexp_get_token(&input, SEXP_ADVANCED);
    
  if (input.token == SEXP_EOF)
    {
      if (options.once)
	die("sexp-conv: No input expression.\n");
      return EXIT_SUCCESS;
    }
  
  do 
    {
      sexp_convert_item(&input, SEXP_ADVANCED, &output, options.mode, 0);
      if (options.hash)
	sexp_put_digest(&output);
      else if (options.mode != SEXP_CANONICAL)
	sexp_put_newline(&output, 0);
	  
      sexp_get_token(&input, SEXP_ADVANCED);
    }
  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
1139
1140
  return EXIT_SUCCESS;
}