Пример #1
0
void
initedit()
{
	editing = 1;

	if (!elc && histc) {
		elc = el_init(__progname, stdin, stdout, stderr);
		el_set(elc, EL_HIST, history, histc); /* use history */
		el_set(elc, EL_EDITOR, "emacs"); /* default type */
		el_set(elc, EL_PROMPT, cprompt); /* set the prompt
						  * function */
		el_set(elc, EL_ADDFN, "complt", "Command completion", complt_c);
		el_set(elc, EL_BIND, "\t", "complt", NULL);
		el_source(elc, NULL);	/* read ~/.editrc */
		el_set(elc, EL_SIGNAL, 1);
	}
	if (!eli && histi) {
		eli = el_init(__progname, stdin, stdout, stderr); /* again */
		el_set(eli, EL_HIST, history, histi);
		el_set(eli, EL_EDITOR, "emacs");
		el_set(eli, EL_PROMPT, iprompt);
		el_set(eli, EL_ADDFN, "complt", "Command completion", complt_i);
		el_set(eli, EL_BIND, "\t", "complt", NULL);
#ifdef notyet
		el_set(eli, EL_ADDFN, "exit", "Exit", NULL);
		el_set(eli, EL_BIND, "\026", "exit", NULL);
#endif
		el_source(eli, NULL);
		el_set(eli, EL_SIGNAL, 1);
	}
}
Пример #2
0
double elementSupplier::element(int i, int j)
{ int k;
   if (elem == NULL) return(el_source(i,j));
     else
    { k = i + j * n;
       if (!elem[k])
      { elem[k] = 1;
         value[k] = el_source(i,j);
         }
      return(value[k]); 
      }
   }
Пример #3
0
void *
cmdinit(struct c**t *cmds, int ncmds)
{
	struct clitenv *env;
	HistEvent ev;

	if ((env = malloc(sizeof(*env))) == NULL)
		err(1, "Can't init cmd interpreter.");

	env->cmds = cmds;
	env->ncmds = ncmds;

	env->hist = history_init();
	history(env->hist, &ev, H_SETSIZE, 100);

	env->el = el_init(__progname, stdin, stdout, stderr);

	el_set(env->el, EL_EDITOR, "emacs");
	el_set(env->el, EL_PROMPT, prompt);
	el_set(env->el, EL_HIST, history, env->hist);
	el_set(env->el, EL_ADDFN, "complt", "complete", complt);
	el_set(env->el, EL_BIND, "\t", "complt");
	el_source(env->el, NULL);

	/* XXX - EL_SIGNAL ? */

	return env;
}
Пример #4
0
static char *fetchline(void)
{
    static EditLine *el;
    static History *hist;
    HistEvent hevent;
    char *line;
    int count;

    if (!el) {
        hist = history_init();
        history(hist, &hevent, H_SETSIZE, 100);
        el = el_init(progname, stdin, stdout, stderr);
        el_source(el, NULL);
        el_set(el, EL_SIGNAL, 1);
        el_set(el, EL_PROMPT, el_get_prompt);
        el_set(el, EL_HIST, history, (const char *)hist);
    }
    line = strdup(el_gets(el, &count));
    if (line) {
        if (count > 0) {
            line[count-1] = '\0';
        }
        if (*line) {
            history(hist, &hevent, H_ENTER, line);
        }
    }
    return line;
}
Пример #5
0
/*
 * ntp_readline_init - setup, set or reset prompt string
 */
int
ntp_readline_init(
	const char *	prompt
	)
{
	int	success;

	success = 1;

	if (prompt) {
		if (lineedit_prompt) 
			free(lineedit_prompt);
		lineedit_prompt = estrdup(prompt);
	}

#ifdef LE_EDITLINE
	if (NULL == ntp_el) {

# if 4 == EL_INIT_ARGS
		ntp_el = el_init(progname, stdin, stdout, stderr);
# else
		ntp_el = el_init(progname, stdin, stdout);
# endif
		if (ntp_el) {

			el_set(ntp_el, EL_PROMPT, ntp_prompt_callback);
			el_set(ntp_el, EL_EDITOR, "emacs");

			ntp_hist = history_init();

			if (NULL == ntp_hist) {

				mfprintf(stderr, "history_init(): %m\n");
				fflush(stderr);

				el_end(ntp_el);
				ntp_el = NULL;

				success = 0;

			} else {
				ZERO(hev);
#ifdef H_SETSIZE
				history(ntp_hist, &hev, H_SETSIZE, 128);
#endif
				el_set(ntp_el, EL_HIST, history,
				       ntp_hist);
				/* use any .editrc */
				el_source(ntp_el, NULL);
			}
		} else
			success = 0;
	}
#endif	/* LE_EDITLINE */

	ntp_readline_initted = success;

	return success;
}
Пример #6
0
/*
 * ntp_readline_init - setup, set or reset prompt string
 */
