예제 #1
0
파일: complete.c 프로젝트: danrl/nsh
void
endhist()
{
	if (histc) {
		history_end(histc);	/* deallocate */
		histc = NULL;
	}
	if (histi) {
		history_end(histi);
		histi = NULL;
	}
}
예제 #2
0
static int acc_el_initialize(void)
{
    HistEvent ev;

    if (el != NULL)
        el_end(el);
    if (el_hist != NULL)
        history_end(el_hist);

    el = el_init("accedian", stdin, stdout, stderr);
    el_set(el, EL_PROMPT, cli_prompt);

    el_set(el, EL_EDITMODE, 1);
    el_set(el, EL_EDITOR, "emacs");
    el_hist = history_init();
    if (!el || !el_hist)
        return -1;

    /* setup history with 100 entries */
    history(el_hist, &ev, H_SETSIZE, 100);
    el_set(el, EL_HIST, history, el_hist);

    el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);

    /* Bind <tab> to command completion */
    el_set(el, EL_BIND, "^I", "ed-complete", NULL);
    #if 0   // Ticket #8152 - This corrupts show_rc passwords containing question marks
    /* Bind ? to command completion */
    el_set(el, EL_BIND, "?", "ed-complete", NULL);
    #endif
    /* Bind ^D to redisplay */
    el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);

    return 0;
}
예제 #3
0
void
noit_console_closure_free(void *vncct) {
  noit_console_closure_t ncct = (noit_console_closure_t) vncct;
  noit_log_stream_t lf;
  noitL(noit_debug, "ncct free(%p)\n", (void *)ncct);
  if(ncct->el) el_end(ncct->el);
  if(ncct->hist) {
    history_end(ncct->hist);
    noitL(noit_debug, "ncct free->hist(%p)\n", (void *)ncct->hist);
    free(ncct->hist);
  }
  if(ncct->pty_master >= 0) close(ncct->pty_master);
  if(ncct->pty_slave >= 0) close(ncct->pty_slave);
  if(ncct->outbuf) free(ncct->outbuf);
  if(ncct->telnet) noit_console_telnet_free(ncct->telnet);
  noit_hash_destroy(&ncct->userdata, NULL, noit_console_userdata_free);
  while(ncct->state_stack) {
    noit_console_state_stack_t *tmp;
    tmp = ncct->state_stack;
    ncct->state_stack = tmp->last;
    if(tmp->name) free(tmp->name);
    free(tmp);
  }
  lf = noit_log_stream_find(ncct->feed_path);
  noit_log_stream_remove(ncct->feed_path);
  if(lf) {
    noit_log_stream_free(lf);
  }
  free(ncct);
}
예제 #4
0
static void
_cleanup_editlineobject(EditLineObject *self)
{
    /* mop up libedit */
    if (self->el)
	el_end(self->el);
    if (self->tok)
	tok_end(self->tok);
    if (self->hist)
	history_end(self->hist);

    /* tidy up the allocated bits */
    if (self->name)
	PyMem_RawFree(self->name);
    if (self->prompt)
	PyMem_RawFree(self->prompt);
    if (self->rprompt)
	PyMem_RawFree(self->rprompt);
    if (self->buffer)
	PyMem_RawFree(self->buffer);
    
    /* manage file-handles? */
    if (self->fin)
	fclose(self->fin);
    if (self->fout)
	fclose(self->fout);
    if (self->ferr)
	fclose(self->ferr);

    /* release my ownership of the I/O refs */
    Py_DECREF(self->pyin);
    Py_DECREF(self->pyout);
    Py_DECREF(self->pyerr);
}
예제 #5
0
파일: main.c 프로젝트: farsightsec/axa
void AXA_NORETURN
stop(int status)
{
	if (el_e != NULL) {
		if (el_history)
			history(el_history, &el_event, H_SAVE,
					history_savefile);
		history_end(el_history);
		el_end(el_e);
	}
	close_in_files();
	fflush(stderr);
	fflush(stdout);
	disconnect(false);
	if (nmsg_input != NULL)
		nmsg_input_close(&nmsg_input);
	if (nmsg_pres != NULL)
		nmsg_output_close(&nmsg_pres);	/* this closes stdout */
	out_close(false);

	axa_unload_fields();
	axa_unload_client_config();

	axa_io_cleanup();

	exit(status);
}
예제 #6
0
파일: IoEditLine.c 프로젝트: cdcarter/io
void IoEditLine_free(IoEditLine *self)
{
	if (IoObject_dataPointer(self))
	{
		el_end(DATA(self)->editline);
		history_end(DATA(self)->history);
	}
}
예제 #7
0
파일: readline.c 프로젝트: digarok/gsplus
void x_readline_end(void) {
	if (el) {
		el_end(el);
		el = NULL;
	}
	if (hist) {
		history_end(hist);
		hist = NULL;
	}
}
예제 #8
0
void
cmdend(void *arg)
{
	struct clitenv *env = arg;

	el_end(env->el);
	history_end(env->hist);

	free(env);
}
예제 #9
0
static void _cliDebuggerDeinit(struct Debugger* debugger) {
	struct CLIDebugger* cliDebugger = (struct CLIDebugger*) debugger;
	history_end(cliDebugger->histate);
	el_end(cliDebugger->elstate);

	if (cliDebugger->system) {
		cliDebugger->system->deinit(cliDebugger->system);
		free(cliDebugger->system);
		cliDebugger->system = 0;
	}
}
예제 #10
0
CommandPrompt::~CommandPrompt()
{
#ifdef ZORBA_HAVE_LIBEDIT_H
  history_end(theHistory);
  el_end(theEditLine);
#endif

  std::map<std::string, UntypedCommand*>::iterator lIter;
  for (lIter = theCommands.begin(); lIter != theCommands.end(); ++lIter) {
    delete lIter->second;
  }
}
예제 #11
0
파일: repl.cpp 프로젝트: rroohhh/MoNS
repl::repl(FILE * in, FILE * out, CommandHandler handler) noexcept {
    auto t = new std::thread([=]() {
        init_editline(in, out);
        const char * line;
        int          length;

        io::log::info("init done");
        while((line = el_gets(el, &length))) {
            io::log::info("got line: {}", line);
            // io::log::info("el->el_flags | NO_TTY {}", el->el_flags&0x02);
            if(length > 1) {
                history(hist, &ev, H_ENTER, line);
            }
        }

        history_end(hist);
        el_end(el);

        fclose(in);
        fclose(out);
    });
}
예제 #12
0
/*
 * ntp_readline_uninit - release resources
 */
