aboutsummaryrefslogtreecommitdiff
path: root/src/util.c
blob: 24b46ab431f2cbb5a972e2241e338bd110eb606a (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
/* This file is part of Eclat.
   Copyright (C) 2012-2018 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"
#include "grecs/json.h"
#include <termios.h>
#include <sys/ioctl.h>
#include <sys/stat.h>

int translation_enabled;
char *custom_map;

void
translate_ids(int argc, char **argv, const char *mapname)
{
	int i;
	struct eclat_map *map;
	char *val;
	char *q, *realname;
	int dir;
	int rc;
	
	if (!translation_enabled || argc == 0)
		return;
	if (custom_map)
		mapname = custom_map;

	dir = eclat_map_name_split(mapname, &realname, &q);
	if (dir == -1)
		die(EX_USAGE, "bad qualifier: %s", q);
	
	map = eclat_map_lookup(realname);
	if (!map) {
		debug(ECLAT_DEBCAT_MAIN, 1,
		      ("no such map: %s", realname));
		return;
	}
	
	if (eclat_map_open(map) != eclat_map_ok)
		die(EX_UNAVAILABLE, "failed to open map %s", realname);
	
	free(realname);

	for (i = 0; i < argc; i++) {
		if (!strchr(argv[i], '=')) {
			switch (rc = eclat_map_get(map, dir, argv[i], &val)) {
			case eclat_map_ok:
				argv[i] = val;
				break;

			case eclat_map_not_found:
				debug(ECLAT_DEBCAT_MAIN, 1,
				      ("%s not found in map %s",
				       argv[i], mapname));
				break;

			default:
				die(EX_UNAVAILABLE, "cannot translate %s: %s",
				    argv[i], eclat_map_strerror(rc));
			}
		}
	}
}

char *
eclat_stpcpy(char *p, char *q)
{
	while ((*p = *q++))
		++p;
	return p;
}

#define RESOURCE_ID_PFX "resource-id="
#define RESOURCE_ID_LEN (sizeof(RESOURCE_ID_PFX) - 1)

void
translate_resource_ids(int argc, char **argv)
{
	int i, j, rc, ecnt;
	size_t len;
	struct eclat_map *map;
	char *val, *p;
	struct wordsplit ws;
	int wsflags = WRDSF_DEFFLAGS|WRDSF_DELIM;

	if (!translation_enabled || argc == 0)
		return;
	ws.ws_delim = ",";
	for (i = 0; i < argc; i++) {
		if (strncmp(argv[i], RESOURCE_ID_PFX, RESOURCE_ID_LEN))
			continue;
		if (wordsplit(argv[i] + RESOURCE_ID_LEN, &ws, wsflags))
			die(EX_SOFTWARE,
			    "error expanding argument %s: %s",
			    argv[i] + RESOURCE_ID_LEN,
			    wordsplit_strerror(&ws));
		wsflags |= WRDSF_REUSE;
		for (j = 0, ecnt = 0; j < ws.ws_wordc; j++) {
			if (!(p = strchr(ws.ws_wordv[j], ':')))
				continue;
			*p++ = 0;
			map = eclat_map_lookup(ws.ws_wordv[j]);
			if (!map)
				die(EX_UNAVAILABLE, "no such map: %s",
				    ws.ws_wordv[j]);
			if (eclat_map_open(map) != eclat_map_ok)
				die(EX_UNAVAILABLE,
				    "failed to open map %s", ws.ws_wordv[j]);
			rc = eclat_map_get(map, MAP_DIR, p, &val);
			if (rc != eclat_map_ok) {
				die(EX_UNAVAILABLE,
				    "cannot translate %s using map %s: %s",
				    p, ws.ws_wordv[j], eclat_map_strerror(rc));
			}
			free(ws.ws_wordv[j]);
			ws.ws_wordv[j] = val;
			ecnt++;
		}
		if (ecnt == 0)
			continue;
		len = RESOURCE_ID_LEN + ws.ws_wordc - 1;
		for (j = 0; j < ws.ws_wordc; j++)
			len += strlen(ws.ws_wordv[j]);
		val = grecs_malloc(len + 1);
		strcpy(val, RESOURCE_ID_PFX);
		p = val + RESOURCE_ID_LEN;
		for (j = 0; j < ws.ws_wordc; j++) {
			if (j)
				*p++ = ',';
			p = eclat_stpcpy(p, ws.ws_wordv[j]);
		}
		argv[i] = val;
	}
	if (wsflags & WRDSF_REUSE)
		wordsplit_free(&ws);
}

int
get_scr_cols()
{
	struct winsize ws;

	ws.ws_col = ws.ws_row = 0;
	if ((ioctl(1, TIOCGWINSZ, (char *) &ws) < 0) || ws.ws_col == 0) {
		const char *p = getenv ("COLUMNS");
		if (p)
			ws.ws_col = strtol(p, NULL, 10);
	}
	return ws.ws_col ? ws.ws_col : 80;
}


void
describe_request_update(eclat_command_env_t *env, int argc, char **argv,    
			const char *uparm, int n_in, int *n_out)
{
	int i, j, k;
	struct ec2_request *q = env->request;
	char *bufptr = NULL;
	size_t bufsize = 0;
	struct wordsplit ws;
	int wsflags;
	int upn = 0;
	
	ws.ws_delim = ",";
	wsflags = WRDSF_DEFFLAGS | WRDSF_DELIM;
	for (i = 0, j = n_in; i < argc; i++) {
		char *p = strchr(argv[i], '=');
		if (!p) {
			if (uparm) {
				grecs_asprintf(&bufptr, &bufsize,
					       "%s.%d", uparm, upn++);
				eclat_request_add_param(q, bufptr, argv[i]);
				continue;
			}
			die(EX_USAGE, "malformed filter: %s", argv[i]);
		}
		*p++ = 0;
		grecs_asprintf(&bufptr, &bufsize, "Filter.%d.Name", j);
		eclat_request_add_param(q, bufptr, argv[i]);
		
		if (wordsplit(p, &ws, wsflags))
			die(EX_SOFTWARE, "wordsplit failed at \"%s\": %s",
			    p, wordsplit_strerror(&ws));
		wsflags |= WRDSF_REUSE;

		for (k = 0; k < ws.ws_wordc; k++) {
			grecs_asprintf(&bufptr, &bufsize, "Filter.%d.Value.%d",
				       j, k+1);
			eclat_request_add_param(q, bufptr, ws.ws_wordv[k]);
		}
		++j;
	}
	if (wsflags & WRDSF_REUSE)
		wordsplit_free(&ws);
	free(bufptr);
	if (n_out)
		*n_out = j;
}

void
describe_request_create(eclat_command_env_t *env, int argc, char **argv,    
			const char *uparm)
{
	describe_request_update(env, argc, argv, uparm, 1, NULL);
}

unsigned long max_retry_sleep = 600;
unsigned long max_retry_time = 1800;

int
eclat_send_request(struct ec2_request *orig, struct grecs_node **ret_tree)
{
	char *url;
	CURLcode res;
	int ret = 0;
	struct curl_slist *headers;
	struct eclat_io *io;
	time_t endtime;
	unsigned long tts, t;
	struct grecs_node *xmltree = NULL;
	
	endtime = time(NULL) + max_retry_time;
	tts = 2;
	while (1) {
		struct grecs_node *node;
		struct ec2_request *req;

		io = eclat_io_init(0);
		if (!io) {
			err("cannot initialize IO structure");
			return -1;
		}

		/* Prepare the request */
		req = eclat_request_dup(orig);
		if (req->flags & EC2_RF_POST) {
			eclat_request_finalize(orig);
			curl_easy_setopt(io->curl, CURLOPT_POST, 1);
			curl_easy_setopt(io->curl, CURLOPT_POSTFIELDS,
					 req->postdata);
			curl_easy_setopt(io->curl, CURLOPT_POSTFIELDSIZE,
					 strlen(req->postdata));
		}
		eclat_request_sign(req, secret_key, signature_version);
		url = eclat_request_to_url(req);
		curl_easy_setopt(io->curl, CURLOPT_URL, url);
		debug(ECLAT_DEBCAT_MAIN, 1, ("using URL: %s", url));
		free(url);
		headers = NULL;
		if (req->headers) {
			struct grecs_list_entry *ep;
			struct grecs_txtacc *acc;
			int rc;
		
			acc = grecs_txtacc_create();
			
			for (ep = req->headers->head; ep; ep = ep->next) {
				struct ec2_param *p = ep->data;
				char *str;
				
				grecs_txtacc_grow_string(acc, p->name);
				grecs_txtacc_grow_char(acc, ':');
				grecs_txtacc_grow_string(acc, p->value);
				grecs_txtacc_grow_char(acc, 0);
				str = grecs_txtacc_finish(acc, 0);
				debug(ECLAT_DEBCAT_MAIN, 1, ("HDR: %s", str));
				
				headers = curl_slist_append(headers, str);
				grecs_txtacc_free_string(acc, str);
			}

			rc = curl_easy_setopt(io->curl, CURLOPT_HTTPHEADER,
					      headers);
			grecs_txtacc_free(acc);

			if (rc)
				die(EX_SOFTWARE,
				    "failed to add headers: %s",
				    curl_easy_strerror(rc));
		}

		if (req->flags & EC2_RF_POST)
			debug(ECLAT_DEBCAT_MAIN, 1,
			      ("DATA: %s", req->postdata));
	
		if (dry_run_mode)
			debug(ECLAT_DEBCAT_MAIN, 1, ("not sending request"));
		else {
			grecs_tree_free(xmltree);
		
			res = curl_easy_perform(io->curl);
			if (res == CURLE_OK) {
				xmltree = eclat_io_finish(io);
			} else {
				err("CURL: %s", curl_easy_strerror(res));
				xmltree = NULL;
				ret = 1;
			}
		}
		eclat_io_free(io);
	
		curl_slist_free_all(headers);
		eclat_request_free(req);

		if (ret || time(NULL) >= endtime)
			break;
		
		node = grecs_find_node(xmltree, ".Response.Errors.Error.Code");
		if (!node)
			break;
		if (node->type != grecs_node_stmt
		    || node->v.value->type != GRECS_TYPE_STRING) {
			err("unexpectedly formatted error code");
			break;
		}
		
		if (strcmp(node->v.value->v.string, "RequestLimitExceeded"))
			break;

		t = random() % tts + 1;
		warn("request limit exceeded; sleeping for %lu seconds", t);
		sleep(t);
		if (tts < max_retry_sleep) {
			tts <<= 1;
			if (tts == 0 || tts > max_retry_sleep)
				tts = max_retry_sleep;
		}
	}

	*ret_tree = xmltree;
	return ret;
}

