kresc.c 10.5 KB
Newer Older
1
/*  Copyright (C) 2016-2017 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>
2 3 4 5 6 7 8 9 10 11 12 13 14 15

    This program 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 of the License, or
    (at your option) any later version.

    This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.
 */
16
#include <arpa/inet.h>
17
#include <assert.h>
18
#include <contrib/ccan/asprintf/asprintf.h>
19
#include <editline/readline.h>
20
#include <errno.h>
21
#include <histedit.h>
22 23 24 25
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
26
#include <string.h>
27
#include <sys/socket.h>
28
#include <sys/stat.h>
29 30
#include <sys/types.h>
#include <sys/un.h>
31
#include <unistd.h>
32

33
#define HISTORY_FILE "kresc_history"
34 35
#define PROGRAM_NAME "kresc"

36 37
FILE *g_tty = NULL;		//!< connection to the daemon

38
static char *run_cmd(const char *cmd, size_t * msg_len);
39

40
const char *prompt(EditLine * e)
41 42 43 44 45 46 47 48 49 50 51
{
	return PROGRAM_NAME "> ";
}

bool starts_with(const char *a, const char *b)
{
	if (strncmp(a, b, strlen(b)) == 0)
		return 1;
	return 0;
}

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
//! Returns Lua name of type of value, NULL on error. Puts length of type in name_len;
const char *get_type_name(const char *value)
{
	if (value == NULL) {
		return NULL;
	}

	for (int i = 0; value[i]; i++) {
		if (value[i] == ')') {
			//Return NULL to prevent unexpected function call
			return NULL;
		}
	}

	char *cmd = afmt("type(%s)", value);

	if (!cmd) {
		perror("While tab-completing.");
		return NULL;
	}

	size_t name_len;
	char *type = run_cmd(cmd, &name_len);
	if (!type) {
		return NULL;
	} else {
		free(cmd);
	}

	if (starts_with(type, "[")) {
		//Return "nil" on non-valid name.
83
		free(type);
84 85 86 87 88 89 90
		return "nil";
	} else {
		type[(strlen(type)) - 1] = '\0';
		return type;
	}
}

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
static void complete_function(EditLine * el)
{
	//Add left parenthesis to function name. 
	el_insertstr(el, "(");
}

static void complete_members(EditLine * el, const char *str,
			     const char *str_type, int str_len, char *dot)
{
	char *table = strdup(str);
	if (!table) {
		perror("While tab-completing");
		return;
	}
	//Get only the table name (without partial member name).
	if (dot) {
		*(table + (dot - str)) = '\0';
	}
	//Insert a dot after the table name.
	if (!strncmp(str_type, "table", 5)) {
		el_insertstr(el, ".");
		str_len++;
	}
	//Check if the substring before dot is a valid table name.
	const char *t_type = get_type_name(table);
	if (t_type && !strncmp("table", t_type, 5)) {
		//Get string of members of the table.
		char *cmd =
		    afmt
		    ("do local s=\"\"; for i in pairs(%s) do s=s..i..\"\\n\" end return(s) end",
		     table);
		if (!cmd) {
			perror("While tab-completing.");
			goto complete_members_exit;
		}
		size_t members_len;
		char *members = run_cmd(cmd, &members_len);
		free(cmd);
		if (!members) {
			perror("While communication with daemon");
			goto complete_members_exit;
		}
		//Split members by newline.
		char *members_tok = strdup(members);
		free(members);
		if (!members_tok) {
			goto complete_members_exit;
		}
		char *token = strtok(members_tok, "\n");
		int matches = 0;
		char *lastmatch = NULL;
		if (!dot || dot - str + 1 == strlen(str)) {
			//Prints all members.
			while (token) {
				char *member = afmt("%s.%s", table, token);
146 147 148 149 150 151 152 153 154
				const char *member_type = get_type_name(member);
				if (member && member_type) {
					printf("\n%s (%s)", member, member_type);
					free(member);
					free((void *)member_type);
				} else if (member) {
					printf("\n%s", member);
					free(member);
				}
155 156 157 158 159 160 161 162 163 164 165 166 167 168
				token = strtok(NULL, "\n");
				matches++;
			}
		} else {
			//Print members matching the current line.
			while (token) {
				if (str && starts_with(token, dot + 1)) {
					const char *member_type =
					    get_type_name(afmt
							  ("%s.%s", table,
							   token));
					if (member_type) {
						printf("\n%s.%s (%s)", table,
						       token, member_type);
169
						free((void *)member_type);
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
					} else {
						printf("\n%s.%s", table, token);
					}
					lastmatch = token;
					matches++;
				}
				token = strtok(NULL, "\n");
			}

			//Complete matching member.
			if (matches == 1) {
				el_deletestr(el, str_len);
				el_insertstr(el, table);
				el_insertstr(el, ".");
				el_insertstr(el, lastmatch);
			}
		}
		if (matches > 1) {
			printf("\n");
		}
		free(members_tok);
	}

complete_members_exit:
	free(table);
195 196 197
	if(t_type) {
		free((void*)t_type);
	}
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
}