void
ntp_readline_uninit(
	void
	)
{
#ifdef LE_EDITLINE
	if (ntp_el) {
		el_end(ntp_el);
		ntp_el = NULL;

		history_end(ntp_hist);
		ntp_hist = NULL;
	}
#endif	/* LE_EDITLINE */

	if (lineedit_prompt) {
		free(lineedit_prompt);
		lineedit_prompt = NULL;
	}

	ntp_readline_initted = 0;
}
예제 #13
0
void
CliContext::Cleanup()
{
	Terminating();

	while (Event* event = fPendingEvents.RemoveHead())
		delete event;

	if (fEditLine != NULL) {
		el_end(fEditLine);
		fEditLine = NULL;
	}

	if (fHistory != NULL) {
		history_end(fHistory);
		fHistory = NULL;
	}

	if (fTeam != NULL) {
		fTeam->RemoveListener(this);
		fTeam = NULL;
	}

	if (fNodeManager != NULL) {
		fNodeManager->ReleaseReference();
		fNodeManager = NULL;
	}

	if (fCurrentBlock != NULL) {
		fCurrentBlock->ReleaseReference();
		fCurrentBlock = NULL;
	}

	if (fExpressionInfo != NULL) {
		fExpressionInfo->ReleaseReference();
		fExpressionInfo = NULL;
	}
}
예제 #14
0
grpc::Status DatasetService::GetDataset(
    const DatasetService::_RepeatedQualifiedName& physical_name,
    const DatasetService::_RepeatedString& description_tags,
    const DatasetService::_RepeatedString& history_tags,
    DatasetService::_RepeatedDataset* dataset,
    DatasetService::_RepeatedMultiDescription* description,
    DatasetService::_RepeatedMultiDescriptionHistory* description_history) {
  int num_requests = physical_name.size();
  if (num_requests == 0) {
    return grpc::Status::OK;
  }

  proto::ConstProtoIterator<std::string> description_begin(
      description_tags.begin());
  proto::ConstProtoIterator<std::string> description_end(
      description_tags.end());
  proto::ConstProtoIterator<std::string> history_begin(
      history_tags.begin());
  proto::ConstProtoIterator<std::string> history_end(
      history_tags.end());
  model::Dataset* current_dataset = nullptr;
  model::MultiDescription* current_description = nullptr;
  model::MultiDescriptionHistory* current_history = nullptr;

  grpc::Status check;
  for (int i = 0; i < num_requests && check.ok(); i++) {
    current_dataset = dataset->Add();
    current_description = description->Add();
    current_history = description_history->Add();
    check = repository_->GetDatasetAndDescription(
        physical_name.Get(i), description_begin, description_end, history_begin,
        history_end, current_dataset, current_description, current_history);
  }

  return check;
}
예제 #15
0
/*
 * Set history and editing status.  Called whenever the status may
 * have changed (figures out what to do).
 */