int
eclat_actcmp(const char *a, const char *b)
{
	int rc = 0;
	enum { cmp_init, cmp_norm, cmp_upca, cmp_upcb } state = cmp_init;

	while (rc == 0) {
		if (!*a)
			return *b ? - *b : 0;
		if (!*b)
			return *a ? *a : 0;
		if (*a == '-') {
			a++;
			if (state == cmp_norm)
				state = cmp_upca;
			else
				state = cmp_norm;
		} else if (*b == '-') {
			b++;
			if (state == cmp_norm)
				state = cmp_upcb;
			else
				state = cmp_norm;
		} else {
			switch (state) {
			case cmp_init:
				rc = toupper(*a) - toupper(*b);
				break;

			case cmp_norm:
				rc = *a - *b;
				break;
				
			case cmp_upca:
				rc = toupper(*a) - *b;
				break;

			case cmp_upcb:
				rc = *a - toupper(*b);
				break;
			}
			a++;
			b++;
			state = cmp_norm;
		}
	}
	return rc;
}

char **available_attrs;

void
list_attrs(FILE *fp)
{
	size_t ncols = get_scr_cols();
	int i, col, len;
	char *delim = "";
	
	fprintf(fp, "Available attributes are:\n");
	col = 0;
	for (i = 0; available_attrs[i]; i++) {
		len = strlen(delim) + strlen(available_attrs[i]);
		if (col + len > ncols) {
			fprintf(fp, ",\n%s", available_attrs[i]);
			col = strlen(available_attrs[i]);
		} else
			col += fprintf(fp, "%s%s", delim, available_attrs[i]);
		delim = ", ";
	}
	fputc('\n', fp);
	fputc('\n', fp);
}	
	
