aboutsummaryrefslogtreecommitdiff
path: root/src/eclat.c
blob: c00c7958deeb897ba588484c541b279d93cace63 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
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
624
625
626
627
628
629
630
631
632
633
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
668
669
670
671
672
673
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
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
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
788
789
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
830
831
832
833
834
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
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
/* This file is part of Eclat.
   Copyright (C) 2012, 2013 Sergey Poznyakoff.
 
   Eclat is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.
 
   Eclat 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 General Public License for more details.
 
   You should have received a copy of the GNU General Public License
   along with Eclat.  If not, see <http://www.gnu.org/licenses/>. */

#include "eclat.h"

char *conffile = SYSCONFDIR "/eclat.conf" ;
int lint_mode;
int dry_run_mode;
int match_command_mode;
int preprocess_only = 0;

char *endpoint = "ec2.amazonaws.com";
char *access_key;
char *secret_key;
char *region_name;
int use_ssl;
int ssl_verify_peer = 1;
char *ssl_ca_file;
char *ssl_ca_path;
char *format_expr_option;
char *format_file_option;
char *format_name_option;
int sort_option;
char *format_file;
char *test_map_name;
enum eclat_confirm_mode confirm_mode;
int translate_option = -1;

FILE *xml_dump_file;


static char *categories[] = {
	"main",
	"cfgram",
	"cflex",
	"conf",
	"curl",
};

static void
debug_init()
{
	int i;

	for (i = 0; i < sizeof(categories)/sizeof(categories[0]); i++)
		debug_register(categories[i]);
}


static void
dump(const char *text, FILE *stream, unsigned char *ptr, size_t size)
{
	size_t i;
	size_t c;
	unsigned int width = 0x10;
	int hex = debug_level(ECLAT_DEBCAT_CURL) > 2;
		
	if (!hex)
		/* without the hex output, we can fit more on screen */
		width = 0x40;

	fprintf(stream, "%s, %zd bytes (0x%zx)\n", text, size, size);

	for (i = 0; i < size; i += width) {
		fprintf(stream, "%04zx: ", i);

		if (hex) {
			for (c = 0; c < width; c++)
				if (i+c < size)
					fprintf(stream, "%02x ", ptr[i+c]);
				else
					fputs("   ", stream);
		}

		for(c = 0; (c < width) && (i+c < size); c++) {
			/* check for CRLf; if found, skip past and start a
			   new line of output */
			if (!hex && (i + c + 1 < size) &&
			    ptr[i+c] == '\r' && ptr[i+c+1] == '\n') {
				i += (c + 2 -width);
				break;
			}
			fprintf(stream, "%c",
				isprint(ptr[i+c]) ? ptr[i+c] : '.');
			/* check again for CRLF, to avoid an extra \n if
			   it's at width */
			if (!hex && (i + c + 2 < size) &&
			    ptr[i+c+1] == '\r' && ptr[i+c+2] == '\n') {
				i += (c + 3 - width);
				break;
			}
		}
		fputc('\n', stream); /* newline */
	}
	fflush(stream);
}

static int
eclat_trace_fun(CURL *handle, curl_infotype type,
		char *data, size_t size,
		void *userp)
{
/*	struct data *config = (struct data *)userp;*/
	const char *text;

	switch (type) {
	case CURLINFO_TEXT:
		fprintf(stderr, "== Info: %s", data);
	default: /* in case a new one is introduced to shock us */
		return 0;

	case CURLINFO_HEADER_OUT:
		text = "=> Send header";
		break;
	case CURLINFO_DATA_OUT:
		text = "=> Send data";
		break;
	case CURLINFO_SSL_DATA_OUT:
		text = "=> Send SSL data";
		break;
	case CURLINFO_HEADER_IN:
		text = "<= Recv header";
		break;
	case CURLINFO_DATA_IN:
		text = "<= Recv data";
		break;
	case CURLINFO_SSL_DATA_IN:
		text = "<= Recv SSL data";
		break;
	}
	
	dump(text, stderr, (unsigned char *)data, size);
	return 0;
}

