1 /*
2  * Minimal command line editing
3  * Copyright (c) 2010, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "includes.h"
10 
11 #include "common.h"
12 #include "eloop.h"
13 #include "edit.h"
14 
15 
16 #ifdef __ZEPHYR__
17 #define STDIN_FILENO 1
18 #endif
19 #define CMD_BUF_LEN 4096
20 static char cmdbuf[CMD_BUF_LEN];
21 static int cmdbuf_pos = 0;
22 static const char *ps2 = NULL;
23 
24 static void *edit_cb_ctx;
25 static void (*edit_cmd_cb)(void *ctx, char *cmd);
26 static void (*edit_eof_cb)(void *ctx);
27 
28 
edit_read_char(int sock,void * eloop_ctx,void * sock_ctx)29 static void edit_read_char(int sock, void *eloop_ctx, void *sock_ctx)
30 {
31 	int c;
32 	unsigned char buf[1];
33 	int res;
34 
35 	res = read(sock, buf, 1);
36 	if (res < 0)
37 		perror("read");
38 	if (res <= 0) {
39 		edit_eof_cb(edit_cb_ctx);
40 		return;
41 	}
42 	c = buf[0];
43 
44 	if (c == '\r' || c == '\n') {
45 		cmdbuf[cmdbuf_pos] = '\0';
46 		cmdbuf_pos = 0;
47 		edit_cmd_cb(edit_cb_ctx, cmdbuf);
48 		printf("%s> ", ps2 ? ps2 : "");
49 		fflush(stdout);
50 		return;
51 	}
52 
53 	if (c == '\b') {
54 		if (cmdbuf_pos > 0)
55 			cmdbuf_pos--;
56 		return;
57 	}
58 
59 	if (c >= 32 && c <= 255) {
60 		if (cmdbuf_pos < (int) sizeof(cmdbuf) - 1) {
61 			cmdbuf[cmdbuf_pos++] = c;
62 		}
63 	}
64 }
65 
66 
edit_init(void (* cmd_cb)(void * ctx,char * cmd),void (* eof_cb)(void * ctx),char ** (* completion_cb)(void * ctx,const char * cmd,int pos),void * ctx,const char * history_file,const char * ps)67 int edit_init(void (*cmd_cb)(void *ctx, char *cmd),
68 	      void (*eof_cb)(void *ctx),
69 	      char ** (*completion_cb)(void *ctx, const char *cmd, int pos),
70 	      void *ctx, const char *history_file, const char *ps)
71 {
72 	edit_cb_ctx = ctx;
73 	edit_cmd_cb = cmd_cb;
74 	edit_eof_cb = eof_cb;
75 	eloop_register_read_sock(STDIN_FILENO, edit_read_char, NULL, NULL);
76 	ps2 = ps;
77 
78 	printf("%s> ", ps2 ? ps2 : "");
79 	fflush(stdout);
80 
81 	return 0;
82 }
83 
84 
edit_deinit(const char * history_file,int (* filter_cb)(void * ctx,const char * cmd))85 void edit_deinit(const char *history_file,
86 		 int (*filter_cb)(void *ctx, const char *cmd))
87 {
88 	eloop_unregister_read_sock(STDIN_FILENO);
89 }
90 
91 
edit_clear_line(void)92 void edit_clear_line(void)
93 {
94 }
95 
96 
edit_redraw(void)97 void edit_redraw(void)
98 {
99 	cmdbuf[cmdbuf_pos] = '\0';
100 	printf("\r> %s", cmdbuf);
101 }
102