char *
canonattrname(char **attrs, const char *arg, char *delim, size_t *plen)
{
	size_t len = strlen(arg);
	int i;

	for (i = 0; attrs[i]; i++) {
		size_t alen = delim ? strcspn(attrs[i], delim)
			            : strlen(attrs[i]);
		if (alen == len && strncasecmp(arg, attrs[i], len) == 0) {
			if (plen)
				*plen = len;
			return attrs[i];
		}
	}
	return NULL;
}

char *
read_file(const char *file)
{
	char *buf = NULL;
	
	if (strcmp(file, "-") == 0) {
		struct grecs_txtacc *acc = grecs_txtacc_create();
		char inbuf[4096];
		size_t n;

		while ((n = fread(inbuf, 1, sizeof(inbuf), stdin)) > 0)
			grecs_txtacc_grow(acc, inbuf, n);
		grecs_txtacc_grow_char(acc, 0);
		if (ferror(stdin))
			die(EX_NOINPUT, "read error");
		grecs_txtacc_grow_char(acc, 0);
		buf = grecs_txtacc_finish(acc, 1);
		grecs_txtacc_free(acc);
	} else {
		struct stat st;
		FILE *fp;
	
		if (stat(file, &st))
			die(EX_USAGE, "cannot stat file %s: %s", file,
			    strerror(errno));

		/* FIXME: Use limits.h to check st.st_size */
		buf = grecs_malloc(st.st_size+1);
		fp = fopen(file, "r");
		if (!fp)
			die(EX_NOINPUT, "cannot open file %s: %s", file,
			    strerror(errno));
		if (fread(buf, st.st_size, 1, fp) != 1)
			die(EX_NOINPUT, "error reading from %s: %s", file,
			    strerror(errno));
		fclose(fp);
		buf[st.st_size] = 0;
	}
	
	return buf;
}
	