static void
dumpxml(void *ptr, size_t realsize)
{
	static int open_failed = 0;

	if (open_failed)
		return;
	if (!xml_dump_file) {
		xml_dump_file = fopen(XML_DUMP_FILE_NAME, "w");
		if (!xml_dump_file) {
			err("cannot open dump file %s: %s",
			    XML_DUMP_FILE_NAME, strerror(errno));
			open_failed = 1;
			return;
		}
	}
	fwrite(ptr, realsize, 1, xml_dump_file);
}

static size_t
write_callback(void *ptr, size_t size, size_t nmemb, void *data)
{
	size_t realsize = size * nmemb;
	XML_Parser parser = data;
	enum XML_Status status;
	int line = XML_GetCurrentLineNumber(parser);
	int column = XML_GetCurrentColumnNumber(parser);

	if (debug_level(ECLAT_DEBCAT_MAIN) >= 10)
		dumpxml(ptr, realsize);

	status = XML_Parse(parser, ptr, realsize, 0);
	if (status == XML_STATUS_ERROR) {
		enum XML_Error error = XML_GetErrorCode(parser);

		line = XML_GetCurrentLineNumber(parser);
		column = XML_GetCurrentColumnNumber(parser);

		/* FIXME: better diagnostics. */
		die(EX_SOFTWARE, "XML parse error at %d:%d: %s",
		    line, column, XML_ErrorString(error));
	}
	return realsize;
}

static int
node_ident_cmp(struct grecs_node const *a, struct grecs_node const *b)
{
        return strcmp(a->ident, b->ident);
}

void listcmd(char *fmt);

#include "cmdline.h"

#define CMD_MOD   0x01
#define CMD_DESTR 0x02
#define CMD_NOQRY 0x04

struct eclat_command cmdtab[] = {
	{ "start", "start-instances",  "StartInstances", eclat_start_instance,
	  CMD_MOD },
	{ "stop", "stop-instances",   "StopInstances",  eclat_stop_instance,
	  CMD_MOD },
	{ "reboot", "reboot-instances", "RebootInstances",  eclat_reboot_instance,
	  CMD_MOD },
	{ "lsaddr", "describe-addresses", "DescribeAddresses",
	  eclat_describe_addresses },
	{ "lstag", "describe-tags",    "DescribeTags",   eclat_describe_tags },
	{ "lsiattr", "describe-instance-attribute", "DescribeInstanceAttribute",
	  eclat_describe_instance_attribute },
	{ "lsistat", "describe-instance-status", "DescribeInstanceStatus",
	  eclat_describe_instance_status },
	{ "lsinst", "describe-instances", "DescribeInstances",
	  eclat_describe_instances },
	{ "lsvol", "describe-volumes", "DescribeVolumes",
	  eclat_describe_volumes },
	{ "allocaddr", "allocate-address", "AllocateAddress",
	  eclat_allocate_address, CMD_MOD },
	{ "rmaddr", "release-address", "ReleaseAddress",
	  eclat_release_address, CMD_MOD|CMD_DESTR },
	{ "assocaddr", "associate-address", "AssociateAddress",
	  eclat_associate_address, CMD_MOD },
	{ "disasaddr", "disassociate-address", "DisassociateAddress",
	  eclat_disassociate_address, CMD_MOD },
	{ "mktag", "create-tags", "CreateTags",
	  eclat_create_tags, CMD_MOD },
	{ "rmtag", "delete-tags", "DeleteTags",
	  eclat_delete_tags, CMD_MOD|CMD_DESTR },
	{ "conmesg", "get-console-output", "GetConsoleOutput",
	  eclat_get_console_output },
	{ "lssg", "describe-security-groups", "DescribeSecurityGroups",
	  eclat_describe_security_groups },
	{ "mksnap", "create-snapshot", "CreateSnapshot",
	  eclat_create_snapshot },
	{ "lssnap", "describe-snapshots", "DescribeSnapshots",
	  eclat_describe_snapshots },
	{ "lssattr", "describe-snapshot-attribute", "DescribeSnapshotAttribute",
	  eclat_describe_snapshot_attribute },
	{ "setsattr", "modify-snapshot-attribute", "ModifySnapshotAttribute",
	  eclat_modify_snapshot_attribute, CMD_MOD },
	{ "clrsattr", "reset-snapshot-attribute", "ResetSnapshotAttribute",
	  eclat_reset_snapshot_attribute, CMD_MOD|CMD_DESTR },
	{ "rmsnap", "delete-snapshot", "DeleteSnapshot",
	  eclat_delete_snapshot, CMD_MOD|CMD_DESTR },
	{ "lszon", "describe-availability-zones", "DescribeAvailabilityZones",
	  eclat_describe_avaialbility_zones },
	{ "lsreg", "describe-regions", "DescribeRegions",
	  eclat_describe_regions },
	{ "mkvol", "create-volume", "CreateVolume",
	  eclat_create_volume, CMD_MOD },
	{ "rmvol", "delete-volume", "DeleteVolume",
	  eclat_delete_volume, CMD_MOD|CMD_DESTR },
	{ "atvol", "attach-volume", "AttachVolume",
	  eclat_attach_volume, CMD_MOD },
	{ "devol", "detach-volume", "DetachVolume",
	  eclat_detach_volume, CMD_MOD|CMD_DESTR },
	{ "setiattr", "modify-instance-attribute", "ModifyInstanceAttribute",
	  eclat_modify_instance_attribute, CMD_MOD },
	{ "lsimg", "describe-images", "DescribeImages",
	  eclat_describe_images },
	{ "mkinst", "run-instances", "RunInstances",
	  eclat_run_instances, CMD_MOD },
	{ "mkimg", "create-image", "CreateImage",
	  eclat_create_image, CMD_MOD },
	{ "deimg", "deregister-image", "DeregisterImage",
	  eclat_deregister_image, CMD_MOD|CMD_DESTR },
	{ "cpimg", "copy-image", "CopyImage",
	  eclat_copy_image },
	{ "cpsnap", "copy-snapshot", "CopySnapshot",
	  eclat_copy_snapshot },
	{ "lsattr", NULL, NULL,
	  eclat_lsattr, CMD_NOQRY },
};
size_t cmdcnt = sizeof(cmdtab) / sizeof(cmdtab[0]);