void
histedit() 
{

#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_out == NULL)
				el_out = fdopen(2, "w");
			if (el_in == NULL || el_out == NULL)
				goto bad;
			el = el_init(arg0, el_in, el_out);
			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");
		}
	} else {
		INTOFF;
		if (el) {	/* no editing if not interactive */
			el_end(el);
			el = NULL;
		}
		if (hist) {
			history_end(hist);
			hist = NULL;
		}
		INTON;
	}
}
예제 #16
0
파일: ui.c 프로젝트: idl3r/rappel
void interact(
		const char *const argv_0)
{
	EditLine *const el = el_init(argv_0, stdin, stdout, stderr);
	el_set(el, EL_PROMPT, &prompt);
	el_set(el, EL_EDITOR, "emacs");

	History *const hist = history_init();
	if (!hist) {
		fprintf(stderr, "Could not initalize history\n");
		exit(EXIT_FAILURE);
	}

	HistEvent ev;
	history(hist, &ev, H_SETSIZE, 100);

	el_set(el, EL_HIST, history, hist);

	const pid_t child_pid = _gen_child();

	verbose_printf("child process is %d\n", child_pid);

	if (options.verbose) help();

	char buf[PAGE_SIZE];
	size_t buf_sz = 0;
	int end = 0;

	struct proc_info_t info = {};
	ARCH_INIT_PROC_INFO(info);

	ptrace_launch(child_pid);
	ptrace_cont(child_pid, &info);
	ptrace_reap(child_pid, &info);

	display(&info);

	for (;;) {
		int count;
		const char *const line = el_gets(el, &count);

		if (count == -1) {
			perror("el_gets");
			exit(EXIT_FAILURE);
		}

		// count is 0 == ^d
		if (!count || strcasestr(line, ".quit") || strcasestr(line, ".exit")) break;

		// We have input, add it to the our history
		history(hist, &ev, H_ENTER, line);

		// If we start with a ., we have a command
		if (line[0] == '.') {
			if (strcasestr(line, "help")) {
				help();
				continue;
			}

			if (strcasestr(line, "info")) {
				display(&info);
				continue;
			}

			if (strcasestr(line, "showmap")) {
				char cmd[PATH_MAX] = { 0 };
				snprintf(cmd, sizeof(cmd), "cat /proc/%d/maps", child_pid);

				if (system(cmd))
					fprintf(stderr, "sh: %s failed\n", cmd);

				continue;
			}


			if (strcasestr(line, "read")) {
				ui_read(child_pid, line);
				continue;
			}

			if (strcasestr(line, "write")) {
				continue;
			}

			if (strcasestr(line, "begin")) {
				in_block = 1;
				continue;
			}

			// Note the lack of continue. Need to fall through...
			if (strcasestr(line, "end")) {
				in_block = 0;
				end = 1;
			}
		}

		if (buf_sz + count > sizeof(buf)) {
			printf("Buffer full (max: 0x%lx), please use '.end'\n", sizeof(buf));
			continue;
		}

		// Since we fell through, we want to avoid adding adding .end to our buffer
		if (!end) {
			memcpy(buf + buf_sz, line, count);
			buf_sz += count;
		}

		if (!in_block) {
			verbose_printf("Trying to assemble(%zu):\n%s", buf_sz, buf);

			uint8_t bytecode[PAGE_SIZE];
			const size_t bytecode_sz = assemble(bytecode, sizeof(bytecode), buf, buf_sz);

			memset(buf, 0, sizeof(buf));
			buf_sz = 0;
			end    = 0;

			verbose_printf("Got asm(%zu):\n", bytecode_sz);
			verbose_dump(bytecode, bytecode_sz, -1);

			if (!bytecode_sz) {
				fprintf(stderr, "'%s' assembled to 0 length bytecode\n", buf);
				continue;
			}

			ptrace_write(child_pid, (void *)options.start, bytecode, bytecode_sz);
			ptrace_reset(child_pid, options.start);

			ptrace_cont(child_pid, &info);
			ptrace_reap(child_pid, &info);

			display(&info);
		}
	}

	ptrace_detatch(child_pid, &info);

	printf("\n");

	history_end(hist);
	el_end(el);
}
예제 #17
0
EditLineReader::~EditLineReader()
{
	el_end(_editLine);
	history_end(_history);
}
예제 #18
0
파일: pppctl.c 프로젝트: hmatyschok/MeshBSD
/*
 * 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;
}
예제 #19
0
void deinitialize_libedit(void)
{
	el_end(el);
	history_end(hist);
}
예제 #20
0
static void *editline_threadproc(void *arg)
{
    HistEvent ev;
    EditLine *el; /* This holds all the state for our line editor */
    History *myhistory; /* This holds the info for our history */
    voglperf_data_t *data = (voglperf_data_t *)arg;

    /* Initialize the EditLine state to use our prompt function and
       emacs style editing. */
    el = el_init("voglperfun", stdin, stdout, stderr);
    el_set(el, EL_PROMPT, &prompt);
    el_set(el, EL_EDITOR, "vi");

    /* Initialize the history */
    myhistory = history_init();
    if (myhistory == 0)
    {
        fprintf(stderr, "history could not be initialized\n");
        return (void *)-1;
    }

    /* Set the size of the history */
    history(myhistory, &ev, H_SETSIZE, 800);

    /* This sets up the call back functions for history functionality */
    el_set(el, EL_HIST, history, myhistory);

    pthread_cleanup_push(cleanup_handler, el);

    while (!(data->flags & F_QUIT))
    {
        /* count is the number of characters read.
           line is a const char* of our command line with the tailing \n */
        int count;
        const char *line = el_gets(el, &count);

        /* In order to use our history we have to explicitly add commands
           to the history */
        if (count > 0)
        {
            size_t line_len = strlen(line);

            while ((line_len > 0) && isspace(line[line_len - 1]))
                line_len--;

            if (line_len)
            {
                std::string command(line, line_len);

                pthread_mutex_lock(&data->lock);
                data->thread_commands.push_back(command);
                pthread_mutex_unlock(&data->lock);

                history(myhistory, &ev, H_ENTER, line);
            }
        }
    }

    pthread_cleanup_pop(0);

    /* Clean up our memory */
    history_end(myhistory);
    el_end(el);
    return NULL;
}
예제 #21
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;
}
예제 #22
0
파일: fsdb.c 프로젝트: sofuture/bitrig
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;
}
예제 #23
0
파일: shell.c 프로젝트: jsachs/uchidb
int main(int argc, char *argv[]) 
{
  EditLine *el;
  History *hist;
  chidb *db;
  int rc;

  HistEvent ev;

  if (argc != 2)
  {
    fprintf(stderr, "ERROR: Must specify a database file.\n");
    return 1;
  }

  rc = chidb_open(argv[1], &db); 
  
  if (rc != CHIDB_OK)
  {
    fprintf(stderr, "ERROR: Could not open file %s or file is not well formed.\n", argv[1]);
    return 1;
  }

  /* Initialize EditLine */    
  el = el_init(argv[0], stdin, stdout, stderr);
  el_set(el, EL_PROMPT, &prompt);
  el_set(el, EL_EDITOR, "emacs");

  /* Initialize the history */
    hist = history_init();
    if (hist == 0) 
    {
      fprintf(stderr, "ERROR: Could not initialize history.\n");
      return 1;
  }
  history(hist, &ev, H_SETSIZE, 100); // 100 elements in history
  el_set(el, EL_HIST, history, hist); // history callback

  while (1) 
  {
    int count;
    const char *sql;
    chidb_stmt *stmt;
    
      sql = el_gets(el, &count);

      if (count == 1)
        break;
      else
      {
        history(hist, &ev, H_ENTER, sql); // Add to history
        
      rc = chidb_prepare(db, sql, &stmt);
      
        if (rc == CHIDB_OK)
        {
          int numcol = chidb_column_count(stmt);
          for(int i = 0; i < numcol; i ++)
          {
            printf(i==0?"":COL_SEPARATOR);
            printf("%s", chidb_column_name(stmt,i));            
          }
          printf("\n");
          
          while((rc = chidb_step(stmt)) == CHIDB_ROW)
          {
            for(int i = 0; i < numcol; i++)
            {
              printf(i==0?"":COL_SEPARATOR);
              switch(chidb_column_type(stmt,i))
              {
                case SQL_NULL:
                  break;
                case SQL_INTEGER_1BYTE: case SQL_INTEGER_2BYTE:  case SQL_INTEGER_4BYTE:
                  printf("%i", chidb_column_int(stmt,i));
                  break;
                case SQL_TEXT:
                  printf("%s", chidb_column_text(stmt,i));
                  break;
              }
            }
            printf("\n");
          }
          
          switch(rc)
          {
            case CHIDB_ECONSTRAINT:
              printf("ERROR: SQL statement failed because of a constraint violation.\n");
              break;
            case CHIDB_EMISMATCH:
              printf("ERROR: Data type mismatch.\n");
              break;
            case CHIDB_EMISUSE:
              printf("ERROR: API used incorrectly.\n");
              break;
            case CHIDB_EIO:
              printf("ERROR: An I/O error has occurred when accessing the file.\n");
              break;
          }

        rc = chidb_finalize(stmt);
        if(rc == CHIDB_EMISUSE)
          printf("API used incorrectly.\n");
        }
      else if (rc == CHIDB_EINVALIDSQL)
        printf("SQL syntax error.\n");
      else if (rc == CHIDB_ENOMEM)
        printf("ERROR: Could not allocate memory.\n");
    }
  }
  

  history_end(hist);
  el_end(el);

  return 0;
}
예제 #24
0
파일: honeydctl.c 프로젝트: moon2l/Honeyd
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;
}
예제 #25
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;
	}
}
예제 #26
0
파일: test.c 프로젝트: Djcd/asterisk-opus
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
/*
 * 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;
	}
}
예제 #28
0
파일: cli.c 프로젝트: crxyz/osv
int main (int argc, char* argv[]) {
#ifdef OSV_CLI
  putenv("TERM=vt100-qemu");

  cli_console_size_dirty();
#else
  struct winsize sz;
  ioctl(0, TIOCGWINSZ, &sz);

  if (sz.ws_col > 0 && sz.ws_row > 0) {
    con_width = sz.ws_col;
    con_height = sz.ws_row;

    signal(SIGWINCH, cli_sigwinch_handler);
  }
#endif

  /* Context */
  env_osv_api = getenv("OSV_API");

  /* Process command line options */
  int opt = 0;
  static struct option long_options[] = {
    {"api", optional_argument, 0, 'a'}
  };

  int long_index = 0;
  while ((opt = getopt_long(argc, argv, "a:",
    long_options, &long_index)) != -1) {
    switch (opt) {
      case 'a': env_osv_api = optarg;
      break;
    }
  }

  /* Lua state */
  L = cli_luaL_newstate();

  if (optind < argc) {
    /* If we have more arguments, the user is running a single command */
    if (L != NULL) {
      lua_getglobal(L, "cli_command_single");
      lua_createtable(L, argc, 0);

      for (int i=1; i<argc; i++) {
        lua_pushinteger(L, i);
        lua_pushstring(L, argv[i]);
        lua_settable(L, -3);
      }

      lua_pushinteger(L, optind - 1);
      int error = lua_pcall(L, 2, 0, 0);
      if (error) {
        fprintf(stderr, "%s\n", lua_tostring(L, -1));
        lua_pop(L, 1);
      }
    }
  } else {
    /* Start a shell */

    /* This holds all the state for our line editor */
    EditLine *el;

    /* This holds the info for our history */
    History *cli_history;

    /* Temp variables */
    int keepreading = 1;
    HistEvent ev;

    /* editline */
    int el_count = 0;
    char *el_line;

    /* Initialize the EditLine state to use our prompt function and
    emacs style editing. */
    el = el_init(argv[0], stdin, stdout, stderr);
    el_set(el, EL_PROMPT, &cli_prompt);
    el_set(el, EL_SIGNAL, 1);
    el_set(el, EL_EDITOR, "emacs");

    /* Initialize the history */
    cli_history = history_init();
    if (cli_history == 0) {
      fprintf(stderr, "history could not be initialized\n");
    }

    /* Set the size of the history */
    history(cli_history, &ev, H_SETSIZE, 800);

    /* This sets up the call back functions for history functionality */
    el_set(el, EL_HIST, history, cli_history);

    while (keepreading) {
      /* el_count is the number of characters read.
         line is a const char* of our command line with the tailing \n */
      el_line = (char *) el_gets(el, &el_count);

      /* If lua failed to load previously, retry */
      if (L == NULL) {
        cli_luaL_renewstate(&L);
      }

      /* with zero input (^D), reset the lua state */
      if (L != NULL && el_count == 0) {
        cli_luaL_renewstate(&L);
      } else if (L != NULL && el_count > 0) {
        /* Remove tailing \n */
        el_line[strlen(el_line)-1] = '\0';

        /* Add commands to history. Don't add empty lines */
        if (strlen(el_line) > 0) {
          history(cli_history, &ev, H_ENTER, el_line);
        }

        /* Typing reset is a special case which, like ^D,
           will reset the lua state */
        if (strcmp(el_line, "reset") == 0) {
          cli_luaL_renewstate(&L);
        } else {
          /* Pass the line, as is, to cli() */
          lua_getglobal(L, "cli_command");
          lua_pushstring(L, el_line);

          int error = lua_pcall(L, 1, 0, 0);
          if (error) {
            fprintf(stderr, "%s\n", lua_tostring(L, -1));
            lua_pop(L, 1);
          }
        }
      }
    }

    history_end(cli_history);
    el_end(el);
  }

  if (L != NULL) {
    lua_close(L);
  }

  return 0;
}
예제 #29
0
파일: tc1.c 프로젝트: cyrilmagsuci/freebsd
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);
}
예제 #30
0
파일: fs_cli.c 프로젝트: jart/freeswitch
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;
}