int
ntp_readline_init(
	const char *	prompt
	)
{
	int	success;

	success = 1;

	if (prompt) {
		if (lineedit_prompt) 
			free(lineedit_prompt);
		lineedit_prompt = estrdup(prompt);
	}

#ifdef LE_EDITLINE
	if (NULL == ntp_el) {

		ntp_el = el_init(progname, stdin, stdout, stderr);
		if (ntp_el) {

			el_set(ntp_el, EL_PROMPT, ntp_prompt_callback);
			el_set(ntp_el, EL_EDITOR, "emacs");

			ntp_hist = history_init();

			if (NULL == ntp_hist) {

				fprintf(stderr, "history_init(): %s\n",
						strerror(errno));
				fflush(stderr);

				el_end(ntp_el);
				ntp_el = NULL;

				success = 0;

			} else {
				memset(&hev, 0, sizeof hev);

				history(ntp_hist, &hev,	H_SETSIZE, 128);

				el_set(ntp_el, EL_HIST, history, ntp_hist);

				/* use any .editrc */
				el_source(ntp_el, NULL);
			}
		} else
			success = 0;
	}
#endif	/* LE_EDITLINE */

	ntp_readline_initted = success;

	return success;
}
Пример #7
0
static EditLine *initEditLine()
{
    EditLine    *e;
    HistEvent   ev; 

    cmdHistory = history_init(); 
    history(cmdHistory, &ev, H_SETSIZE, 100); 
    e = el_init("ejs", stdin, stdout, stderr); 
    el_set(e, EL_EDITOR, "vi");
    el_set(e, EL_HIST, history, cmdHistory);
    el_source(e, NULL);
    return e;
}
Пример #8
0
int
main(int argc, char *argv[])
{
	HistEvent he;
	static EditLine *el;
	static History *hist;
	bool interactive;

	acting_as_client = 1;
	peer = -1;
	strcpy(mode, "netascii");
	signal(SIGINT, intr);

	interactive = isatty(STDIN_FILENO);
	if (interactive) {
		el = el_init("tftp", stdin, stdout, stderr);
		hist = history_init();
		history(hist, &he, H_SETSIZE, 100);
		el_set(el, EL_HIST, history, hist);
		el_set(el, EL_EDITOR, "emacs");
		el_set(el, EL_PROMPT, command_prompt);
		el_set(el, EL_SIGNAL, 1);
		el_source(el, NULL);
	}

	if (argc > 1) {
		if (setjmp(toplevel) != 0)
			exit(txrx_error);

		if (strncmp(argv[1], "tftp://", 7) == 0) {
			urihandling(argv[1]);
			exit(txrx_error);
		}

		setpeer(argc, argv);
	}

	if (setjmp(toplevel) != 0) {
		if (interactive)
			el_reset(el);
		(void)putchar('\n');
	}

	init_options();
	command(interactive, el, hist, &he);
}
Пример #9
0
void repl::init_editline(FILE * infile, FILE * outfile) noexcept {
    setlocale(LC_CTYPE, "");

    hist = history_init();
    history(hist, &ev, H_SETSIZE, 100);

    el = el_init("./MoNS", infile, outfile, outfile);
    el_set(el, EL_EDITOR, "vi");
    // el_set(el, EL_PROMPT_ESC,
    //        +[](EditLine *el) -> const char * {
    //          const char *prompt = "λ ";
    //          return prompt;
    //        },
    //        '\1');
    el_set(el, EL_PROMPT_ESC, &prompt, '\1');
    el_set(el, EL_HIST, history, hist);
    el_source(el, NULL);
}
Пример #10
0
int
inputrc(int argc, char **argv)
{
	if (argc != 2) {
		out2str("usage: inputrc file\n");
		return 1;
	}
	if (el != NULL) {
		if (el_source(el, argv[1])) {
			out2str("inputrc: failed\n");
			return 1;
		} else
			return 0;
	} else {
		out2str("sh: inputrc ignored, not editing\n");
		return 1;
	}
}
Пример #11
0
int
main(int argc, char **argv)
{
	EditLine *el;
	History *hist;
	const char *buf;
	int num, state;
	
	check_args(argc, argv);
	if(connect_uri)
	{
		sql_conn = sql_connect(connect_uri);
		if(!sql_conn)
		{
			fprintf(stderr, "%s: [%s] %s\n", short_program_name, sql_sqlstate(NULL), sql_error(NULL));
			exit(EXIT_FAILURE);
		}
	}
	fprintf(stderr, "%s interactive SQL shell (%s)\n\n", PACKAGE, VERSION);
	fprintf(stderr, 
		"Type:  \\c URI to establish a new connection\n"
		"       \\g or ; to execute query\n"
		"       \\G to execute the query showing results in long format\n"
		"       \\q to end the SQL session\n"
		"\n"
		);
	hist = history_init();
	el = el_init(argv[0], stdin, stdout, stderr);
	el_set(el, EL_EDITOR, "emacs");
	el_set(el, EL_SIGNAL, 1);
	el_set(el, EL_PROMPT, prompt);
	el_set(el, EL_HIST, history, hist);
	el_source(el, NULL);
	while((buf = el_gets(el, &num)) != NULL && num != 0)
	{
		state = parse_query(buf);
		if(state == 0)
		{
			exec_queries(hist);
		}
	}
	return 0;
}
Пример #12
0
static PyObject *
read_init_file(EditLineObject *self, PyObject *args)
{
    PyObject *filename_obj = Py_None, *filename_bytes;
    
    if (!PyArg_ParseTuple(args, "|O:read_init_file", &filename_obj))
        return NULL;
    
    if (filename_obj == Py_None)
	return NULL;

    if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
	return NULL;

    errno = el_source(self->el, PyBytes_AsString(filename_bytes));

    Py_DECREF(filename_bytes);
    if (errno)
        return PyErr_SetFromErrno(PyExc_IOError);
    Py_RETURN_NONE;
}
Пример #13
0
IoEditLine *IoEditLine_proto(void *state)
{
	IoMethodTable methodTable[] = {
		{"hasEditLib", IoEditLine_hasEditLib},
		{"readLine", IoEditLine_readLine},
		{"addHistory", IoEditLine_addHistory},
		{NULL, NULL},
	};

	IoObject *self = IoObject_new(state);
	IoObject_tag_(self, IoEditLine_newTag(state));

	/* Make sure editline returns characters in the multi-byte charset
	   of the locale */
	setlocale(LC_CTYPE, "");

	IoObject_setDataPointer_(self, io_calloc(1, sizeof(IoEditLineData)));
	DATA(self)->prompt  = IOSYMBOL("");
	DATA(self)->editline = el_init("io", stdin, stdout, stderr);
	DATA(self)->history = history_init();

	el_set(DATA(self)->editline, EL_CLIENTDATA, self);
	el_set(DATA(self)->editline, EL_HIST, history, DATA(self)->history);
	el_set(DATA(self)->editline, EL_PROMPT, promptCallback);
	el_set(DATA(self)->editline, EL_SIGNAL, 1);
	el_set(DATA(self)->editline, EL_EDITOR, "emacs");

	{
		HistEvent ev;
		history(DATA(self)->history, &ev, H_SETSIZE, 300);
	}

	el_source(DATA(self)->editline, NULL);

	IoState_registerProtoWithFunc_((IoState *)state, self, IoEditLine_proto);

	IoObject_addMethodTable_(self, methodTable);

	return self;
}
Пример #14
0
char *x_readline(const char *prompt) {
	static char buffer[1024];
	int count = 0;
	const char *cp;

	if (!el) {
		hist = history_init();
		history(hist, &ev, H_SETSIZE, HISTORY_SIZE);
		history(hist, &ev, H_SETUNIQUE, 1);

		el = el_init("GS+", stdin, stdout, stderr);
		el_set(el, EL_EDITOR, "emacs");
		el_set(el, EL_BIND, "-e", NULL, NULL, NULL);
		el_set(el, EL_HIST, history, hist);
		el_set(el, EL_PROMPT, prompt_fn);
		el_set(el, EL_SIGNAL, 1);
		el_source(el, NULL);
	}

	el_prompt = prompt;
	cp = el_gets(el, &count);
	el_prompt = NULL;
	if (count <= 0) {
		if (prompt) fputc('\n', stdout);
		return NULL;
	}
	if (count > sizeof(buffer) - 1) return "";


	memcpy(buffer, cp, count);
	cleanup_buffer(buffer, count);

	if (*buffer)
		history(hist, &ev, H_ENTER, buffer);

	return buffer;
}
Пример #15
0
int
main(int argc, char **argv)
{
	const char *fields_file = "";
	const char *config_file = "";
#if LIBEDIT_IS_UNICODE
	wchar_t wc;
#endif
	char cmd_buf[500];
	const char *cmd;
	int cmd_len;
	bool version = false;
	const char *cfile = NULL;
	size_t n;
	nmsg_res res;
	char *p;
	int i;

	axa_set_me(argv[0]);
	AXA_ASSERT(axa_parse_log_opt(NULL, "trace,off,stderr"));
	AXA_ASSERT(axa_parse_log_opt(NULL, "error,off,stderr"));
	axa_syslog_init();
	axa_set_core();
	axa_client_init(&client);

	if (strcmp(axa_prog_name, "radtool") == 0)
		mode = RAD;

	if (isatty(STDIN_FILENO))
		el_e = el_init(axa_prog_name, stdin, stdout, stderr);
	if (el_e != NULL) {
		int flag;

		if (0 > el_get(el_e, EL_EDITMODE, &flag) || !flag) {
			el_end(el_e);
			el_e = NULL;
		}
	}
	if (el_e != NULL) {
		/* prefer emacs mode but let the user choose in .editrc */
		el_set(el_e, EL_EDITOR, "emacs");
		/* bind emacs search to ^R */
		el_set(el_e, EL_BIND, "\022", "em-inc-search-prev", NULL);
		el_source(el_e, NULL);
		el_history = history_init();
		history(el_history, &el_event, H_SETSIZE, 800);
		history_get_savefile();
		history(el_history, &el_event, H_LOAD, history_savefile);
		el_set(el_e, EL_HIST, history, el_history);
		el_set(el_e, EL_PROMPT, el_prompt);
		el_set(el_e, EL_SIGNAL, 1);
		el_set(el_e, EL_GETCFN, getcfn);
	}

	while ((i = getopt(argc, argv, "hVdNF:E:S:c:n:")) != -1) {
		switch (i) {
		case 'n':
			config_file = optarg;
			break;
		case 'V':
			version = true;
			break;

		case 'h':
			usage();
			break;
		case 'd':
			++axa_debug;
			break;

		case 'N':
			no_prompt = true;
			break;

		case 'F':
			fields_file = optarg;
			break;

		case 'E':
			if (axa_tls_cipher_list(&emsg, optarg) == NULL)
				error_msg("%s", emsg.c);
			break;

		case 'S':
			if (!axa_tls_certs_dir(&emsg, optarg))
				error_msg("%s", emsg.c);
			break;

		case 'c':
			if (cfile != NULL)
				error_msg("only one -c allowed;"
					  " ignoring all but the last");
			cfile = optarg;
			break;

		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (version) {
		version_cmd(AXA_TAG_NONE, "", NULL);
		if (argc == 0)
			stop(EX_OK);
	}

	signal(SIGPIPE, SIG_IGN);
	if (el_e != NULL) {
		signal(SIGINT, sigint);
		signal(SIGTERM, sigterm);
		signal(SIGHUP, sigterm);
	}

	AXA_DEBUG_TO_NMSG(axa_debug);
	res = nmsg_init();
	if (res != nmsg_res_success) {
		error_msg("nmsg_init(): %s", nmsg_res_lookup(res));
		exit(EX_SOFTWARE);
	}
	nmsg_input = nmsg_input_open_null();
	AXA_ASSERT(nmsg_input != NULL);
	nmsg_pres = nmsg_output_open_pres(STDOUT_FILENO);

	axa_load_fields(fields_file);
	if (!axa_load_client_config(&emsg, config_file)) {
			axa_error_msg("can't load config file: %s", emsg.c);
			exit(EXIT_FAILURE);
	}

	/* Answer commands from the control file. */
	if (cfile != NULL) {
		axa_asprintf(&p, "source %s", cfile);
		if (el_e != NULL)
			history(el_history, &el_event, H_ENTER, p);
		if (!do_cmds(p))
			error_msg(" initial \"-c %s\" failed", cfile);
		free(p);
	}

	/* Answer commands from the command line. */
	while (argc != 0) {
		if (el_e != NULL)
			history(el_history, &el_event, H_ENTER, *argv);
		if (!do_cmds(*argv)) {
			error_msg(" initial command \"%s\" failed", *argv);
			break;
		}

		++argv;
		--argc;
	}

	for (;;) {
		cmd_input.tv_sec = 0;
		fflush(stderr);
		fflush(stdout);

		if (in_file_cur > 0) {
			/* Get a command from a "sourced" file. */
			if (interrupted) {
				close_in_files();
				continue;
			}
			cmd = axa_fgetln(in_files[in_file_cur].f,
					 in_files[in_file_cur].name,
					 &in_files[in_file_cur].lineno,
					 &in_files[in_file_cur].buf,
					 &in_files[in_file_cur].buf_size);
			if (cmd == NULL) {
				close_in_file_cur();
				continue;
			}
			if (axa_debug != 0) {
				printf("< %s\n", cmd);
				fflush(stdout);
			}

		} else if (el_e != NULL) {
			/* Get a command from the terminal via editline(3). */
			cmd = el_gets(el_e, &cmd_len);
			prompt_len = 0;
			if (!interrupted) {
				if (cmd == NULL) {
					fputc('\n', stdout);
					if (cmd_len == -1)
					    error_msg("el_gets(): %s",
						      strerror(errno));
					stop(EX_OK);
				}

				/* Save nontrivial command lines. */
				if (*(cmd+strspn(cmd, AXA_WHITESPACE)) != '\0')
					history(el_history, &el_event,
						H_ENTER, cmd);
			}

		} else if (!interrupted) {
			/* Get a command from stdin. */
			n = 0;
			for (;;) {
#if LIBEDIT_IS_UNICODE
				getcfn(NULL, &wc);
				cmd_buf[n] = wctob(wc);
#else
				getcfn(NULL, &cmd_buf[n]);
#endif
				if (cmd_buf[n++] == '\n'
				    || n >= sizeof(cmd_buf)-1)
					break;
			}
			cmd_buf[n] = '\0';
			cmd = cmd_buf;
		}

		if (interrupted) {
			interrupted = false;
			if (el_e != NULL) {
				el_set(el_e, EL_UNBUFFERED, 0);
				el_reset(el_e);
				if (prompt_cleared.tv_sec != 0) {
					packet_counting = true;
					packet_count = 0;
					packet_count_total = 0;
				}
			}
			close_in_files();
			fputs(" (int)\n", stdout);
			continue;
		}

		if (!do_cmds(cmd)) {
			fputs(" ?\n", stderr);
			fflush(stdout);
			close_in_files();
		}
	}
}
Пример #16
0
/*
 * Set history and editing status.  Called whenever the status may
 * have changed (figures out what to do).
 */
void
histedit(void)
{
	FILE *el_err;

#define editing (Eflag || Vflag)

	if (iflag == 1) {
		if (!hist) {
			/*
			 * turn history on
			 */
			INTOFF;
			hist = history_init();
			INTON;

			if (hist != NULL)
				sethistsize(histsizeval());
			else
				out2str("sh: can't initialize history\n");
		}
		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
			/*
			 * turn editing on
			 */
			char *term, *shname;

			INTOFF;
			if (el_in == NULL)
				el_in = fdopen(0, "r");
			if (el_out == NULL)
				el_out = fdopen(2, "w");
			if (el_in == NULL || el_out == NULL)
				goto bad;
			el_err = el_out;
#if DEBUG
			if (tracefile)
				el_err = tracefile;
#endif
			term = lookupvar("TERM");
			if (term)
				setenv("TERM", term, 1);
			else
				unsetenv("TERM");
			shname = arg0;
			if (shname[0] == '-')
				shname++;
			el = el_init(shname, el_in, el_out, el_err);
			if (el != NULL) {
				if (hist)
					el_set(el, EL_HIST, history, hist);
				el_set(el, EL_PROMPT, getprompt);
				el_set(el, EL_SIGNAL, 1);
				el_set(el, EL_ALIAS_TEXT, alias_text, NULL);
				el_set(el, EL_ADDFN, "rl-complete",
				    "ReadLine compatible completion function",
				    _el_fn_complete);
			} else {
bad:
				out2str("sh: can't initialize editing\n");
			}
			INTON;
		} else if (!editing && el) {
			INTOFF;
			el_end(el);
			el = NULL;
			INTON;
		}
		if (el) {
			el_source(el, NULL);
			if (Vflag)
				el_set(el, EL_EDITOR, "vi");
			else if (Eflag)
				el_set(el, EL_EDITOR, "emacs");
			el_set(el, EL_BIND, "^I", 
			    tabcomplete ? "rl-complete" : "ed-insert", NULL);
		}
	} else {
		INTOFF;
		if (el) {	/* no editing if not interactive */
			el_end(el);
			el = NULL;
		}
		if (hist) {
			history_end(hist);
			hist = NULL;
		}
		INTON;
	}
}
Пример #17
0
int
main(int argc, char *argv[])
{
    EditLine *el = NULL;
    int num;
    const char *buf;
    Tokenizer *tok;
#if 0
    int lastevent = 0;
#endif
    int ncontinuation;
    History *hist;
    HistEvent ev;

    (void) setlocale(LC_CTYPE, "");
    (void) signal(SIGINT, sig);
    (void) signal(SIGQUIT, sig);
    (void) signal(SIGHUP, sig);
    (void) signal(SIGTERM, sig);

    hist = history_init();		/* Init the builtin history	*/
    /* Remember 100 events		*/
    history(hist, &ev, H_SETSIZE, 100);

    tok  = tok_init(NULL);		/* Initialize the tokenizer	*/

    /* Initialize editline		*/
    el = el_init(*argv, stdin, stdout, stderr);

    el_set(el, EL_EDITOR, "vi");	/* Default editor is vi		*/
    el_set(el, EL_SIGNAL, 1);	/* Handle signals gracefully	*/
    el_set(el, EL_PROMPT_ESC, prompt, '\1');/* Set the prompt function */

    /* Tell editline to use this history interface	*/
    el_set(el, EL_HIST, history, hist);

    /* Add a user-defined function	*/
    el_set(el, EL_ADDFN, "ed-complete", "Complete argument", complete);

    /* Bind tab to it 		*/
    el_set(el, EL_BIND, "^I", "ed-complete", NULL);

    /*
     * Bind j, k in vi command mode to previous and next line, instead
     * of previous and next history.
     */
    el_set(el, EL_BIND, "-a", "k", "ed-prev-line", NULL);
    el_set(el, EL_BIND, "-a", "j", "ed-next-line", NULL);

    /*
     * Source the user's defaults file.
     */
    el_source(el, NULL);

    while ((buf = el_gets(el, &num)) != NULL && num != 0)  {
        int ac, cc, co;
#ifdef DEBUG
        int i;
#endif
        const char **av;
        const LineInfo *li;
        li = el_line(el);
#ifdef DEBUG
        (void) fprintf(stderr, "==> got %d %s", num, buf);
        (void) fprintf(stderr, "  > li `%.*s_%.*s'\n",
                       (li->cursor - li->buffer), li->buffer,
                       (li->lastchar - 1 - li->cursor),
                       (li->cursor >= li->lastchar) ? "" : li->cursor);

#endif
        if (gotsig) {
            (void) fprintf(stderr, "Got signal %d.\n", (int)gotsig);
            gotsig = 0;
            el_reset(el);
        }

        if (!continuation && num == 1)
            continue;

        ac = cc = co = 0;
        ncontinuation = tok_line(tok, li, &ac, &av, &cc, &co);
        if (ncontinuation < 0) {
            (void) fprintf(stderr, "Internal error\n");
            continuation = 0;
            continue;
        }
#ifdef DEBUG
        (void) fprintf(stderr, "  > nc %d ac %d cc %d co %d\n",
                       ncontinuation, ac, cc, co);
#endif
#if 0
        if (continuation) {
            /*
             * Append to the right event in case the user
             * moved around in history.
             */
            if (history(hist, &ev, H_SET, lastevent) == -1)
                err(1, "%d: %s", lastevent, ev.str);
            history(hist, &ev, H_ADD , buf);
        } else {
            history(hist, &ev, H_ENTER, buf);
            lastevent = ev.num;
        }
#else
        /* Simpler */
        history(hist, &ev, continuation ? H_APPEND : H_ENTER, buf);
#endif

        continuation = ncontinuation;
        ncontinuation = 0;
        if (continuation)
            continue;
#ifdef DEBUG
        for (i = 0; i < ac; i++) {
            (void) fprintf(stderr, "  > arg# %2d ", i);
            if (i != cc)
                (void) fprintf(stderr, "`%s'\n", av[i]);
            else
                (void) fprintf(stderr, "`%.*s_%s'\n",
                               co, av[i], av[i] + co);
        }
#endif

        if (strcmp(av[0], "history") == 0) {
            int rv;

            switch (ac) {
            case 1:
                for (rv = history(hist, &ev, H_LAST); rv != -1;
                        rv = history(hist, &ev, H_PREV))
                    (void) fprintf(stdout, "%4d %s",
                                   ev.num, ev.str);
                break;

            case 2:
                if (strcmp(av[1], "clear") == 0)
                    history(hist, &ev, H_CLEAR);
                else
                    goto badhist;
                break;

            case 3:
                if (strcmp(av[1], "load") == 0)
                    history(hist, &ev, H_LOAD, av[2]);
                else if (strcmp(av[1], "save") == 0)
                    history(hist, &ev, H_SAVE, av[2]);
                break;

badhist:
            default:
                (void) fprintf(stderr,
                               "Bad history arguments\n");
                break;
            }
        } else if (el_parse(el, ac, av) == -1) {
            switch (fork()) {
            case 0:
                execvp(av[0], __DECONST(char **, av));
                perror(av[0]);
                _exit(1);
                /*NOTREACHED*/
                break;

            case -1:
                perror("fork");
                break;

            default:
                if (wait(&num) == -1)
                    perror("wait");
                (void) fprintf(stderr, "Exit %x\n", num);
                break;
            }
        }

        tok_reset(tok);
    }

    el_end(el);
    tok_end(tok);
    history_end(hist);

    return (0);
}
Пример #18
0
int
cmdloop(void)
{
    char *line;
    const char *elline;
    int cmd_argc, rval = 0, known;
#define scratch known
    char **cmd_argv;
    struct cmdtable *cmdp;
    History *hist;
    EditLine *elptr;
    HistEvent he;

    curinode = check_ginode(ROOTINO);
    curinum = ROOTINO;
    printactive(0);

    hist = history_init();
    history(hist, &he, H_SETSIZE, 100);	/* 100 elt history buffer */

    elptr = el_init("fsdb", stdin, stdout, stderr);
    el_set(elptr, EL_EDITOR, "emacs");
    el_set(elptr, EL_PROMPT, prompt);
    el_set(elptr, EL_HIST, history, hist);
    el_source(elptr, NULL);

    while ((elline = el_gets(elptr, &scratch)) != NULL && scratch != 0) {
	if (check_debug)
	    printf("command `%s'\n", elline);

	history(hist, &he, H_ENTER, elline);

	line = strdup(elline);
	cmd_argv = crack(line, &cmd_argc);
	/*
	 * el_parse returns -1 to signal that it's not been handled
	 * internally.
	 */
	if (el_parse(elptr, cmd_argc, (const char **)cmd_argv) != -1)
	    continue;
	if (cmd_argc) {
	    known = 0;
	    for (cmdp = cmds; cmdp->cmd; cmdp++) {
		if (!strcmp(cmdp->cmd, cmd_argv[0])) {
		    if ((cmdp->flags & FL_WR) == FL_WR && nflag)
			warnx("`%s' requires write access", cmd_argv[0]),
			    rval = 1;
		    else if (cmd_argc >= cmdp->minargc &&
			cmd_argc <= cmdp->maxargc)
			rval = (*cmdp->handler)(cmd_argc, cmd_argv);
		    else if (cmd_argc >= cmdp->minargc &&
			(cmdp->flags & FL_ST) == FL_ST) {
			strcpy(line, elline);
			cmd_argv = recrack(line, &cmd_argc, cmdp->maxargc);
			rval = (*cmdp->handler)(cmd_argc, cmd_argv);
		    } else
			rval = argcount(cmdp, cmd_argc, cmd_argv);
		    known = 1;
		    break;
		}
	    }
	    if (!known)
		warnx("unknown command `%s'", cmd_argv[0]), rval = 1;
	} else
	    rval = 0;
	free(line);
	if (rval < 0)
	    /* user typed "quit" */
	    return 0;
	if (rval)
	    warnx("rval was %d", rval);
    }
    el_end(elptr);
    history_end(hist);
    return rval;
}
Пример #19
0
int
main(int argc, char * const argv[])
{
    Boolean			doDNS	= FALSE;
    Boolean			doNet	= FALSE;
    Boolean			doNWI	= FALSE;
    Boolean			doPrefs	= FALSE;
    Boolean			doProxy	= FALSE;
    Boolean			doReach	= FALSE;
    Boolean			doSnap	= FALSE;
    char			*get	= NULL;
    char			*log	= NULL;
    extern int		optind;
    int			opt;
    int			opti;
    const char		*prog	= argv[0];
    char			*renew	= NULL;
    char			*set	= NULL;
    char			*nc_cmd	= NULL;
    InputRef		src;
    int			timeout	= 15;	/* default timeout (in seconds) */
    char			*wait	= NULL;
    Boolean			watch	= FALSE;
    int			xStore	= 0;	/* non dynamic store command line options */

    /* process any arguments */

    while ((opt = getopt_long(argc, argv, "dDvprt:w:W", longopts, &opti)) != -1)
        switch(opt) {
        case 'd':
            _sc_debug = TRUE;
            _sc_log   = FALSE;	/* enable framework logging */
            break;
        case 'D':
            doDispatch = TRUE;
            break;
        case 'v':
            _sc_verbose = TRUE;
            _sc_log     = FALSE;	/* enable framework logging */
            break;
        case 'p':
            enablePrivateAPI = TRUE;
            break;
        case 'r':
            doReach = TRUE;
            xStore++;
            break;
        case 't':
            timeout = atoi(optarg);
            break;
        case 'w':
            wait = optarg;
            xStore++;
            break;
        case 'W':
            watch = TRUE;
            break;
        case 0:
            if        (strcmp(longopts[opti].name, "dns") == 0) {
                doDNS = TRUE;
                xStore++;
            } else if (strcmp(longopts[opti].name, "get") == 0) {
                get = optarg;
                xStore++;
            } else if (strcmp(longopts[opti].name, "nc") == 0) {
                nc_cmd = optarg;
                xStore++;
            } else if (strcmp(longopts[opti].name, "net") == 0) {
                doNet = TRUE;
                xStore++;
            } else if (strcmp(longopts[opti].name, "nwi") == 0) {
                doNWI = TRUE;
                xStore++;
            } else if (strcmp(longopts[opti].name, "prefs") == 0) {
                doPrefs = TRUE;
                xStore++;
            } else if (strcmp(longopts[opti].name, "proxy") == 0) {
                doProxy = TRUE;
                xStore++;
            } else if (strcmp(longopts[opti].name, "renew") == 0) {
                renew = optarg;
                xStore++;
            } else if (strcmp(longopts[opti].name, "set") == 0) {
                set = optarg;
                xStore++;
            } else if (strcmp(longopts[opti].name, "snapshot") == 0) {
                doSnap = TRUE;
                xStore++;
            } else if (strcmp(longopts[opti].name, "log") == 0) {
                log = optarg;
                xStore++;
            } else if (strcmp(longopts[opti].name, "user") == 0) {
                username = CFStringCreateWithCString(NULL, optarg, kCFStringEncodingUTF8);
            } else if (strcmp(longopts[opti].name, "password") == 0) {
                password = CFStringCreateWithCString(NULL, optarg, kCFStringEncodingUTF8);
            } else if (strcmp(longopts[opti].name, "secret") == 0) {
                sharedsecret = CFStringCreateWithCString(NULL, optarg, kCFStringEncodingUTF8);
            }
            break;
        case '?':
        default :
            usage(prog);
        }
    argc -= optind;
    argv += optind;

    if (xStore > 1) {
        // if we are attempting to process more than one type of request
        usage(prog);
    }

    /* are we checking (or watching) the reachability of a host/address */
    if (doReach) {
        if (argc < 1) {
            usage(prog);
        }
        if (watch) {
            do_watchReachability(argc, (char **)argv);
        } else {
            do_checkReachability(argc, (char **)argv);
        }
        /* NOT REACHED */
    }

    /* are we waiting on the presense of a dynamic store key */
    if (wait) {
        do_wait(wait, timeout);
        /* NOT REACHED */
    }

    /* are we looking up the DNS configuration */
    if (doDNS) {
        do_showDNSConfiguration(argc, (char **)argv);
        /* NOT REACHED */
    }

    if (doNWI) {
        do_nwi(argc, (char**)argv);
        /* NOT REACHED */
    }

    if (doSnap) {
        if (!enablePrivateAPI
#if	!TARGET_IPHONE_SIMULATOR
                || (geteuid() != 0)
#endif	// !TARGET_IPHONE_SIMULATOR
           ) {
            usage(prog);
        }

        do_open(0, NULL);	/* open the dynamic store */
        do_snapshot(argc, (char**)argv);
        exit(0);
    }

    /* are we looking up a preference value */
    if (get) {
        if (argc != 2) {
            if (findPref(get) < 0) {
                usage(prog);
            }
        } else {
            /* need to go back one argument
             * for the filename */
            argc++;
            argv--;
        }

        do_getPref(get, argc, (char **)argv);
        /* NOT REACHED */
    }

    /* are we looking up the proxy configuration */
    if (doProxy) {
        do_showProxyConfiguration(argc, (char **)argv);
        /* NOT REACHED */
    }

    /* are we changing a preference value */
    if (set) {
        if (findPref(set) < 0) {
            usage(prog);
        }
        do_setPref(set, argc, (char **)argv);
        /* NOT REACHED */
    }

    /* verbose log */
    if (log != NULL) {
        if (strcasecmp(log, "IPMonitor")) {
            usage(prog);
        }
        do_log(log, argc, (char * *)argv);
        /* NOT REACHED */
    }
    /* network connection commands */
    if (nc_cmd) {
        if (find_nc_cmd(nc_cmd) < 0) {
            usage(prog);
        }
        do_nc_cmd(nc_cmd, argc, (char **)argv, watch);
        /* NOT REACHED */
    }

    if (doNet) {
        /* if we are going to be managing the network configuration */
        commands  = (cmdInfo *)commands_net;
        nCommands = nCommands_net;

        if (!getenv("ENABLE_EXPERIMENTAL_SCUTIL_COMMANDS")) {
            usage(prog);
        }

        do_net_init();				/* initialization */
        do_net_open(argc, (char **)argv);	/* open prefs */
    } else if (doPrefs) {
        /* if we are going to be managing the network configuration */
        commands  = (cmdInfo *)commands_prefs;
        nCommands = nCommands_prefs;

        do_dictInit(0, NULL);			/* start with an empty dictionary */
        do_prefs_init();			/* initialization */
        do_prefs_open(argc, (char **)argv);	/* open prefs */
    } else {
        /* if we are going to be managing the dynamic store */
        commands  = (cmdInfo *)commands_store;
        nCommands = nCommands_store;

        do_dictInit(0, NULL);	/* start with an empty dictionary */
        do_open(0, NULL);	/* open the dynamic store */
    }

    /* are we trying to renew a DHCP lease */
    if (renew != NULL) {
        do_renew(renew);
        /* NOT REACHED */
    }

    /* allocate command input stream */
    src = (InputRef)CFAllocatorAllocate(NULL, sizeof(Input), 0);
    src->fp = stdin;
    src->el = NULL;
    src->h  = NULL;

    if (isatty(fileno(src->fp))) {
        int		editmode	= 1;
        HistEvent	ev;
        struct termios	t;

        if (tcgetattr(fileno(src->fp), &t) != -1) {
            if ((t.c_lflag & ECHO) == 0) {
                editmode = 0;
            }
        }
        src->el = el_init(prog, src->fp, stdout, stderr);
        src->h  = history_init();

        (void)history(src->h, &ev, H_SETSIZE, INT_MAX);
        el_set(src->el, EL_HIST, history, src->h);

        if (!editmode) {
            el_set(src->el, EL_EDITMODE, 0);
        }

        el_set(src->el, EL_EDITOR, "emacs");
        el_set(src->el, EL_PROMPT, prompt);

        el_source(src->el, NULL);

        if ((el_get(src->el, EL_EDITMODE, &editmode) != -1) && editmode != 0) {
            el_set(src->el, EL_SIGNAL, 1);
        } else {
            history_end(src->h);
            src->h = NULL;
            el_end(src->el);
            src->el = NULL;
        }
    }

    while (TRUE) {
        Boolean	ok;

        ok = process_line(src);
        if (!ok) {
            break;
        }
    }

    /* close the socket, free resources */
    if (src->h)	history_end(src->h);
    if (src->el)	el_end(src->el);
    (void)fclose(src->fp);
    CFAllocatorDeallocate(NULL, src);

    exit (EX_OK);	// insure the process exit status is 0
    return 0;	// ...and make main fit the ANSI spec.
}
Пример #20
0
int
main(int argc, char **argv)
{
	struct sockaddr *sock;
	struct sockaddr_un ifsun;
	int fd, len, display, save_errno;
	unsigned TimeoutVal;
	struct sigaction act, oact;
	char *sockname = HONEYD_SOCK;
#ifdef HAVE_LIBEDIT
	EditLine *edit;
	History *hist;
	HistEvent hev = { 0, "" };
#endif
	const char *l;
	int ch;

	display = REC_SHOW;
	TimeoutVal = 2;

	while ((ch = getopt(argc, argv, "t:v")) != -1) {
		switch (ch) {
		case 't':
			TimeoutVal = (unsigned)atoi(optarg);
			break;
    
		case 'v':
			display += REC_VERBOSE;
			break;
		default:
			usage();
		}
	}

        argc -= optind;
        argv += optind;

	if (argc > 0)
		sockname = argv[0];

	sock = (struct sockaddr *)&ifsun;
	
	memset(&ifsun, '\0', sizeof (ifsun));
#ifdef HAVE_SUN_LEN
	ifsun.sun_len = strlen(sockname);
	if (ifsun.sun_len > sizeof (ifsun.sun_path) - 1)
		errx(1, "%s: path too long", sockname);
#endif /* HAVE_SUN_LEN */

	ifsun.sun_family = AF_UNIX;
	strlcpy(ifsun.sun_path, sockname, sizeof(ifsun.sun_path));

	if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
		errx(2, "cannot create local domain socket");

	TimedOut = 0;
	if (TimeoutVal) {
		act.sa_handler = Timeout;
		sigemptyset(&act.sa_mask);
		act.sa_flags = 0;
		sigaction(SIGALRM, &act, &oact);
		alarm(TimeoutVal);
	}

	if (connect(fd, sock, sizeof (ifsun)) == -1) {
		if (TimeoutVal) {
			save_errno = errno;
			alarm(0);
			sigaction(SIGALRM, &oact, 0);
			errno = save_errno;
		}
		if (TimedOut)
			warnx("timeout: cannot connect to socket %s",
			    sockname);
		else
			warn("cannot connect to socket %s", sockname);
		close(fd);
		return 3;
	}

	if (TimeoutVal) {
		alarm(0);
		sigaction(SIGALRM, &oact, 0);
	}

	/* Get Prompt ? */
	receive(fd, display);

#ifdef HAVE_LIBEDIT
	hist = history_init();
#  ifdef H_SETSIZE
	history(hist, &hev, H_SETSIZE, 20);
	edit = el_init("honeydctl", stdin, stdout, stderr);
#  else /* !H_SETSIZE */
	history(hist, H_EVENT, 20);
	edit = el_init("honeydctl", stdin, stdout);
#  endif

	el_source(edit, NULL);
	el_set(edit, EL_PROMPT, getprompt);
	el_set(edit, EL_EDITOR, "emacs");
	el_set(edit, EL_SIGNAL, 1);
	el_set(edit, EL_HIST, history, (const char *)hist);
#endif
	
#ifdef HAVE_LIBEDIT
	while ((l = smartgets(edit, &len, fd))) {
		if (len > 1)
#	ifdef H_SETSIZE
			history(hist, &hev, H_ENTER, l);
#	else
			history(hist, H_ENTER, l);
#	endif /* H_SETSIZE */
#else /* !HAVE_LIBEDIT */
	while ((l = smartgets(&len, fd))) {
		char line[128];
		if (len > 0) {
			add_history((char *)l);
			snprintf(line, sizeof(line), "%s\n", l);
			l = line;
			len++;
		}
#endif
		if(write(fd, l, len) == -1)
		{
			errx(EXIT_FAILURE, "Failed to write to file descriptor");
		}
		if (receive(fd, display) != 0)
			break;
	}
	fprintf(stderr, "Connection closed\n");
#ifdef HAVE_LIBEDIT
	el_end(edit);
	history_end(hist);
#endif
	close(fd);
    
	return 0;
}
Пример #21
0
/*
 * Set history and editing status.  Called whenever the status may
 * have changed (figures out what to do).
 */
void
histedit(void)
{

#define editing (Eflag || Vflag)

	if (iflag) {
		if (!hist) {
			/*
			 * turn history on
			 */
			INTOFF;
			hist = history_init();
			INTON;

			if (hist != NULL)
				sethistsize(histsizeval());
			else
				out2fmt_flush("sh: can't initialize history\n");
		}
		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
			/*
			 * turn editing on
			 */
			char *term;

			INTOFF;
			if (el_in == NULL)
				el_in = fdopen(0, "r");
			if (el_err == NULL)
				el_err = fdopen(1, "w");
			if (el_out == NULL)
				el_out = fdopen(2, "w");
			if (el_in == NULL || el_err == NULL || el_out == NULL)
				goto bad;
			term = lookupvar("TERM");
			if (term) {
				if (setenv("TERM", term, 1) == -1)
					error("setenv: cannot set TERM=1");
			}
			else
				unsetenv("TERM");
			el = el_init(arg0, el_in, el_out, el_err);
			if (el != NULL) {
				if (hist)
					el_set(el, EL_HIST, history, hist);
				el_set(el, EL_PROMPT, getprompt);
				el_set(el, EL_ADDFN, "rl-complete",
				    "ReadLine compatible completion function",
				    _el_fn_complete);
			} else {
bad:
				out2fmt_flush("sh: can't initialize editing\n");
			}
			INTON;
		} else if (!editing && el) {
			INTOFF;
			el_end(el);
			el = NULL;
			INTON;
		}
		if (el) {
			if (Vflag)
				el_set(el, EL_EDITOR, "vi");
			else if (Eflag)
				el_set(el, EL_EDITOR, "emacs");
			el_set(el, EL_BIND, "^I",
			    tabcomplete ? "rl-complete" : "ed-insert", NULL);
			el_source(el, NULL);
		}
	} else {
		INTOFF;
		if (el) {	/* no editing if not interactive */
			el_end(el);
			el = NULL;
		}
		if (hist) {
			history_end(hist);
			hist = NULL;
		}
		INTON;
	}
}
Пример #22
0
/*
 * Command parser.
 */
static void
cmdscanner(void)
{
	register struct cmd *c;
	static EditLine *el;
	static History *hist;
	HistEvent he;
	size_t len;
	int num;
	const char *bp;

	num = 0;
	bp = NULL;
	el = NULL;
	hist = NULL;
	for (;;) {
		if (fromatty) {
			if (!el) {
				el = el_init("lpc", stdin, stdout, stderr);
				hist = history_init();
				history(hist, &he, H_SETSIZE, 100);
				el_set(el, EL_HIST, history, hist);
				el_set(el, EL_EDITOR, "emacs");
				el_set(el, EL_PROMPT, lpc_prompt);
				el_set(el, EL_SIGNAL, 1);
				el_source(el, NULL);
				/*
				 * EditLine init may call 'cgetset()' to set a
				 * capability-db meant for termcap (eg: to set
				 * terminal type 'xterm').  Reset that now, or
				 * that same db-information will be used for
				 * printcap (giving us an "xterm" printer, with
				 * all kinds of invalid capabilities...).
				 */
				cgetset(NULL);
			}
			if ((bp = el_gets(el, &num)) == NULL || num == 0)
				quit(0, NULL);

			len = (num > MAX_CMDLINE - 1) ? MAX_CMDLINE - 1 : num;
			memcpy(cmdline, bp, len);
			cmdline[len] = 0; 
			history(hist, &he, H_ENTER, bp);

		} else {
			if (fgets(cmdline, MAX_CMDLINE, stdin) == NULL)
				quit(0, NULL);
			if (cmdline[0] == 0 || cmdline[0] == '\n')
				break;
		}

		makeargv();
		if (margc == 0)
			continue;
		if (el != NULL && el_parse(el, margc, margv) != -1)
			continue;

		c = getcmd(margv[0]);
		if (c == (struct cmd *)-1) {
			printf("?Ambiguous command\n");
			continue;
		}
		if (c == NULL) {
			printf("?Invalid command\n");
			continue;
		}
		if ((c->c_opts & LPC_PRIVCMD) && getuid() &&
		    ingroup(LPR_OPER) == 0) {
			printf("?Privileged command\n");
			continue;
		}

		/*
		 * Two different commands might have the same generic rtn
		 * (eg: "clean" and "tclean"), and just use different
		 * handler routines for distinct command-setup.  The handler
		 * routine might also be set on a generic routine for
		 * initial parameter processing.
		 */
		if (c->c_generic != NULL)
			generic(c->c_generic, c->c_opts, c->c_handler,
			    margc, margv);
		else
			(*c->c_handler)(margc, margv);
	}
}
Пример #23
0
char *lg_readline(const char *mb_prompt)
{
	static int is_init = FALSE;
	static HistoryW *hist = NULL;
	static HistEventW ev;
	static EditLine *el = NULL;

	int numc;
	size_t byte_len;
	const wchar_t *wc_line;
	char *mb_line;
	char *nl;

	if (!is_init)
	{
		size_t sz;
#define HFILE ".lg_history"
		is_init = TRUE;

		sz = mbstowcs(NULL, mb_prompt, 0) + 4;
		wc_prompt = malloc (sz*sizeof(wchar_t));
		mbstowcs(wc_prompt, mb_prompt, sz);

		hist = history_winit();    /* Init built-in history */
		history_w(hist, &ev, H_SETSIZE, 20);  /* Remember 20 events */
		history_w(hist, &ev, H_LOAD, HFILE);
		el = el_init("link-parser", stdin, stdout, stderr);

		/* By default, it comes up in vi mode, with the editor not in
		 * insert mode; and even when in insert mode, it drops back to
		 * command mode at the drop of a hat. Totally confusing/lame. */
		el_wset(el, EL_EDITOR, L"emacs");
		el_wset(el, EL_HIST, history_w, hist);
		el_wset(el, EL_PROMPT_ESC, prompt, '\1'); /* Set the prompt function */
		el_source(el, NULL); /* Source the user's defaults file. */
	}

	wc_line = el_wgets(el, &numc);

	/* Received end-of-file */
	if (numc <= 0)
	{
		el_end(el);
		history_wend(hist);
		free(wc_prompt);
		wc_prompt = NULL;
		hist = NULL;
		el = NULL;
		is_init = FALSE;
		return NULL;
	}

	if (1 < numc)
	{
		history_w(hist, &ev, H_ENTER, wc_line);
		history_w(hist, &ev, H_SAVE, HFILE);
	}
	/* fwprintf(stderr, L"==> got %d %ls", numc, wc_line); */

	byte_len = wcstombs(NULL, wc_line, 0) + 4;
	mb_line = malloc(byte_len);
	wcstombs(mb_line, wc_line, byte_len);

	/* In order to be compatible with regular libedit, we have to
	 * strip away the trailing newline, if any. */
	nl = strchr(mb_line, '\n');
	if (nl) *nl = 0x0;
	
	return mb_line;
}
Пример #24
0
int main(int argc, char *argv[])
{
	esl_handle_t handle = {{0}};
	int count = 0;
	const char *line = NULL;
	char cmd_str[1024] = "";
	esl_config_t cfg;
	cli_profile_t *profile = NULL;
	int rv = 0;

#ifndef WIN32
	char hfile[512] = "/etc/fs_cli_history";
	char cfile[512] = "/etc/fs_cli.conf";
	char dft_cfile[512] = "/etc/fs_cli.conf";
#else
	char hfile[512] = "fs_cli_history";
	char cfile[512] = "fs_cli.conf";
	char dft_cfile[512] = "fs_cli.conf";
#endif
	char *home = getenv("HOME");
	/* Vars for optargs */
	int opt;
	static struct option options[] = {
		{"help", 0, 0, 'h'},
		{"host", 1, 0, 'H'},
		{"port", 1, 0, 'P'},
		{"user", 1, 0, 'u'},
		{"password", 1, 0, 'p'},
		{"debug", 1, 0, 'd'},
		{"execute", 1, 0, 'x'},
		{"loglevel", 1, 0, 'l'},
		{"quiet", 0, 0, 'q'},
		{0, 0, 0, 0}
	};

	char temp_host[128];
	int argv_host = 0;
	char temp_user[256];
	char temp_pass[128];
	int argv_pass = 0 ;
	int argv_user = 0 ;
	int temp_port = 0;
	int argv_port = 0;
	int temp_log = -1;
	int argv_error = 0;
	int argv_exec = 0;
	char argv_command[256] = "";
	char argv_loglevel[128] = "";
	int argv_quiet = 0;
	

	strncpy(internal_profile.host, "127.0.0.1", sizeof(internal_profile.host));
	strncpy(internal_profile.pass, "ClueCon", sizeof(internal_profile.pass));
	strncpy(internal_profile.name, "internal", sizeof(internal_profile.name));
	internal_profile.port = 8021;
	set_fn_keys(&internal_profile);


	if (home) {
		snprintf(hfile, sizeof(hfile), "%s/.fs_cli_history", home);
		snprintf(cfile, sizeof(cfile), "%s/.fs_cli_conf", home);
	}
	
	signal(SIGINT, handle_SIGINT);
#ifdef SIGQUIT
	signal(SIGQUIT, handle_SIGQUIT);
#endif
	esl_global_set_default_logger(6); /* default debug level to 6 (info) */
	
	for(;;) {
		int option_index = 0;
		opt = getopt_long(argc, argv, "H:U:P:S:u:p:d:x:l:qh?", options, &option_index);
		if (opt == -1) break;
		switch (opt)
		{
			case 'H':
				esl_set_string(temp_host, optarg);
				argv_host = 1;
				break;
			case 'P':
				temp_port= atoi(optarg);
				if (temp_port > 0 && temp_port < 65536){
					argv_port = 1;
				} else {
					printf("ERROR: Port must be in range 1 - 65535\n");
					argv_error = 1;
				}
				break;
			case 'u':
				esl_set_string(temp_user, optarg);
				argv_user = 1;
				break;
			case 'p':
				esl_set_string(temp_pass, optarg);
				argv_pass = 1;
				break;
			case 'd':
				temp_log=atoi(optarg);
				if (temp_log < 0 || temp_log > 7){
					printf("ERROR: Debug level should be 0 - 7.\n");
					argv_error = 1;
				} else {
					esl_global_set_default_logger(temp_log);
				}
				break;
			case 'x':
				argv_exec = 1;
				esl_set_string(argv_command, optarg);
				break;
			case 'l':
				esl_set_string(argv_loglevel, optarg);
				break;
			case 'q':
				argv_quiet = 1;
				break;
				
			case 'h':
			case '?':
				print_banner(stdout);
				usage(argv[0]);
				return 0;
			default:
				opt = 0;
		}
	}
	
	if (argv_error){
		printf("\n");
		return usage(argv[0]);
	}

	if (!(rv = esl_config_open_file(&cfg, cfile))) {
		rv = esl_config_open_file(&cfg, dft_cfile);
	}

	if (rv) {
		char *var, *val;
		char cur_cat[128] = "";

		while (esl_config_next_pair(&cfg, &var, &val)) {
			if (strcmp(cur_cat, cfg.category)) {
				esl_set_string(cur_cat, cfg.category);
				esl_set_string(profiles[pcount].name, cur_cat);
				esl_set_string(profiles[pcount].host, "localhost");
				esl_set_string(profiles[pcount].pass, "ClueCon");
				profiles[pcount].port = 8021;
				set_fn_keys(&profiles[pcount]);
				esl_log(ESL_LOG_DEBUG, "Found Profile [%s]\n", profiles[pcount].name);
				pcount++;
			}
			
			if (!strcasecmp(var, "host")) {
				esl_set_string(profiles[pcount-1].host, val);
			} else if (!strcasecmp(var, "user")) {
				esl_set_string(profiles[pcount-1].user, val);
			} else if (!strcasecmp(var, "password")) {
				esl_set_string(profiles[pcount-1].pass, val);
			} else if (!strcasecmp(var, "port")) {
				int pt = atoi(val);
				if (pt > 0) {
					profiles[pcount-1].port = (esl_port_t)pt;
				}
			} else if (!strcasecmp(var, "debug")) {
				int dt = atoi(val);
				if (dt > -1 && dt < 8){
					 profiles[pcount-1].debug = dt;
				}	
 			} else if(!strcasecmp(var, "loglevel")) {
 				esl_set_string(profiles[pcount-1].loglevel, val);
 			} else if(!strcasecmp(var, "quiet")) {
 				profiles[pcount-1].quiet = esl_true(val);
			} else if (!strncasecmp(var, "key_F", 5)) {
				char *key = var + 5;

				if (key) {
					int i = atoi(key);
				
					if (i > 0 && i < 13) {
						profiles[pcount-1].console_fnkeys[i - 1] = strdup(val);
					}
				}
			} 
		}
		esl_config_close_file(&cfg);
	}
	
	if (optind < argc) {
		get_profile(argv[optind], &profile);
	}
	
	if (!profile) {
		if (get_profile("default", &profile)) {
			esl_log(ESL_LOG_DEBUG, "profile default does not exist using builtin profile\n");
			profile = &internal_profile;
		}
	}

	if (temp_log < 0 ) {
		esl_global_set_default_logger(profile->debug);
	}	

	if (argv_host) {
		esl_set_string(profile->host, temp_host);
	}
	if (argv_port) {
		profile->port = (esl_port_t)temp_port;
	}

	if (argv_user) {
		esl_set_string(profile->user, temp_user);
	}

	if (argv_pass) {
		esl_set_string(profile->pass, temp_pass);
	}
	
	if (*argv_loglevel) {
		esl_set_string(profile->loglevel, argv_loglevel);
		profile->quiet = 0;
	}

	esl_log(ESL_LOG_DEBUG, "Using profile %s [%s]\n", profile->name, profile->host);
	
	if (argv_host) {
		if (argv_port && profile->port != 8021) {
			snprintf(prompt_str, sizeof(prompt_str), "freeswitch@%s:%u@%s> ", profile->host, profile->port, profile->name);
		} else {
			snprintf(prompt_str, sizeof(prompt_str), "freeswitch@%s@%s> ", profile->host, profile->name);
		}
	} else {
		snprintf(prompt_str, sizeof(prompt_str), "freeswitch@%s> ", profile->name);
	}

	if (esl_connect(&handle, profile->host, profile->port, profile->user, profile->pass)) {
		esl_global_set_default_logger(7);
		esl_log(ESL_LOG_ERROR, "Error Connecting [%s]\n", handle.err);
		if (!argv_exec) usage(argv[0]);
		return -1;
	}


	if (argv_exec){
		const char *err = NULL;

		snprintf(cmd_str, sizeof(cmd_str), "api %s\n\n", argv_command);
		esl_send_recv(&handle, cmd_str);
		if (handle.last_sr_event) {
			if (handle.last_sr_event->body) {
				printf("%s\n", handle.last_sr_event->body);
			} else if ((err = esl_event_get_header(handle.last_sr_event, "reply-text")) && !strncasecmp(err, "-err", 3)) {
				printf("Error: %s!\n", err + 4);
			}
		}

		esl_disconnect(&handle);
		return 0;
	} 

	global_handle = &handle;
	global_profile = profile;

	esl_thread_create_detached(msg_thread_run, &handle);

#ifdef HAVE_EDITLINE
	el = el_init(__FILE__, stdout, stdout, stdout);
	el_set(el, EL_PROMPT, &prompt);
	el_set(el, EL_EDITOR, "emacs");

	myhistory = history_init();

	el_set(el, EL_ADDFN, "f1-key", "F1 KEY PRESS", console_f1key);
	el_set(el, EL_ADDFN, "f2-key", "F2 KEY PRESS", console_f2key);
	el_set(el, EL_ADDFN, "f3-key", "F3 KEY PRESS", console_f3key);
	el_set(el, EL_ADDFN, "f4-key", "F4 KEY PRESS", console_f4key);
	el_set(el, EL_ADDFN, "f5-key", "F5 KEY PRESS", console_f5key);
	el_set(el, EL_ADDFN, "f6-key", "F6 KEY PRESS", console_f6key);
	el_set(el, EL_ADDFN, "f7-key", "F7 KEY PRESS", console_f7key);
	el_set(el, EL_ADDFN, "f8-key", "F8 KEY PRESS", console_f8key);
	el_set(el, EL_ADDFN, "f9-key", "F9 KEY PRESS", console_f9key);
	el_set(el, EL_ADDFN, "f10-key", "F10 KEY PRESS", console_f10key);
	el_set(el, EL_ADDFN, "f11-key", "F11 KEY PRESS", console_f11key);
	el_set(el, EL_ADDFN, "f12-key", "F12 KEY PRESS", console_f12key);

	el_set(el, EL_ADDFN, "EOF-key", "EOF (^D) KEY PRESS", console_eofkey);

	el_set(el, EL_BIND, "\033OP", "f1-key", NULL);
	el_set(el, EL_BIND, "\033OQ", "f2-key", NULL);
	el_set(el, EL_BIND, "\033OR", "f3-key", NULL);
	el_set(el, EL_BIND, "\033OS", "f4-key", NULL);


	el_set(el, EL_BIND, "\033[11~", "f1-key", NULL);
	el_set(el, EL_BIND, "\033[12~", "f2-key", NULL);
	el_set(el, EL_BIND, "\033[13~", "f3-key", NULL);
	el_set(el, EL_BIND, "\033[14~", "f4-key", NULL);
	el_set(el, EL_BIND, "\033[15~", "f5-key", NULL);
	el_set(el, EL_BIND, "\033[17~", "f6-key", NULL);
	el_set(el, EL_BIND, "\033[18~", "f7-key", NULL);
	el_set(el, EL_BIND, "\033[19~", "f8-key", NULL);
	el_set(el, EL_BIND, "\033[20~", "f9-key", NULL);
	el_set(el, EL_BIND, "\033[21~", "f10-key", NULL);
	el_set(el, EL_BIND, "\033[23~", "f11-key", NULL);
	el_set(el, EL_BIND, "\033[24~", "f12-key", NULL);

	el_set(el, EL_BIND, "\004", "EOF-key", NULL);

	el_set(el, EL_ADDFN, "ed-complete", "Complete argument", complete);
	el_set(el, EL_BIND, "^I", "ed-complete", NULL);

	if (myhistory == 0) {
		esl_log(ESL_LOG_ERROR, "history could not be initialized\n");
		goto done;
	}

	history(myhistory, &ev, H_SETSIZE, 800);
	el_set(el, EL_HIST, history, myhistory);
	history(myhistory, &ev, H_LOAD, hfile);

	el_source(el, NULL);

#endif
#ifdef WIN32
	hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
	if (hStdout != INVALID_HANDLE_VALUE && GetConsoleScreenBufferInfo(hStdout, &csbiInfo)) {
		wOldColorAttrs = csbiInfo.wAttributes;
	}
#endif

	if (!argv_quiet && !profile->quiet) {
		snprintf(cmd_str, sizeof(cmd_str), "log %s\n\n", profile->loglevel);	
		esl_send_recv(&handle, cmd_str);
	}

	print_banner(stdout);

	esl_log(ESL_LOG_INFO, "FS CLI Ready.\nenter /help for a list of commands.\n");
	printf("%s\n", handle.last_sr_reply);

	while (running) {

#ifdef HAVE_EDITLINE
		line = el_gets(el, &count);
#else
		line = basic_gets(&count);
#endif

		if (count > 1) {
			if (!esl_strlen_zero(line)) {
				char *cmd = strdup(line);
				char *p;

#ifdef HAVE_EDITLINE
				const LineInfo *lf = el_line(el);
				char *foo = (char *) lf->buffer;
#endif

				if ((p = strrchr(cmd, '\r')) || (p = strrchr(cmd, '\n'))) {
					*p = '\0';
				}
				assert(cmd != NULL);

#ifdef HAVE_EDITLINE
				history(myhistory, &ev, H_ENTER, line);
#endif
				
				if (process_command(&handle, cmd)) {
					running = 0;
				}

#ifdef HAVE_EDITLINE
				el_deletestr(el, strlen(foo) + 1);
				memset(foo, 0, strlen(foo));
#endif
				free(cmd);
			}
		}

		usleep(1000);

	}

#ifdef HAVE_EDITLINE
 done:
	history(myhistory, &ev, H_SAVE, hfile);

	/* Clean up our memory */
	history_end(myhistory);
	el_end(el);
#endif

	esl_disconnect(&handle);
	
	thread_running = 0;

	return 0;
}
Пример #25
0
/*
 * Connect to ppp using either a local domain socket or a tcp socket.
 *
 * If we're given arguments, process them and quit, otherwise create two
 * threads to handle interactive mode.
 */
int
main(int argc, char **argv)
{
    struct sockaddr_un ifsun;
    int n, arg, fd, len, verbose, save_errno, hide1, hide1off, hide2;
    unsigned TimeoutVal;
    char *DoneWord = "x", *next, *start;
    struct sigaction act, oact;
    void *thread_ret;
    pthread_t mon;
    char Command[LINELEN];
    char Buffer[LINELEN];

    verbose = 0;
    TimeoutVal = 2;
    hide1 = hide1off = hide2 = 0;

    for (arg = 1; arg < argc; arg++)
        if (*argv[arg] == '-') {
            for (start = argv[arg] + 1; *start; start++)
                switch (*start) {
                    case 't':
                        TimeoutVal = (unsigned)atoi
                            (start[1] ? start + 1 : argv[++arg]);
                        start = DoneWord;
                        break;
    
                    case 'v':
                        verbose = REC_VERBOSE;
                        break;

                    case 'p':
                        if (start[1]) {
                          hide1 = arg;
                          hide1off = start - argv[arg];
                          passwd = start + 1;
                        } else {
                          hide1 = arg;
                          hide1off = start - argv[arg];
                          passwd = argv[++arg];
                          hide2 = arg;
                        }
                        start = DoneWord;
                        break;
    
                    default:
                        usage();
                }
        }
        else
            break;


    if (argc < arg + 1)
        usage();

    if (hide1) {
      char title[1024];
      int pos, harg;

      for (harg = pos = 0; harg < argc; harg++)
        if (harg == 0 || harg != hide2) {
          if (harg == 0 || harg != hide1)
            n = snprintf(title + pos, sizeof title - pos, "%s%s",
                            harg ? " " : "", argv[harg]);
          else if (hide1off > 1)
            n = snprintf(title + pos, sizeof title - pos, " %.*s",
                            hide1off, argv[harg]);
          else
            n = 0;
          if (n < 0 || n >= sizeof title - pos)
            break;
          pos += n;
        }
#ifdef __FreeBSD__
      setproctitle("-%s", title);
#else
      setproctitle("%s", title);
#endif
    }

    if (*argv[arg] == '/') {
        memset(&ifsun, '\0', sizeof ifsun);
        ifsun.sun_len = strlen(argv[arg]);
        if (ifsun.sun_len > sizeof ifsun.sun_path - 1) {
            warnx("%s: path too long", argv[arg]);
            return 1;
        }
        ifsun.sun_family = AF_LOCAL;
        strcpy(ifsun.sun_path, argv[arg]);

        if (fd = socket(AF_LOCAL, SOCK_STREAM, 0), fd < 0) {
            warnx("cannot create local domain socket");
            return 2;
        }
	if (connect(fd, (struct sockaddr *)&ifsun, sizeof(ifsun)) < 0) {
	    if (errno)
		warn("cannot connect to socket %s", argv[arg]);
	    else
		warnx("cannot connect to socket %s", argv[arg]);
	    close(fd);
	    return 3;
	}
    } else {
        char *addr, *p, *port;
	const char *caddr;
	struct addrinfo hints, *res, *pai;
        int gai;
	char local[] = "localhost";

	addr = argv[arg];
	if (addr[strspn(addr, "0123456789")] == '\0') {
	    /* port on local machine */
	    port = addr;
	    addr = local;
	} else if (*addr == '[') {
	    /* [addr]:port */
	    if ((p = strchr(addr, ']')) == NULL) {
		warnx("%s: mismatched '['", addr);
		return 1;
	    }
	    addr++;
	    *p++ = '\0';
	    if (*p != ':') {
		warnx("%s: missing port", addr);
		return 1;
	    }
	    port = ++p;
	} else {
	    /* addr:port */
	    p = addr + strcspn(addr, ":");
	    if (*p != ':') {
		warnx("%s: missing port", addr);
		return 1;
	    }
	    *p++ = '\0';
	    port = p;
	}
	memset(&hints, 0, sizeof(hints));
	hints.ai_socktype = SOCK_STREAM;
	gai = getaddrinfo(addr, port, &hints, &res);
	if (gai != 0) {
	    warnx("%s: %s", addr, gai_strerror(gai));
	    return 1;
	}
	for (pai = res; pai != NULL; pai = pai->ai_next) {
	    if (fd = socket(pai->ai_family, pai->ai_socktype,
		pai->ai_protocol), fd < 0) {
		warnx("cannot create socket");
		continue;
	    }
	    TimedOut = 0;
	    if (TimeoutVal) {
		act.sa_handler = Timeout;
		sigemptyset(&act.sa_mask);
		act.sa_flags = 0;
		sigaction(SIGALRM, &act, &oact);
		alarm(TimeoutVal);
	    }
	    if (connect(fd, pai->ai_addr, pai->ai_addrlen) == 0)
		break;
	    if (TimeoutVal) {
		save_errno = errno;
		alarm(0);
		sigaction(SIGALRM, &oact, 0);
		errno = save_errno;
	    }
	    caddr = sockaddr_ntop(pai->ai_addr);
	    if (caddr == NULL)
		caddr = argv[arg];
	    if (TimedOut)
		warnx("timeout: cannot connect to %s", caddr);
	    else {
		if (errno)
		    warn("cannot connect to %s", caddr);
		else
		    warnx("cannot connect to %s", caddr);
	    }
	    close(fd);
	}
	freeaddrinfo(res);
	if (pai == NULL)
	    return 1;
	if (TimeoutVal) {
	    alarm(0);
	    sigaction(SIGALRM, &oact, 0);
	}
    }

    len = 0;
    Command[sizeof(Command)-1] = '\0';
    for (arg++; arg < argc; arg++) {
        if (len && len < sizeof(Command)-1)
            strcpy(Command+len++, " ");
        strncpy(Command+len, argv[arg], sizeof(Command)-len-1);
        len += strlen(Command+len);
    }

    switch (Receive(fd, verbose | REC_PASSWD)) {
        case 1:
            fprintf(stderr, "Password incorrect\n");
            break;

        case 0:
            passwd = NULL;
            if (len == 0) {
                struct thread_data td;
                const char *env;
                int size;
#ifndef __OpenBSD__
                HistEvent hev = { 0, "" };
#endif

                td.hist = history_init();
                if ((env = getenv("EL_SIZE"))) {
                    size = atoi(env);
                    if (size < 0)
                      size = 20;
                } else
                    size = 20;
#ifdef __OpenBSD__
                history(td.hist, H_EVENT, size);
                td.edit = el_init("pppctl", stdin, stdout);
#else
                history(td.hist, &hev, H_SETSIZE, size);
                td.edit = el_init("pppctl", stdin, stdout, stderr);
#endif
                el_source(td.edit, NULL);
                el_set(td.edit, EL_PROMPT, GetPrompt);
                if ((env = getenv("EL_EDITOR"))) {
                    if (!strcmp(env, "vi"))
                        el_set(td.edit, EL_EDITOR, "vi");
                    else if (!strcmp(env, "emacs"))
                        el_set(td.edit, EL_EDITOR, "emacs");
                }
                el_set(td.edit, EL_SIGNAL, 1);
                el_set(td.edit, EL_HIST, history, (const char *)td.hist);

                td.ppp = fd;
                td.trm = NULL;

                /*
                 * We create two threads.  The Terminal thread does all the
                 * work while the Monitor thread simply tells the Terminal
                 * thread when ``fd'' becomes readable.  The telling is done
                 * by sending a SIGUSR1 to the Terminal thread.  The
                 * sem_select semaphore is used to prevent the monitor
                 * thread from firing excessive signals at the Terminal
                 * thread (it's abused for exit handling too - see below).
                 *
                 * The Terminal thread never uses td.trm !
                 */
                sem_init(&sem_select, 0, 0);

                pthread_create(&td.trm, NULL, Terminal, &td);
                pthread_create(&mon, NULL, Monitor, &td);

                /* Wait for the terminal thread to finish */
                pthread_join(td.trm, &thread_ret);
                fprintf(stderr, "Connection closed\n");

                /* Get rid of the monitor thread by abusing sem_select */
                timetogo = 1;
                close(fd);
                fd = -1;
                sem_post(&sem_select);
                pthread_join(mon, &thread_ret);

                /* Restore our terminal and release resources */
                el_end(td.edit);
                history_end(td.hist);
                sem_destroy(&sem_select);
            } else {
                start = Command;
                do {
                    next = strchr(start, ';');
                    while (*start == ' ' || *start == '\t')
                        start++;
                    if (next)
                        *next = '\0';
                    strcpy(Buffer, start);
                    Buffer[sizeof(Buffer)-2] = '\0';
                    strcat(Buffer, "\n");
                    if (verbose)
                        write(STDOUT_FILENO, Buffer, strlen(Buffer));
                    write(fd, Buffer, strlen(Buffer));
                    if (Receive(fd, verbose | REC_SHOW) != 0) {
                        fprintf(stderr, "Connection closed\n");
                        break;
                    }
                    if (next)
                        start = ++next;
                } while (next && *next);
                if (verbose)
                    write(STDOUT_FILENO, "quit\n", 5);
                write(fd, "quit\n", 5);
                while (Receive(fd, verbose | REC_SHOW) == 0)
                    ;
                if (verbose)
                    puts("");
            }
            break;

        default:
            warnx("ppp is not responding");
            break;
    }

    if (fd != -1)
        close(fd);
    
    return 0;
}
Пример #26
0
int
main(int argc, char *argv[])
{
	int num;
	const char *buf;
	Tokenizer *tok;
#if 0
	int lastevent = 0;
#endif
	int ncontinuation;
	History *hist;
	HistEvent ev;

	(void) signal(SIGINT, sig);
	(void) signal(SIGQUIT, sig);
	(void) signal(SIGHUP, sig);
	(void) signal(SIGTERM, sig);

	hist = history_init();		/* Init the builtin history	*/
					/* Remember 100 events		*/
	history(hist, &ev, H_SETSIZE, 100);

	tok  = tok_init(NULL);		/* Initialize the tokenizer	*/

					/* Initialize editline		*/
	el = el_init(*argv, stdin, stdout, stderr);

	el_set(el, EL_EDITOR, "vi");	/* Default editor is vi		*/
	el_set(el, EL_SIGNAL, 1);	/* Handle signals gracefully	*/
	el_set(el, EL_PROMPT, prompt);	/* Set the prompt function	*/

			/* Tell editline to use this history interface	*/
	el_set(el, EL_HIST, history, hist);

					/* Add a user-defined function	*/
	el_set(el, EL_ADDFN, "ed-complete", "Complete argument", complete);

					/* Bind tab to it 		*/
	el_set(el, EL_BIND, "^I", "ed-complete", NULL);

	/*
	 * Bind j, k in vi command mode to previous and next line, instead
	 * of previous and next history.
	 */
	el_set(el, EL_BIND, "-a", "k", "ed-prev-line", NULL);
	el_set(el, EL_BIND, "-a", "j", "ed-next-line", NULL);

	/*
	 * Source the user's defaults file.
	 */
	el_source(el, NULL);

	while ((buf = el_gets(el, &num)) != NULL && num != 0)  {
		int ac;
		const char **av;
#ifdef DEBUG
		(void) fprintf(stderr, "got %d %s", num, buf);
#endif
		if (!continuation && num == 1)
			continue;

		ncontinuation = tok_line(tok, buf, &ac, &av) > 0;
#if 0
		if (continuation) {
			/*
			 * Append to the right event in case the user
			 * moved around in history.
			 */
			if (history(hist, &ev, H_SET, lastevent) == -1)
				err(1, "%d: %s\n", lastevent, ev.str);
			history(hist, &ev, H_ADD , buf);
		} else {
			history(hist, &ev, H_ENTER, buf);
			lastevent = ev.num;
		}
#else
				/* Simpler */
		history(hist, &ev, continuation ? H_APPEND : H_ENTER, buf);
#endif

		continuation = ncontinuation;
		ncontinuation = 0;

		if (strcmp(av[0], "history") == 0) {
			int rv;

			switch (ac) {
			case 1:
				for (rv = history(hist, &ev, H_LAST); rv != -1;
				    rv = history(hist, &ev, H_PREV))
					(void) fprintf(stdout, "%4d %s",
					    ev.num, ev.str);
				break;

			case 2:
				if (strcmp(av[1], "clear") == 0)
					 history(hist, &ev, H_CLEAR);
				else
					 goto badhist;
				break;

			case 3:
				if (strcmp(av[1], "load") == 0)
					 history(hist, &ev, H_LOAD, av[2]);
				else if (strcmp(av[1], "save") == 0)
					 history(hist, &ev, H_SAVE, av[2]);
				break;

			badhist:
			default:
				(void) fprintf(stderr,
				    "Bad history arguments\n");
				break;
			}
		} else if (el_parse(el, ac, av) == -1) {
			switch (fork()) {
			case 0:
				execvp(av[0], (char *const *)av);
				perror(av[0]);
				_exit(1);
				/*NOTREACHED*/
				break;

			case -1:
				perror("fork");
				break;

			default:
				if (wait(&num) == -1)
					perror("wait");
				(void) fprintf(stderr, "Exit %x\n", num);
				break;
			}
		}

		tok_reset(tok);
	}

	el_end(el);
	tok_end(tok);
	history_end(hist);

	return (0);
}
Пример #27
0
int
main(int argc, char *argv[])
{
	EditLine *el = NULL;
	int numc, ncontinuation;
	const wchar_t *line;
	TokenizerW *tok;
	HistoryW *hist;
	HistEventW ev;
#ifdef DEBUG
	int i;
#endif

	setlocale(LC_ALL, "");

	(void)signal(SIGINT,  sig);
	(void)signal(SIGQUIT, sig);
	(void)signal(SIGHUP,  sig);
	(void)signal(SIGTERM, sig);

	hist = history_winit();		/* Init built-in history     */
	history_w(hist, &ev, H_SETSIZE, 100);	/* Remember 100 events	     */
	history_w(hist, &ev, H_LOAD, hfile);

	tok = tok_winit(NULL);			/* Init the tokenizer	     */

	el = el_init(argv[0], stdin, stdout, stderr);

	el_wset(el, EL_EDITOR, L"vi");		/* Default editor is vi	     */
	el_wset(el, EL_SIGNAL, 1);		/* Handle signals gracefully */
	el_wset(el, EL_PROMPT_ESC, prompt, '\1'); /* Set the prompt function */

	el_wset(el, EL_HIST, history_w, hist);	/* FIXME - history_w? */

					/* Add a user-defined function	*/
	el_wset(el, EL_ADDFN, L"ed-complete", L"Complete argument", complete);

					/* Bind <tab> to it */
	el_wset(el, EL_BIND, L"^I", L"ed-complete", NULL);

	/*
	* Bind j, k in vi command mode to previous and next line, instead
	* of previous and next history.
	*/
	el_wset(el, EL_BIND, L"-a", L"k", L"ed-prev-line", NULL);
	el_wset(el, EL_BIND, L"-a", L"j", L"ed-next-line", NULL);

	/* Source the user's defaults file. */
	el_source(el, NULL);

	while((line = el_wgets(el, &numc)) != NULL && numc != 0) {
		int ac, cc, co, rc;
		const wchar_t **av;

		const LineInfoW *li;
		li = el_wline(el);

#ifdef DEBUG
		(void)fwprintf(stderr, L"==> got %d %ls", numc, line);
		(void)fwprintf(stderr, L"  > li `%.*ls_%.*ls'\n",
		    (li->cursor - li->buffer), li->buffer,
		    (li->lastchar - 1 - li->cursor),
		    (li->cursor >= li->lastchar) ? L"" : li->cursor);
#endif

		if (gotsig) {
			(void)fprintf(stderr, "Got signal %d.\n", gotsig);
			gotsig = 0;
			el_reset(el);
		}

		if(!continuation && numc == 1)
			continue;	/* Only got a linefeed */

		ac = cc = co = 0;
		ncontinuation = tok_wline(tok, li, &ac, &av, &cc, &co);
		if (ncontinuation < 0) {
			(void) fprintf(stderr, "Internal error\n");
			continuation = 0;
			continue;
		}

#ifdef DEBUG
		(void)fprintf(stderr, "  > nc %d ac %d cc %d co %d\n",
			ncontinuation, ac, cc, co);
#endif
		history_w(hist, &ev, continuation ? H_APPEND : H_ENTER, line);

		continuation = ncontinuation;
		ncontinuation = 0;
		if(continuation)
			continue;

#ifdef DEBUG
		for (i = 0; i < ac; ++i) {
			(void)fwprintf(stderr, L"  > arg# %2d ", i);
			if (i != cc)
				(void)fwprintf(stderr, L"`%ls'\n", av[i]);
			else
				(void)fwprintf(stderr, L"`%.*ls_%ls'\n",
				    co, av[i], av[i] + co);
		}
#endif

		if (wcscmp (av[0], L"history") == 0) {
			switch(ac) {
			case 1:
				for(rc = history_w(hist, &ev, H_LAST);
				     rc != -1;
				     rc = history_w(hist, &ev, H_PREV))
					(void)fwprintf(stdout, L"%4d %ls",
					     ev.num, ev.str);
				break;
			case 2:
				if (wcscmp(av[1], L"clear") == 0)
					history_w(hist, &ev, H_CLEAR);
				else
					goto badhist;
				break;
			case 3:
				if (wcscmp(av[1], L"load") == 0)
					history_w(hist, &ev, H_LOAD,
					    my_wcstombs(av[2]));
				else if (wcscmp(av[1], L"save") == 0)
					history_w(hist, &ev, H_SAVE,
					    my_wcstombs(av[2]));
				else
					goto badhist;
				break;
			badhist:
			default:
				(void)fprintf(stderr,
				    "Bad history arguments\n");
				break;
			}
		} else if (el_wparse(el, ac, av) == -1) {
			switch (fork()) {
			case 0: {
				Tokenizer *ntok = tok_init(NULL);
				int nargc;
				const char **nav;
				tok_str(ntok, my_wcstombs(line), &nargc, &nav);
				execvp(nav[0],(char **)nav);
				perror(nav[0]);
				_exit(1);
				/* NOTREACHED */
				break;
			}
			case -1:
				perror("fork");
				break;
			default:
				if (wait(&rc) == -1)
					perror("wait");
				(void)fprintf(stderr, "Exit %x\n", rc);
				break;
			}
		}

		tok_wreset(tok);
	}

	el_end(el);
	tok_wend(tok);
	history_w(hist, &ev, H_SAVE, hfile);
	history_wend(hist);

	fprintf(stdout, "\n");
	return 0;
}
Пример #28
0
/*
 * Set history and editing status.  Called whenever the status may
 * have changed (figures out what to do).
 */
void
histedit(void)
{

#define editing (Eflag || Vflag)

	if (iflag) {
		if (!hist) {
			/*
			 * turn history on
			 */
			INTOFF;
			hist = history_init();
			INTON;

			if (hist != NULL)
				sethistsize(histsizeval());
			else
				out2str("sh: can't initialize history\n");
		}
		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
			/*
			 * turn editing on
			 */
			INTOFF;
			if (el_in == NULL)
				el_in = fdopen(0, "r");
			if (el_err == NULL)
				el_err = fdopen(1, "w");
			if (el_out == NULL)
				el_out = fdopen(2, "w");
			if (el_in == NULL || el_err == NULL || el_out == NULL)
				goto bad;
			el = el_init(arg0, el_in, el_out, el_err);
			if (el != NULL) {
				if (hist)
					el_set(el, EL_HIST, history, hist);
				el_set(el, EL_PROMPT, getprompt);
			} else {
bad:
				out2str("sh: can't initialize editing\n");
			}
			INTON;
		} else if (!editing && el) {
			INTOFF;
			el_end(el);
			el = NULL;
			INTON;
		}
		if (el) {
			if (Vflag)
				el_set(el, EL_EDITOR, "vi");
			else if (Eflag)
				el_set(el, EL_EDITOR, "emacs");
			el_source(el, NULL);
		}
	} else {
		INTOFF;
		if (el) {	/* no editing if not interactive */
			el_end(el);
			el = NULL;
		}
		if (hist) {
			history_end(hist);
			hist = NULL;
		}
		INTON;
	}
}
Пример #29
0
int main(int argc, char *argv[])
{
	esl_handle_t handle = {{0}};
	int count = 0;
	const char *line = NULL;
	char cmd_str[1024] = "";
	cli_profile_t *profile = NULL;
#ifndef WIN32
	char hfile[512] = "/tmp/fs_cli_history";
	char cfile[512] = "/etc/fs_cli.conf";
	char dft_cfile[512] = "/etc/fs_cli.conf";
#else
	char hfile[512] = "fs_cli_history";
	char cfile[512] = "fs_cli.conf";
	char dft_cfile[512] = "fs_cli.conf";
#endif
	char *home = getenv("HOME");
	/* Vars for optargs */
	int opt;
	static struct option options[] = {
		{"help", 0, 0, 'h'},
		{"no-color", 0, 0, 'n'},
		{"host", 1, 0, 'H'},
		{"port", 1, 0, 'P'},
		{"user", 1, 0, 'u'},
		{"password", 1, 0, 'p'},
		{"debug", 1, 0, 'd'},
		{"execute", 1, 0, 'x'},
		{"loglevel", 1, 0, 'l'},
		{"log-uuid", 0, 0, 'U'},
		{"quiet", 0, 0, 'q'},
		{"batchmode", 0, 0, 'b'},
		{"retry", 0, 0, 'r'},
		{"interrupt", 0, 0, 'i'},
		{"reconnect", 0, 0, 'R'},
		{"timeout", 1, 0, 't'},
		{"connect-timeout", 1, 0, 'T'},
		{0, 0, 0, 0}
	};
	char temp_host[128];
	int argv_host = 0;
	char temp_user[256];
	char temp_pass[128];
	int argv_pass = 0 ;
	int argv_user = 0 ;
	int temp_port = 0;
	int argv_port = 0;
	int temp_log = -1;
	int argv_error = 0;
	int argv_exec = 0;
	char argv_command[1024] = "";
	char argv_loglevel[128] = "";
	int argv_log_uuid = 0;
	int argv_quiet = 0;
	int argv_batch = 0;
	int loops = 2, reconnect = 0;
	char *ccheck;

#ifdef WIN32
	feature_level = 0;
#else
	feature_level = 1;
#endif

	if ((ccheck = getenv("FS_CLI_COLOR"))) {
		is_color = esl_true(ccheck);
	}

	strncpy(internal_profile.host, "127.0.0.1", sizeof(internal_profile.host));
	strncpy(internal_profile.pass, "ClueCon", sizeof(internal_profile.pass));
	strncpy(internal_profile.name, "internal", sizeof(internal_profile.name));
	internal_profile.port = 8021;
	set_fn_keys(&internal_profile);
	esl_set_string(internal_profile.prompt_color, prompt_color);
	esl_set_string(internal_profile.input_text_color, input_text_color);
	esl_set_string(internal_profile.output_text_color, output_text_color);
	if (home) {
		snprintf(hfile, sizeof(hfile), "%s/.fs_cli_history", home);
		snprintf(cfile, sizeof(cfile), "%s/.fs_cli_conf", home);
	}
	signal(SIGINT, handle_SIGINT);
#ifdef SIGTSTP
	signal(SIGTSTP, handle_SIGINT);
#endif
#ifdef SIGQUIT
	signal(SIGQUIT, handle_SIGQUIT);
#endif
	esl_global_set_default_logger(6); /* default debug level to 6 (info) */
	for(;;) {
		int option_index = 0;
		opt = getopt_long(argc, argv, "H:P:S:u:p:d:x:l:Ut:T:qrRhib?n", options, &option_index);
		if (opt == -1) break;
		switch (opt) {
			case 'H':
				esl_set_string(temp_host, optarg);
				argv_host = 1;
				break;
			case 'P':
				temp_port= atoi(optarg);
				if (temp_port > 0 && temp_port < 65536) {
					argv_port = 1;
				} else {
					printf("ERROR: Port must be in range 1 - 65535\n");
					argv_error = 1;
				}
				break;
			case 'n':
				is_color = 0;
				break;
			case 'u':
				esl_set_string(temp_user, optarg);
				argv_user = 1;
				break;
			case 'p':
				esl_set_string(temp_pass, optarg);
				argv_pass = 1;
				break;
			case 'd':
				temp_log=atoi(optarg);
				if (temp_log < 0 || temp_log > 7) {
					printf("ERROR: Debug level should be 0 - 7.\n");
					argv_error = 1;
				} else {
					esl_global_set_default_logger(temp_log);
				}
				break;
			case 'x':
				argv_exec = 1;
				esl_set_string(argv_command, optarg);
				break;
			case 'l':
				esl_set_string(argv_loglevel, optarg);
				break;
			case 'U':
				argv_log_uuid = 1;
				break;
			case 'q':
				argv_quiet = 1;
				break;
			case 'b':
				argv_batch = 1;
				break;
			case 'i':
				allow_ctl_c = 1;
				break;
			case 'r':
				loops += 120;
				break;
			case 'R':
				reconnect = 1;
				break;
			case 't':
				timeout = atoi(optarg);
				break;
			case 'T':
				connect_timeout = atoi(optarg);
				break;
			case 'h':
			case '?':
				print_banner(stdout, is_color);
				usage(argv[0]);
				return 0;
		}
	}
	if (argv_error) {
		printf("\n");
		return usage(argv[0]);
	}
	read_config(dft_cfile, cfile);
	if (optind < argc) {
		get_profile(argv[optind], &profile);
	}
	if (!profile) {
		if (get_profile("default", &profile)) {
			esl_log(ESL_LOG_DEBUG, "profile default does not exist using builtin profile\n");
			profile = &internal_profile;
		}
	}
	if (temp_log < 0 ) {
		esl_global_set_default_logger(profile->debug);
	}
	if (argv_host) {
		esl_set_string(profile->host, temp_host);
	}
	if (argv_port) {
		profile->port = (esl_port_t)temp_port;
	}
	if (argv_user) {
		esl_set_string(profile->user, temp_user);
	}
	if (argv_pass) {
		esl_set_string(profile->pass, temp_pass);
	}
	if (argv_batch || profile->batch_mode) {
		profile->batch_mode = 1;
		feature_level=0;
	}
	if (*argv_loglevel) {
		esl_set_string(profile->loglevel, argv_loglevel);
		profile->quiet = 0;
	}
	if (argv_log_uuid) {
		profile->log_uuid = 1;
	}
	esl_log(ESL_LOG_DEBUG, "Using profile %s [%s]\n", profile->name, profile->host);
	esl_set_string(prompt_color, profile->prompt_color);
	esl_set_string(input_text_color, profile->input_text_color);
	esl_set_string(output_text_color, profile->output_text_color);
	if (argv_host) {
		if (argv_port && profile->port != 8021) {
			snprintf(bare_prompt_str, sizeof(bare_prompt_str), "freeswitch@%s:%u@%s> ", profile->host, profile->port, profile->name);
		} else {
			snprintf(bare_prompt_str, sizeof(bare_prompt_str), "freeswitch@%s@%s> ", profile->host, profile->name);
		}
	} else {
		snprintf(bare_prompt_str, sizeof(bare_prompt_str), "freeswitch@%s> ", profile->name);
	}
	bare_prompt_str_len = (int)strlen(bare_prompt_str);
	if (feature_level) {
		snprintf(prompt_str, sizeof(prompt_str), "%s%s%s", prompt_color, bare_prompt_str, input_text_color);
	} else {
		snprintf(prompt_str, sizeof(prompt_str), "%s", bare_prompt_str);
	}
 connect:
	connected = 0;
	while (--loops > 0) {
		memset(&handle, 0, sizeof(handle));
		if (esl_connect_timeout(&handle, profile->host, profile->port, profile->user, profile->pass, connect_timeout)) {
			esl_global_set_default_logger(7);
			esl_log(ESL_LOG_ERROR, "Error Connecting [%s]\n", handle.err);
			if (loops == 1) {
				if (!argv_exec) usage(argv[0]);
				return -1;
			} else {
				sleep_s(1);
				esl_log(ESL_LOG_INFO, "Retrying\n");
			}
		} else {
			connected = 1;
			if (temp_log < 0 ) {
				esl_global_set_default_logger(profile->debug);
			} else {
				esl_global_set_default_logger(temp_log);
			}
			break;
		}
	}
	if (argv_exec) {
		const char *err = NULL;
		snprintf(cmd_str, sizeof(cmd_str), "api %s\nconsole_execute: true\n\n", argv_command);
		if (timeout) {
			esl_status_t status = esl_send_recv_timed(&handle, cmd_str, timeout);
			if (status != ESL_SUCCESS) {
				printf("Request timed out.\n");
				esl_disconnect(&handle);
				return -2;
			}
		} else {
			esl_send_recv(&handle, cmd_str);
		}
		if (handle.last_sr_event) {
			if (handle.last_sr_event->body) {
				printf("%s\n", handle.last_sr_event->body);
			} else if ((err = esl_event_get_header(handle.last_sr_event, "reply-text")) && !strncasecmp(err, "-err", 3)) {
				printf("Error: %s!\n", err + 4);
			}
		}
		esl_disconnect(&handle);
		return 0;
	}
	global_handle = &handle;
	global_profile = profile;

	if (esl_thread_create_detached(msg_thread_run, &handle) != ESL_SUCCESS) {
		printf("Error starting thread!\n");
		esl_disconnect(&handle);
		return 0;
	}

#ifdef HAVE_EDITLINE
	el = el_init(__FILE__, stdin, stdout, stderr);
	el_set(el, EL_PROMPT, &prompt);
	el_set(el, EL_EDITOR, "emacs");

	el_set(el, EL_ADDFN, "f1-key", "F1 KEY PRESS", console_f1key);
	el_set(el, EL_ADDFN, "f2-key", "F2 KEY PRESS", console_f2key);
	el_set(el, EL_ADDFN, "f3-key", "F3 KEY PRESS", console_f3key);
	el_set(el, EL_ADDFN, "f4-key", "F4 KEY PRESS", console_f4key);
	el_set(el, EL_ADDFN, "f5-key", "F5 KEY PRESS", console_f5key);
	el_set(el, EL_ADDFN, "f6-key", "F6 KEY PRESS", console_f6key);
	el_set(el, EL_ADDFN, "f7-key", "F7 KEY PRESS", console_f7key);
	el_set(el, EL_ADDFN, "f8-key", "F8 KEY PRESS", console_f8key);
	el_set(el, EL_ADDFN, "f9-key", "F9 KEY PRESS", console_f9key);
	el_set(el, EL_ADDFN, "f10-key", "F10 KEY PRESS", console_f10key);
	el_set(el, EL_ADDFN, "f11-key", "F11 KEY PRESS", console_f11key);
	el_set(el, EL_ADDFN, "f12-key", "F12 KEY PRESS", console_f12key);
	el_set(el, EL_ADDFN, "EOF-key", "EOF (^D) KEY PRESS", console_eofkey);

	el_set(el, EL_BIND, "\033OP", "f1-key", NULL);
	el_set(el, EL_BIND, "\033OQ", "f2-key", NULL);
	el_set(el, EL_BIND, "\033OR", "f3-key", NULL);
	el_set(el, EL_BIND, "\033OS", "f4-key", NULL);
	el_set(el, EL_BIND, "\033OT", "f5-key", NULL);
	el_set(el, EL_BIND, "\033OU", "f6-key", NULL);
	el_set(el, EL_BIND, "\033OV", "f7-key", NULL);
	el_set(el, EL_BIND, "\033OW", "f8-key", NULL);
	el_set(el, EL_BIND, "\033OX", "f9-key", NULL);
	el_set(el, EL_BIND, "\033OY", "f10-key", NULL);
	el_set(el, EL_BIND, "\033OZ", "f11-key", NULL);
	el_set(el, EL_BIND, "\033O[", "f12-key", NULL);

	el_set(el, EL_BIND, "\033[11~", "f1-key", NULL);
	el_set(el, EL_BIND, "\033[12~", "f2-key", NULL);
	el_set(el, EL_BIND, "\033[13~", "f3-key", NULL);
	el_set(el, EL_BIND, "\033[14~", "f4-key", NULL);
	el_set(el, EL_BIND, "\033[15~", "f5-key", NULL);
	el_set(el, EL_BIND, "\033[17~", "f6-key", NULL);
	el_set(el, EL_BIND, "\033[18~", "f7-key", NULL);
	el_set(el, EL_BIND, "\033[19~", "f8-key", NULL);
	el_set(el, EL_BIND, "\033[20~", "f9-key", NULL);
	el_set(el, EL_BIND, "\033[21~", "f10-key", NULL);
	el_set(el, EL_BIND, "\033[23~", "f11-key", NULL);
	el_set(el, EL_BIND, "\033[24~", "f12-key", NULL);

	el_set(el, EL_BIND, "\004", "EOF-key", NULL);

	el_set(el, EL_ADDFN, "ed-complete", "Complete argument", complete);
	el_set(el, EL_BIND, "^I", "ed-complete", NULL);

	/* "Delete" key. */
	el_set(el, EL_BIND, "\033[3~", "ed-delete-next-char", NULL);

	if (!(myhistory = history_init())) {
		esl_log(ESL_LOG_ERROR, "history could not be initialized\n");
		goto done;
	}
	history(myhistory, &ev, H_SETSIZE, 800);
	el_set(el, EL_HIST, history, myhistory);
	history(myhistory, &ev, H_LOAD, hfile);
	el_source(el, NULL);
#endif
#ifdef WIN32
	hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
	if (hStdout != INVALID_HANDLE_VALUE && GetConsoleScreenBufferInfo(hStdout, &csbiInfo)) {
		wOldColorAttrs = csbiInfo.wAttributes;
	}
#endif
	if (!argv_quiet && !profile->quiet) {
		snprintf(cmd_str, sizeof(cmd_str), "log %s\n\n", profile->loglevel);
		esl_send_recv(&handle, cmd_str);
	}
	if (global_profile->batch_mode) {
		setvbuf(stdout, (char*)NULL, _IONBF, 0);
	}
	print_banner(stdout, is_color);
	esl_log(ESL_LOG_INFO, "FS CLI Ready.\nenter /help for a list of commands.\n");
	output_printf("%s\n", handle.last_sr_reply);
	while (running > 0) {
		int r;
#ifdef HAVE_EDITLINE
		if (!(global_profile->batch_mode)) {
			line = el_gets(el, &count);
		} else {
#endif
		line = basic_gets(&count);
#ifdef HAVE_EDITLINE
		}
#endif
		if (count > 1 && !esl_strlen_zero(line)) {
			char *p, *cmd = strdup(line);
			assert(cmd);
			if ((p = strrchr(cmd, '\r')) || (p = strrchr(cmd, '\n'))) {
				*p = '\0';
			}
#ifdef HAVE_EDITLINE
			history(myhistory, &ev, H_ENTER, line);
#endif
			if ((r = process_command(&handle, cmd))) {
				running = r;
			}
			free(cmd);
			clear_el_buffer();
		}
		sleep_ms(1);
	}
	if (running < 0 && reconnect) {
		running = 1;
		loops = 120;
		goto connect;
	}
#ifdef HAVE_EDITLINE
 done:
	history(myhistory, &ev, H_SAVE, hfile);
	history_end(myhistory);
	el_end(el);
#endif
	esl_disconnect(&handle);
	global_handle = NULL;
	thread_running = 0;
	return 0;
}
Пример #30
0
static int
cmdloop(void)
{
	char *line = NULL;
	const char *elline;
	int cmd_argc, rval = 0, known;
#define scratch known
	char **cmd_argv;
	struct cmdtable *cmdp;
	History *hist;
	EditLine *elptr;
	HistEvent hev;

	curinode = ginode(ROOTINO);
	curinum = ROOTINO;
	printactive();

	hist = history_init();
	history(hist, &hev, H_SETSIZE, 100);	/* 100 elt history buffer */

	elptr = el_init(__progname, stdin, stdout, stderr);
	el_set(elptr, EL_EDITOR, "emacs");
	el_set(elptr, EL_PROMPT, prompt);
	el_set(elptr, EL_HIST, history, hist);
	el_source(elptr, NULL);

	while ((elline = el_gets(elptr, &scratch)) != NULL && scratch != 0) {
		if (debug)
			printf("command `%s'\n", line);

		history(hist, &hev, H_ENTER, elline);

		line = strdup(elline);
		if (line == NULL)
			errx(1, "out of memory");
		cmd_argv = crack(line, &cmd_argc);
		if (cmd_argc) {
			/*
			 * el_parse returns -1 to signal that it's not been handled
			 * internally.
			 */
			if (el_parse(elptr, cmd_argc, (const char **)cmd_argv) != -1)
				continue;
			known = 0;
			for (cmdp = cmds; cmdp->cmd; cmdp++) {
				if (!strcmp(cmdp->cmd, cmd_argv[0])) {
					if (cmd_argc >= cmdp->minargc &&
					    cmd_argc <= cmdp->maxargc)
						rval = (*cmdp->handler)(cmd_argc,
						    cmd_argv);
					else
						rval = argcount(cmdp,
						    cmd_argc, cmd_argv);
					known = 1;
					break;
				}
			}
			if (!known) {
				warnx("unknown command `%s'", cmd_argv[0]);
				rval = 1;
			}
		} else
			rval = 0;
		free(line);
		if (rval < 0)
			return rval;
		if (rval)
			warnx("rval was %d", rval);
	}
	el_end(elptr);
	history_end(hist);
	return rval;
}