static int
cmdcmp(const void *a, const void *b)
{
	struct eclat_command const *cmda = a;
	struct eclat_command const *cmdb = b;
	if (cmda->name && cmdb->name)
		return strcmp(cmda->name, cmdb->name);
	else if (cmda->ident && cmdb->ident)
		return strcmp(cmda->ident, cmdb->ident);
	else if (cmda->ident || cmda->name)
		return 127;
	else if (cmdb->ident || cmdb->name)
		return -127;
	return 0;
}

static void
sortcmds()
{
	qsort(cmdtab, cmdcnt, sizeof(cmdtab[0]), cmdcmp);
}

/* Format:

   %[pfx:][sfx][ni]

   For example, to format the table of available commands for doc/eclat.1:

      eclat -l '\t\\fB%n\\fR\t\\fB%i\\fR\n'

   To format a "see also" list of commands (ibidem):
   
      eclat -l '%.BR eclat-: (1)n,\n'
*/

int
parsespec(char *start, char **endp, char *fchr, char *s[], int l[])
{
	char *p;
	int n = 0;

	++start;
	s[0] = start;
	s[1] = NULL;
	l[0] = l[1] = 0;
	for (p = start; *p; p++) {
		if (*p == ':' || strchr(fchr, *p)) {
			if (n > 1)
				return -1;
			l[n++] = p - start;
			if (*p != ':') {
				*endp = p + 1;
				return *p;
			}
			if (n == 1)
				s[n] = start = p + 1;
		}
	}
	return -1;
}

void
fmtstr(const char *str, int len)
{
	while (len--) {
		int c = *str++;
		if (c == '\\') {
			if (len) {
				len--;
				c = wordsplit_c_unquote_char(*str++);
			}
		}
		fputc(c, stdout);
	}
}