static void complete_globals(EditLine * el, const char *str, int str_len)
{
	//Parse Lua globals.
	size_t globals_len;
	char *globals = run_cmd("_G.__orig_name_list", &globals_len);
	if (!globals) {
		perror("While tab-completing");
		return;
	}
	//Show possible globals.
	char *globals_tok = strdup(globals);
	free(globals);
	if (!globals_tok) {
		return;
	}
	char *token = strtok(globals_tok, "\n");
	int matches = 0;
	char *lastmatch = NULL;
	while (token) {
		if (str && starts_with(token, str)) {
			printf("\n%s (%s)", token, get_type_name(token));
			lastmatch = token;
			matches++;
		}
		token = strtok(NULL, "\n");
	}
	if (matches > 1) {
		printf("\n");
	}
	//Complete matching global.
	if (matches == 1) {
		el_deletestr(el, str_len);
		el_insertstr(el, lastmatch);
	}
234
	free(globals_tok);
235 236
}

237 238 239 240 241 242 243
static unsigned char complete(EditLine * el, int ch)
{
	int argc, pos;
	const char **argv;
	const LineInfo *li = el_line(el);
	Tokenizer *tok = tok_init(NULL);

244 245
	//Tokenize current line.
	int ret = tok_line(tok, li, &argc, &argv, NULL, &pos);
246

247 248 249 250 251 252 253 254 255 256 257 258 259 260
	if (ret != 0) {
		perror("While tab-completing.");
		goto complete_exit;
	}
	//Show help.
	if (argc == 0) {
		size_t help_len;
		char *help = run_cmd("help()", &help_len);
		if (help) {
			printf("\n%s", help);
			free(help);
		} else {
			perror("While communication with daemon");
		}
261 262 263
		goto complete_exit;
	}

264
	if (argc > 1) {
265 266
		goto complete_exit;
	}
267 268
	//Get name of type of current line.
	const char *type = get_type_name(argv[0]);
269

270 271 272 273 274 275 276
	if (!type) {
		goto complete_exit;
	}
	//Get position of last dot in current line (useful for parsing table).
	char *dot = strrchr(argv[0], '.');

	if (strncmp(type, "table", 5) && !dot) {
277 278
		//Line is not a name of some table and there is no dot in it.
		complete_globals(el, argv[0], pos);
279 280
	} else if ((dot && !strncmp(type, "nil", 3))
		   || !strncmp(type, "table", 5)) {
281 282
		//Current line (or part of it) is a name of some table.
		complete_members(el, argv[0], type, pos, dot);
283
	} else if (!strncmp(type, "function", 8)) {
284 285
		//Current line is a function.
		complete_function(el);
286
	}
287 288 289
	if (type) {
		free((void *)type);
	}
290 291 292 293 294 295 296

complete_exit:
	tok_reset(tok);
	tok_end(tok);
	return CC_REDISPLAY;
}

297 298 299 300 301 302 303 304 305 306 307 308
//! Initialize connection to the daemon; return 0 on success.
static int init_tty(const char *path)
{
	int fd = socket(AF_UNIX, SOCK_STREAM, 0);
	if (fd < 0)
		return 1;

	struct sockaddr_un addr;
	addr.sun_family = AF_UNIX;
	size_t plen = strlen(path);
	if (plen + 1 > sizeof(addr.sun_path)) {
		fprintf(stderr, "Path too long\n");
309
		close(fd);
310 311 312 313 314
		return 1;
	}
	memcpy(addr.sun_path, path, plen + 1);
	if (connect(fd, (const struct sockaddr *)&addr, sizeof(addr))) {
		perror("While connecting to daemon");
315
		close(fd);
316 317 318 319 320
		return 1;
	}
	g_tty = fdopen(fd, "r+");
	if (!g_tty) {
		perror("While opening TTY");
321
		close(fd);
322 323
		return 1;
	}
324

325 326 327 328
	// Switch to binary mode and consume the text "> ".
	if (fprintf(g_tty, "__binary\n") < 0 || !fread(&addr, 2, 1, g_tty)
	    || fflush(g_tty)) {
		perror("While initializing TTY");
329 330
		fclose(g_tty);
		g_tty = NULL;
331 332 333 334 335 336
		return 1;
	}

	return 0;
}