char *instance_store_base_url = "http://169.254.169.254/latest";
unsigned short instance_store_port;
char *instance_store_document_path = "dynamic/instance-identity/document";
char *instance_store_credentials_path = "meta-data/iam/security-credentials";

static CURL *
get_curl(struct grecs_txtacc *acc)
{
	CURL *curl = instance_store_curl_new(acc);
	
	eclat_set_curl_trace(curl, debug_level(ECLAT_DEBCAT_CURL));
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
	if (instance_store_port)
		curl_easy_setopt(curl, CURLOPT_PORT,
				 (long) instance_store_port);
	return curl;
}

char *
eclat_get_instance_zone()
{
	char *doc;
	struct json_value *obj, *p;
	char *retval = NULL;
	CURL *curl;
	char *url;
	struct grecs_txtacc *acc;

	acc = grecs_txtacc_create();
	curl = get_curl(acc);
	url = path_concat(instance_store_base_url,
			  instance_store_document_path);
	if (instance_store_read(url, curl))
		doc = NULL;
	else {
		grecs_txtacc_grow_char(acc, 0);
		doc = grecs_txtacc_finish(acc, 0);
	}
	free(url);
	curl_easy_cleanup(curl);
	if (!doc)
		return NULL;
	obj = json_parse_string(doc, strlen(doc));
	if (!obj) {
		char *str = NULL;
		size_t len = 0;
		grecs_asprint_locus(&str, &len, &json_err_locus);
		die(EX_DATAERR, "%s: %s", str, json_err_diag);
	}
	p = json_value_lookup(obj, "region");
	if (p && p->type == json_string)
		retval = grecs_strdup(p->v.s);
	grecs_txtacc_free(acc);
	json_value_free(obj);
	return retval;
}

void
eclat_get_instance_creds(char *id, char **access_key_ptr, char **secret_key_ptr,
			 char **token_ptr)
{
	CURL *curl;
	char *url = NULL;
	char *s;
	char *doc;
	struct json_value *obj, *p;
	int err = 0;
	struct grecs_txtacc *acc;

	acc = grecs_txtacc_create();
	curl = get_curl(acc);
	url = path_concat(instance_store_base_url,
			  instance_store_credentials_path);
	if (id) {
		s = url;
		url = path_concat(s, id);
		free(s);
	}
	if (instance_store_read(url, curl))
		die(EX_UNAVAILABLE, "url %s: not found ", url);
	else {
		grecs_txtacc_grow_char(acc, 0);
		doc = grecs_txtacc_finish(acc, 0);
	}
	if (!id) {
		size_t len = strcspn(doc, "\r\n");
		doc[len] = 0;
		s = url;
		url = path_concat(s, doc);
		free(s);
		if (instance_store_read(url, curl))
			die(EX_UNAVAILABLE, "url %s: not found ", url);
		else {
			grecs_txtacc_grow_char(acc, 0);
			doc = grecs_txtacc_finish(acc, 0);
		}
	}
	free(url);
	
	obj = json_parse_string(doc, strlen(doc));
	if (!obj) {
		char *str = NULL;
		size_t len = 0;
		grecs_asprint_locus(&str, &len, &json_err_locus);
		die(EX_DATAERR, "%s: %s", str, json_err_diag);
	}
	
	p = json_value_lookup(obj, "AccessKeyId");
	if (p && p->type == json_string)
		*access_key_ptr = grecs_strdup(p->v.s);
	else
		err = 1;
	
	p = json_value_lookup(obj, "SecretAccessKey");
	if (p && p->type == json_string)
		*secret_key_ptr = grecs_strdup(p->v.s);
	else
		err = 1;

	p = json_value_lookup(obj, "Token");
	if (p && p->type == json_string)
		*token_ptr = grecs_strdup(p->v.s);
	else
		err = 1;

	grecs_txtacc_free(acc);
	json_value_free(obj);

	if (err)
		die(EX_DATAERR, "security credentials missing");
}

Return to:

Send suggestions and report system problems to the System administrator.