void
listcmd(char *fmt)
{
	struct eclat_command *cp;
	
	for (cp = cmdtab; cp < cmdtab + cmdcnt; cp++) {
		char *p = fmt;
		char *start = fmt;
		char *end;
		char *s[2];
		int l[2];
		const char *str;
		
		while (*p) {
			if (*p == '%') {
				switch (parsespec(p, &end, "ni", s, l)) {
				case 'n':
					str = cp->name;
					break;
				case 'i':
					str = cp->ident;
					break;
				default:
					p++;
					continue;
				}

				if (str) {
					if (p != start)
						fmtstr(start, p - start);
					fmtstr(s[0], l[0]);
					printf("%s", str);
					fmtstr(s[1], l[1]);
				}
				start = p = end;
			} else {
				p++;
			}
		}
		if (p != start)
			fmtstr(start, p - start);
	}
}

void
listcmdhook()
{
	struct eclat_command *cp;

	printf("Available commands\n");
	printf("Eclat name   EC2 Name\n");
	printf("-----------+---------\n");
	for (cp = cmdtab; cp < cmdtab + cmdcnt; cp++) {
		printf("  %-10s", cp->name ? cp->name : "");
		if (cp->ident)
			printf (" %s", cp->ident);
		putchar ('\n');
	}

	printf("\nRun \"%s COMMAND --help\" to get help on a particular command.\n",
		program_name);
	
	putchar('\n');
}


#define NO_MATCH      0
#define EXACT_MATCH   1
#define PARTIAL_MATCH 2

static int
ident_matches(const char *p, const char *q)
{
	int match = EXACT_MATCH;
	
	for (;; p++, q++) {
		if (*p == 0)
			return *q == 0 ? match : NO_MATCH;
		else if (*q == 0)
			return PARTIAL_MATCH;
		else if (*p == *q)
			continue;
		else if (*q == '-') {
			for (; *p != '-'; p++)
				if (!*p)
					return NO_MATCH;
			match = PARTIAL_MATCH;
		} else
			break;
	}
	return NO_MATCH;
}	

struct eclat_command *
find_command_name(const char *name)
{
	struct eclat_command *cp, *match = NULL;
	
	for (cp = cmdtab; cp < cmdtab + cmdcnt; cp++) {
		if (cp->name && strcmp(cp->name, name) == 0)
			return cp;
		if (!cp->ident)
			continue;
		switch (ident_matches(cp->ident, name)) {
		case NO_MATCH:
			break;
		case EXACT_MATCH:
			return cp;
		case PARTIAL_MATCH:
			if (!match)
				match = cp;
			else {
				/* Second match */
				err("ambiguous command %s:", name);
				err("  %s", match->ident);
				err("  %s", cp->ident);
				while (++cp < cmdtab + cmdcnt)
					if (ident_matches(cp->ident, name) !=
					    NO_MATCH)
						err("  %s", cp->ident);
				exit(EX_USAGE);
			}
		}
	}
	return match;
}

static void
print_matching_commands(const char *pat)
{
	struct eclat_command *cp;
	size_t patlen = strlen (pat);
	
	for (cp = cmdtab; cp < cmdtab + cmdcnt; cp++) {
		if (cp->name && strlen (cp->name) >= patlen &&
		    memcmp (cp->name, pat, patlen) == 0)
			printf("%s\n", cp->name);
		if (cp->ident && ident_matches(cp->ident, pat) != NO_MATCH)
			printf("%s\n", cp->ident);
	}
}

struct eclat_command *
find_command_tag(const char *tag)
{
	struct eclat_command *cp;

	for (cp = cmdtab; cp < cmdtab + cmdcnt; cp++) {
		if (eclat_actcmp(cp->tag, tag) == 0)
			return cp;
	}
	return NULL;
}

void
set_command_confirmation(const char *name, enum eclat_confirm_mode cfmode,
			 grecs_locus_t *locus)
{
	struct eclat_command *cp;
	int flag = 0;
	
	if (strcmp(name, "all") == 0)
		flag = CMD_MOD;
	else if (strcmp(name, "destructive") == 0)
		flag = CMD_DESTR;
	else {
		cp = find_command_tag(name);
	
		if (!cp)
			grecs_error(locus, 0, "unknown command or class");
		else
			cp->confirm = cfmode;
		return;
	}
	
	for (cp = cmdtab; cp < cmdtab + cmdcnt; cp++) {
		if (cp->flags & flag)
			cp->confirm = cfmode;
	}
}