337 338
//! Run a command on the daemon; return the answer or NULL on failure, puts answer length to out_len.
static char *run_cmd(const char *cmd, size_t * out_len)
339 340 341 342 343 344 345 346 347 348
{
	if (!g_tty || !cmd) {
		assert(false);
		return NULL;
	}
	if (fprintf(g_tty, "%s", cmd) < 0 || fflush(g_tty))
		return NULL;
	uint32_t len;
	if (!fread(&len, sizeof(len), 1, g_tty))
		return NULL;
349
	len = ntohl(len);
350
	char *msg = malloc(1 + (size_t) len);
351 352
	if (!msg)
		return NULL;
353
	if (len && !fread(msg, len, 1, g_tty)) {
354 355 356
		free(msg);
		return NULL;
	}
357
	msg[len] = '\0';
358
	*out_len = len;
359 360 361 362 363
	return msg;
}

static int interact()
{
364 365 366 367 368 369
	EditLine *el;
	History *hist;
	int count;
	const char *line;
	HistEvent ev;
	el = el_init(PROGRAM_NAME, stdin, stdout, stderr);
370
	el_set(el, EL_PROMPT, prompt);
371 372 373 374 375 376 377 378 379 380 381 382 383
	el_set(el, EL_EDITOR, "emacs");
	el_set(el, EL_ADDFN, PROGRAM_NAME "-complete",
	       "Perform " PROGRAM_NAME " completion.", complete);
	el_set(el, EL_BIND, "^I", PROGRAM_NAME "-complete", NULL);

	hist = history_init();
	if (hist == 0) {
		perror("While initializing command history");
		return 1;
	}
	history(hist, &ev, H_SETSIZE, 800);
	el_set(el, EL_HIST, history, hist);

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
	char *hist_file = NULL;

	char *data_home = getenv("XDG_DATA_HOME");

	//Check whether $XDG_DATA_HOME is set.
	if (!data_home || *data_home == '\0') {
		const char *home = getenv("HOME");	//This should be set on any POSIX compliant OS, even for nobody

		//Create necessary folders.
		char *dirs[3] =
		    { afmt("%s/.local", home), afmt("%s/.local/share", home),
			afmt("%s/.local/share/kresd/", home)
		};
		bool ok = true;
		for (int i = 0; i < 3; i++) {
			if (mkdir(dirs[i], 0755) && errno != EEXIST) {
				ok = false;
				break;
			}
		}
		if (ok) {
			hist_file =
			    afmt("%s/.local/share/kresd/" HISTORY_FILE, home);
		}
	} else {
		if (!mkdir(afmt("%s/kresd/", data_home), 0755)
		    || errno == EEXIST) {
			hist_file = afmt("%s/kresd/" HISTORY_FILE, data_home);
		}
	}

	//Load history file
	if (hist_file) {
		history(hist, &ev, H_LOAD, hist_file);
	} else {
		perror("While opening history file");
	}
421

422
	while (1) {
423 424 425
		line = el_gets(el, &count);
		if (count > 0) {
			history(hist, &ev, H_ENTER, line);
426
			size_t msg_len;
427 428 429 430 431 432 433 434 435 436 437 438
			char *msg = run_cmd(line, &msg_len);
			if (!msg) {
				perror("While communication with daemon");
				history_end(hist);
				el_end(el);
				free(msg);
				return 1;
			}
			printf("%s", msg);
			if (msg_len == 0 || msg[msg_len - 1] != '\n') {
				printf("\n");
			}
439 440 441
			if (hist_file) {
				history(hist, &ev, H_SAVE, hist_file);
			}
442
			free(msg);
443 444
		}
	}
445
	history_end(hist);
446
	free(hist_file);
447
	el_end(el);
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
	if (feof(stdin))
		return 0;
	perror("While reading input");
	return 1;
}

int main(int argc, char **argv)
{
	if (argc != 2) {
		fprintf(stderr, "Usage: %s tty/xxxxx\n", argv[0]);
		return 1;
	}

	int res = init_tty(argv[1]);

	if (!res)
		res = interact();

	if (g_tty)
		fclose(g_tty);
	return res;
}