void
set_command_format(const char *name, const char *format, grecs_locus_t *locus)
{
	struct eclat_command *cp = find_command_tag(name);

	if (!cp) {
		grecs_error(locus, 0, "unknown command");
		return;
	}

	if (cp->fmt) {
		grecs_error(locus, 0, "format %s redefined", name);
		grecs_error(&cp->locus, 0, "this is the location of "
			    "the previous definition");
		free(cp->fmt);
	}

	cp->fmt = grecs_strdup(format);
	cp->locus = *locus;
}

forlan_eval_env_t 
compile_format_file(const char *fmtfile)
{
	forlan_eval_env_t env;
	FILE *fp;
	struct grecs_locus_point pt;
	
	fp = fopen(fmtfile, "r");
	if (!fp)
		die(EX_UNAVAILABLE, "cannot open format file \"%s\": %s",
		    fmtfile, strerror(errno));

	pt.file = (char*) fmtfile;
	pt.line = 1;
	pt.col = 0;

	env = forlan_parse_file(fp, &pt);
	fclose(fp);
	if (!env)
		exit(EX_UNAVAILABLE);
	
	return env;
}


struct filter_descr *available_filters;

static char *aws_typestr[] = {
	"String",
	"dateType",
	"Boolean",
	"Integer"
};

void
list_filters(FILE *fp)
{
	struct filter_descr *flt;
	size_t ncols = get_scr_cols();
	size_t col, start;
	
	fprintf(fp, "Available filters are:\n");
	for (flt = available_filters; flt->name; flt++) {
		col = fprintf(fp, " %-24s ", flt->name);
		if (col > 26) {
			col = start = 26;
			fprintf(fp, "\n%*.*s", (int)start, (int)start, "");
		}
		if (flt->type != FILTER_ENUM)
			fprintf(fp, "%s", aws_typestr[flt->type]);
		else {
			int i;
			char *delim;
			size_t len;
			
			col += fprintf(fp, "One of:");
			start = col + 1;
			delim = " ";
			for (i = 0; flt->avail[i]; i++) {
				len = strlen(delim) + strlen(flt->avail[i]);
				if (col + len >= ncols) {
					fprintf(fp, ",\n%*.*s",
						(int)start, (int)start, "");
					col = start;
					delim = "";
				}
				col += fprintf(fp, "%s%s", delim,
					       flt->avail[i]);
				delim = ", ";
			}
		}
		fputc('\n', fp);
	}
	fputc('\n', fp);
}

struct format_defn {
	const char *name;
	char *text;
	grecs_locus_t locus;
};

static struct grecs_symtab *format_table;

void
define_format(const char *name, const char *fmt, grecs_locus_t *loc)
{
	struct format_defn key;
	struct format_defn *ent;
	int install = 1;

	if (!format_table) {
		format_table = grecs_symtab_create_default(
			              sizeof(struct format_defn));
		if (!format_table)
			grecs_alloc_die();
	}
  
	key.name = (char*) name;
	ent = grecs_symtab_lookup_or_install(format_table, &key, &install);
	if (!ent)
		grecs_alloc_die();
	if (!install) {
		grecs_error(loc, 0, "redefinition of format \"%s\"", name);
		grecs_error(&ent->locus, 0,
			    "this is the place of the original definition");
		free(ent->text);
	}
	ent->text = grecs_strdup(fmt);
	ent->locus = *loc;
}

forlan_eval_env_t
find_format(const char *name)
{
	struct format_defn key;
	struct format_defn *defn;
	forlan_eval_env_t env;
	
	if (!format_table)
		return NULL;
	key.name = (char*) name;
	defn = grecs_symtab_lookup_or_install(format_table, &key, NULL);
	if (!defn)
		return NULL;
		
	env = forlan_parse_buffer(defn->text, strlen(defn->text),
				  &defn->locus.beg);
	return env;
}

static forlan_eval_env_t
read_format(struct eclat_command *cmd)
{
	forlan_eval_env_t env = NULL;

	if (format_expr_option) {
		struct grecs_locus_point pt;

		pt.file = "<tty>";
		pt.line = 1;
		pt.col = 0;

		env = forlan_parse_buffer(format_expr_option,
					  strlen(format_expr_option),
					  &pt);
	} else if (format_file_option)
		env = compile_format_file(format_file_option);
	else if (format_name_option)
		env = find_format(format_name_option);
	else if (!cmd)
		return NULL;
	else if (cmd->fmt)
		env = forlan_parse_buffer(cmd->fmt, strlen(cmd->fmt),
					  &cmd->locus.beg);
	else if (format_file) {
		const char *kwe[5];
		struct grecs_locus_point pt;
		FILE *fp;
		char *filename;
		
		kwe[0] = "command";
		kwe[1] = cmd->ident ? cmd->ident : cmd->name;
		kwe[2] = "action";
		kwe[3] = cmd->tag;
		kwe[4] = NULL;

		filename = eclat_expand_kw(format_file, kwe);
		fp = fopen(filename, "r");
		if (!fp) {
			if (errno == ENOENT) {
				debug(ECLAT_DEBCAT_MAIN, 1,
				      ("cannot open format source \"%s\": %s",
				       filename, strerror(errno)));
				free(filename);
				return NULL;
			}
			die(EX_UNAVAILABLE,
			    "cannot open format file %s: %s",
			    filename, strerror(errno));
		}
		
		pt.file = filename;
		pt.line = 1;
		pt.col = 0;

		env = forlan_parse_file(fp, &pt);
		fclose(fp);
		free(filename);
	} else
		return NULL;
	
	if (!env)
		exit(EX_UNAVAILABLE);
	return env;
}

int
eclat_do_command(eclat_command_env_t *env, struct eclat_command *command,
		 int argc, char **argv)
{
	int rc;
	
	if (!(command->flags & CMD_NOQRY)) {
		env->query = eclat_query_create(use_ssl ? EC2_QF_HTTPS : 0,
						endpoint, "/");
		eclat_query_add_param(env->query, "Action", command->tag);
	}
	
	rc = command->handler(env, argc, argv);
			
	if (rc == 0 && !(command->flags & CMD_NOQRY)) {
		if (!eclat_confirm(confirm_mode,
				   "Proceed with %s", command->ident))
			die(EX_CANCELLED, "command not confirmed");
		rc = eclat_send_query(env->curl, env->query);
	}
	return rc;
}

int
main(int argc, char **argv)
{
	int rc;
	struct grecs_node *tree;
	CURL *curl;
	XML_Parser parser;
	eclat_partial_tree_t part;
	struct grecs_node *xmltree;
	forlan_eval_env_t env = NULL;
	struct eclat_command *command = NULL; 
	eclat_command_env_t cmdenv;
	
	set_program_name(argv[0]);
	proginfo.print_help_hook = listcmdhook;
	debug_init();
	forlan_init();
	eclat_map_init();
	eclat_map_drv_register(&eclat_map_drv_null);
	eclat_map_drv_register(&eclat_map_drv_file);
	eclat_map_drv_register(&eclat_map_drv_seq);
	eclat_map_drv_register(&eclat_map_drv_bidi);
#ifdef WITH_GDBM
	eclat_map_drv_register(&eclat_map_drv_gdbm);
#endif
#ifdef WITH_LDAP
	eclat_map_drv_register(&eclat_map_drv_ldap);
#endif
	sortcmds();
	config_init();
	parse_options(&argc, &argv);

	if (match_command_mode) {
		if (argc > 1)
			die(EX_USAGE, "wrong number of arguments");
		print_matching_commands(argc == 1 ? argv[0] : "");
		return 0;
	}
	
	if (argc && !test_map_name) {
		command = find_command_name(argv[0]);
		if (!command)
			die(EX_USAGE, "unrecognized command");
	}
	
	grecs_gram_trace(debug_level(ECLAT_DEBCAT_CFGRAM));
	grecs_lex_trace(debug_level(ECLAT_DEBCAT_CFLEX));

	if (preprocess_only)
		exit(grecs_preproc_run(conffile, grecs_preprocessor) ?
		     EX_CONFIG : 0);

	if (access(conffile, R_OK) == 0) {
		tree = grecs_parse(conffile);
		if (!tree)
			exit(EX_CONFIG);
		config_finish(tree);
		/* Prevent texttab from being freed by grecs_tree_free.
		   FIXME: A dirty kludge, needed to preserve file names
		   in locus structures. A proper solution would be to have
		   our own texttab for that purpose. */
		tree->v.texttab = NULL;
		grecs_tree_free(tree);
	} else if (errno == ENOENT) {
		warn("no configuration file");
		run_config_finish_hooks();
	} else
		die(errno == EACCES ? EX_NOPERM : EX_OSFILE,
		    "cannot access \"%s\": %s",
		    conffile, strerror(errno));

	if (translate_option != -1)
		translation_enabled = translate_option;
	
	if (test_map_name) {
		int i;

		if (argc < 1)
			die(EX_USAGE, "wrong number of arguments");
		translate_ids(argc, argv, test_map_name);
		for (i = 0; i < argc; i++) {
			printf("%s\n", argv[i]);
		}
		return 0;
	}

	env = read_format(command);
	
	if (lint_mode)
		exit(0);

	if (!command)
		die(EX_USAGE, "no command given");

	if (region_name) {
		endpoint = region_to_endpoint(region_name);
		if (!endpoint) 			
			die(EX_USAGE,
			    "cannot find endpoint for region %s", region_name);
	}
	
	if (!secret_key) {
		if (get_access_creds(access_key, &access_key, &secret_key))
			die(EX_UNAVAILABLE,
			    "cannot find authentication credentials");
	}
	debug(ECLAT_DEBCAT_MAIN, 1, ("using access key %s", access_key));
	
	curl = curl_easy_init();
	if (!curl)
		die(EX_UNAVAILABLE, "curl_easy_init failed");

	if (debug_level(ECLAT_DEBCAT_CURL)) {
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
		if (debug_level(ECLAT_DEBCAT_CURL) > 1)
			curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
					 eclat_trace_fun);
	}
		
	/* Create XML parser */
	parser = XML_ParserCreate("UTF-8");
	if (!parser)
		die(EX_SOFTWARE, "cannot create XML parser");

	XML_SetElementHandler(parser,
			      eclat_partial_tree_start_handler,
			      eclat_partial_tree_end_handler);
	XML_SetCharacterDataHandler(parser,
				    eclat_partial_tree_data_handler);
	part = eclat_partial_tree_create();
	XML_SetUserData(parser, part);

	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, parser);
	if (use_ssl) {
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER,
				 (long) ssl_verify_peer);
		if (ssl_verify_peer) {
			if (ssl_ca_file)
				curl_easy_setopt(curl, CURLOPT_CAINFO,
						 ssl_ca_file);
			if (ssl_ca_path)
				curl_easy_setopt(curl, CURLOPT_CAPATH,
						 ssl_ca_path);
		}
	}
	
	if (confirm_mode == eclat_confirm_unspecified)
		confirm_mode = command->confirm;

	/* Prepare environment */
	memset(&cmdenv, 0, sizeof(cmdenv));
	cmdenv.cmd = command;
	cmdenv.curl = curl;

	rc = eclat_do_command(&cmdenv, command, argc, argv);
	if (rc)
		exit(rc);
	
	curl_easy_cleanup(curl);
	XML_Parse(parser, "", 0, 1);
	if (xml_dump_file)
		fclose(xml_dump_file);
	
	xmltree = eclat_partial_tree_finish(part);

	if (sort_option)
		grecs_tree_sort(xmltree, node_ident_cmp);
	
	if (dry_run_mode)
		/* nothing */;
	else if (env) {
		rc = forlan_run(env, xmltree);
	} else {
		grecs_print_node(xmltree, GRECS_NODE_FLAG_DEFAULT, stdout);
		fputc('\n', stdout);
	}
	
	eclat_map_free_all();
	
	exit(rc);
}

Return to:

Send suggestions and report system problems to the System administrator.