code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
#ifndef _konf_net_h
#define _konf_net_h
#include <konf/buf.h>
typedef struct konf_client_s konf_client_t;
#define KONFD_SOCKET_PATH "/tmp/konfd.socket"
konf_client_t *konf_client_new(const char *path);
void konf_client_free(konf_client_t *instance);
int konf_client_connect(konf_client_t *instance);
void konf_client_disconnect(konf_client_t *instance);
int konf_client_reconnect(konf_client_t *instance);
int konf_client_send(konf_client_t *instance, char *command);
int konf_client__get_sock(konf_client_t *instance);
konf_buf_t * konf_client_recv_data(konf_client_t * instance, konf_buf_t *buf);
int konf_client_recv_answer(konf_client_t * instance, konf_buf_t **data);
#endif
|
zzysjtu-klish
|
konf/net.h
|
C
|
bsd
| 685
|
/*
* conf_dump.c
*/
#include "private.h"
#include "lub/dump.h"
/*--------------------------------------------------------- */
/*void clish_conf_dump(clish_conf_t * this)
{
clish_command_t *c;
lub_bintree_iterator_t iter;
unsigned i;
lub_dump_printf("view(%p)\n", this);
lub_dump_indent();
c = lub_bintree_findfirst(&this->tree);
lub_dump_printf("name : %s\n", clish_view__get_name(this));
lub_dump_printf("depth : %u\n", clish_view__get_depth(this));
*/
/* Get each namespace to dump their details */
/* for (i = 0; i < this->nspacec; i++) {
clish_nspace_dump(clish_view__get_nspace(this, i));
}
*/
/* iterate the tree of commands */
/* for (lub_bintree_iterator_init(&iter, &this->tree, c);
c; c = lub_bintree_iterator_next(&iter)) {
clish_command_dump(c);
}
lub_dump_undent();
} */
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
konf/tree/tree_dump.c
|
C
|
bsd
| 880
|
/*
* tree.c
*
* This file provides the implementation of a konf_tree class
*/
#include "private.h"
#include "lub/argv.h"
#include "lub/string.h"
#include "lub/ctype.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <regex.h>
/*---------------------------------------------------------
* PRIVATE META FUNCTIONS
*--------------------------------------------------------- */
static int konf_tree_compare(const void *first, const void *second)
{
const konf_tree_t *f = (const konf_tree_t *)first;
const konf_tree_t *s = (const konf_tree_t *)second;
/* Priority check */
if (f->priority != s->priority)
return (f->priority - s->priority);
/* Sequence check */
if (f->seq_num != s->seq_num)
return (f->seq_num - s->seq_num);
/* Sub-sequence check */
if (f->sub_num != s->sub_num)
return (f->sub_num - s->sub_num);
/* Line check */
return strcmp(f->line, s->line);
}
/*---------------------------------------------------------
* PRIVATE METHODS
*--------------------------------------------------------- */
static void konf_tree_init(konf_tree_t * this, const char *line,
unsigned short priority)
{
/* set up defaults */
this->line = strdup(line);
this->priority = priority;
this->seq_num = 0;
this->sub_num = KONF_ENTRY_OK;
this->splitter = BOOL_TRUE;
this->depth = -1;
/* initialise the list of commands for this conf */
this->list = lub_list_new(konf_tree_compare);
}
/*--------------------------------------------------------- */
static void konf_tree_fini(konf_tree_t * this)
{
lub_list_node_t *iter;
/* delete each conf held by this conf */
while ((iter = lub_list__get_head(this->list))) {
/* remove the conf from the tree */
lub_list_del(this->list, iter);
/* release the instance */
konf_tree_delete((konf_tree_t *)lub_list_node__get_data(iter));
lub_list_node_free(iter);
}
lub_list_free(this->list);
/* free our memory */
free(this->line);
this->line = NULL;
}
/*---------------------------------------------------------
* PUBLIC META FUNCTIONS
*--------------------------------------------------------- */
/*--------------------------------------------------------- */
konf_tree_t *konf_tree_new(const char *line, unsigned short priority)
{
konf_tree_t *this = malloc(sizeof(konf_tree_t));
if (this)
konf_tree_init(this, line, priority);
return this;
}
/*---------------------------------------------------------
* PUBLIC METHODS
*--------------------------------------------------------- */
void konf_tree_delete(konf_tree_t * this)
{
konf_tree_fini(this);
free(this);
}
/*--------------------------------------------------------- */
void konf_tree_fprintf(konf_tree_t *this, FILE *stream,
const char *pattern, int top_depth, int depth,
bool_t seq, unsigned char prev_pri_hi)
{
konf_tree_t *conf;
lub_list_node_t *iter;
unsigned char pri = 0;
regex_t regexp;
if (this->line && (*(this->line) != '\0') &&
(this->depth > top_depth) &&
((depth < 0 ) || (this->depth <= (top_depth + depth)))) {
char *space = NULL;
unsigned space_num = this->depth - top_depth - 1;
if (space_num > 0) {
space = malloc(space_num + 1);
memset(space, ' ', space_num);
space[space_num] = '\0';
}
if ((0 == this->depth) &&
(this->splitter ||
(konf_tree__get_priority_hi(this) != prev_pri_hi)))
fprintf(stream, "!\n");
fprintf(stream, "%s", space ? space : "");
if (seq && (konf_tree__get_seq_num(this) != 0))
fprintf(stream, "%u ", konf_tree__get_seq_num(this));
fprintf(stream, "%s\n", this->line);
free(space);
}
/* regexp compilation */
if (pattern)
if (regcomp(®exp, pattern, REG_EXTENDED | REG_ICASE) != 0)
return;
/* iterate child elements */
for(iter = lub_list__get_head(this->list);
iter; iter = lub_list_node__get_next(iter)) {
conf = (konf_tree_t *)lub_list_node__get_data(iter);
if (pattern && (0 != regexec(®exp, conf->line, 0, NULL, 0)))
continue;
konf_tree_fprintf(conf, stream, NULL, top_depth, depth, seq, pri);
pri = konf_tree__get_priority_hi(conf);
}
if (pattern)
regfree(®exp);
}
/*-------------------------------------------------------- */
static int normalize_seq(konf_tree_t * this, unsigned short priority,
lub_list_node_t *start)
{
unsigned short cnt = 1;
konf_tree_t *conf = NULL;
lub_list_node_t *iter;
unsigned short cur_pri;
if (start) {
lub_list_node_t *prev;
iter = start;
if ((prev = lub_list_node__get_prev(iter))) {
conf = (konf_tree_t *)lub_list_node__get_data(prev);
if (konf_tree__get_priority(conf) == priority)
cnt = konf_tree__get_seq_num(conf) + 1;
}
} else {
iter = lub_list__get_head(this->list);
}
/* If list is empty */
if (!iter)
return 0;
/* Iterate and renum */
do {
conf = (konf_tree_t *)lub_list_node__get_data(iter);
cur_pri = konf_tree__get_priority(conf);
if (cur_pri > priority)
break;
if (cur_pri < priority)
continue;
if (konf_tree__get_seq_num(conf) == 0)
continue;
konf_tree__set_seq_num(conf, cnt++);
} while ((iter = lub_list_node__get_next(iter)));
return 0;
}
/*--------------------------------------------------------- */
konf_tree_t *konf_tree_new_conf(konf_tree_t * this,
const char *line, unsigned short priority,
bool_t seq, unsigned short seq_num)
{
lub_list_node_t *node;
/* Allocate the memory for a new child element */
konf_tree_t *newconf = konf_tree_new(line, priority);
assert(newconf);
/* Sequence */
if (seq) {
konf_tree__set_seq_num(newconf,
seq_num ? seq_num : 0xffff);
konf_tree__set_sub_num(newconf, KONF_ENTRY_NEW);
}
/* Insert it into the list */
node = lub_list_add(this->list, newconf);
if (seq) {
normalize_seq(this, priority, node);
konf_tree__set_sub_num(newconf, KONF_ENTRY_OK);
}
return newconf;
}
/*--------------------------------------------------------- */
konf_tree_t *konf_tree_find_conf(konf_tree_t * this,
const char *line, unsigned short priority, unsigned short seq_num)
{
konf_tree_t *conf;
lub_list_node_t *iter;
int check_pri = 0;
/* If list is empty */
if (!(iter = lub_list__get_tail(this->list)))
return NULL;
if ((0 != priority) && (0 != seq_num))
check_pri = 1;
/* Iterate non-empty tree */
do {
conf = (konf_tree_t *)lub_list_node__get_data(iter);
if (check_pri) {
if (priority < conf->priority)
continue;
if (priority > conf->priority)
break;
if (seq_num < conf->seq_num)
continue;
if (seq_num > conf->seq_num)
break;
}
if (!strcmp(conf->line, line))
return conf;
} while ((iter = lub_list_node__get_prev(iter)));
return NULL;
}
/*--------------------------------------------------------- */
int konf_tree_del_pattern(konf_tree_t *this,
const char *line, bool_t unique,
const char *pattern, unsigned short priority,
bool_t seq, unsigned short seq_num)
{
int res = 0;
konf_tree_t *conf;
lub_list_node_t *iter;
lub_list_node_t *tmp;
regex_t regexp;
int del_cnt = 0; /* how many strings were deleted */
if (seq && (0 == priority))
return -1;
/* Is tree empty? */
if (!(iter = lub_list__get_head(this->list)))
return 0;
/* Compile regular expression */
if (regcomp(®exp, pattern, REG_EXTENDED | REG_ICASE) != 0)
return -1;
/* Iterate configuration tree */
tmp = lub_list_node_new(NULL);
do {
conf = (konf_tree_t *)lub_list_node__get_data(iter);
if ((0 != priority) &&
(priority != conf->priority))
continue;
if (seq && (seq_num != 0) &&
(seq_num != conf->seq_num))
continue;
if (seq && (0 == seq_num) && (0 == conf->seq_num))
continue;
if (0 != regexec(®exp, conf->line, 0, NULL, 0))
continue;
if (unique && line && !strcmp(conf->line, line)) {
res++;
continue;
}
lub_list_del(this->list, iter);
konf_tree_delete(conf);
lub_list_node_copy(tmp, iter);
lub_list_node_free(iter);
iter = tmp;
del_cnt++;
} while ((iter = lub_list_node__get_next(iter)));
lub_list_node_free(tmp);
regfree(®exp);
if (seq && (del_cnt != 0))
normalize_seq(this, priority, NULL);
return res;
}
/*--------------------------------------------------------- */
unsigned short konf_tree__get_priority(const konf_tree_t * this)
{
return this->priority;
}
/*--------------------------------------------------------- */
unsigned char konf_tree__get_priority_hi(const konf_tree_t * this)
{
return (unsigned char)(this->priority >> 8);
}
/*--------------------------------------------------------- */
unsigned char konf_tree__get_priority_lo(const konf_tree_t * this)
{
return (unsigned char)(this->priority & 0xff);
}
/*--------------------------------------------------------- */
bool_t konf_tree__get_splitter(const konf_tree_t * this)
{
return this->splitter;
}
/*--------------------------------------------------------- */
void konf_tree__set_splitter(konf_tree_t *this, bool_t splitter)
{
this->splitter = splitter;
}
/*--------------------------------------------------------- */
unsigned short konf_tree__get_seq_num(const konf_tree_t * this)
{
return this->seq_num;
}
/*--------------------------------------------------------- */
void konf_tree__set_seq_num(konf_tree_t * this, unsigned short seq_num)
{
this->seq_num = seq_num;
}
/*--------------------------------------------------------- */
unsigned short konf_tree__get_sub_num(const konf_tree_t * this)
{
return this->sub_num;
}
/*--------------------------------------------------------- */
void konf_tree__set_sub_num(konf_tree_t * this, unsigned short sub_num)
{
this->sub_num = sub_num;
}
/*--------------------------------------------------------- */
const char * konf_tree__get_line(const konf_tree_t * this)
{
return this->line;
}
/*--------------------------------------------------------- */
void konf_tree__set_depth(konf_tree_t * this, int depth)
{
this->depth = depth;
}
/*--------------------------------------------------------- */
int konf_tree__get_depth(const konf_tree_t * this)
{
return this->depth;
}
|
zzysjtu-klish
|
konf/tree/tree.c
|
C
|
bsd
| 9,942
|
/*
* konf/tree/private.h
*/
#ifndef _konf_tree_private_h
#define _konf_tree_private_h
#include "konf/tree.h"
#include "lub/types.h"
#include "lub/list.h"
/*---------------------------------------------------------
* PRIVATE TYPES
*--------------------------------------------------------- */
struct konf_tree_s {
lub_list_t *list;
char *line;
unsigned short priority;
unsigned short seq_num;
unsigned short sub_num;
bool_t splitter;
int depth;
};
#endif
|
zzysjtu-klish
|
konf/tree/private.h
|
C
|
bsd
| 468
|
#ifndef _konf_query_h
#define _konf_query_h
#include <lub/types.h>
typedef enum
{
KONF_QUERY_OP_NONE,
KONF_QUERY_OP_OK,
KONF_QUERY_OP_ERROR,
KONF_QUERY_OP_SET,
KONF_QUERY_OP_UNSET,
KONF_QUERY_OP_STREAM,
KONF_QUERY_OP_DUMP
} konf_query_op_t;
typedef struct konf_query_s konf_query_t;
konf_query_t *konf_query_new(void);
void konf_query_free(konf_query_t *instance);
int konf_query_parse(konf_query_t *instance, int argc, char **argv);
int konf_query_parse_str(konf_query_t *instance, char *str);
void konf_query_dump(konf_query_t *instance);
char *konf_query__get_pwd(konf_query_t *instance, unsigned index);
int konf_query__get_pwdc(konf_query_t *instance);
konf_query_op_t konf_query__get_op(konf_query_t *instance);
char * konf_query__get_path(konf_query_t *instance);
const char * konf_query__get_pattern(konf_query_t *instance);
const char * konf_query__get_line(konf_query_t *instance);
unsigned short konf_query__get_priority(konf_query_t *instance);
bool_t konf_query__get_splitter(konf_query_t *instance);
bool_t konf_query__get_seq(konf_query_t *instance);
unsigned short konf_query__get_seq_num(konf_query_t *instance);
bool_t konf_query__get_unique(konf_query_t *instance);
int konf_query__get_depth(konf_query_t *instance);
#endif
|
zzysjtu-klish
|
konf/query.h
|
C
|
bsd
| 1,263
|
/*
* buf.h
*/
/**
\ingroup clish
\defgroup clish_conf config
@{
\brief This class is a config in memory container.
Use it to implement config in memory.
*/
#ifndef _konf_buf_h
#define _konf_buf_h
#include <stdio.h>
#include <lub/bintree.h>
typedef struct konf_buf_s konf_buf_t;
/*=====================================
* CONF INTERFACE
*===================================== */
/*-----------------
* meta functions
*----------------- */
konf_buf_t *konf_buf_new(int fd);
int konf_buf_bt_compare(const void *clientnode, const void *clientkey);
void konf_buf_bt_getkey(const void *clientnode, lub_bintree_key_t * key);
size_t konf_buf_bt_offset(void);
/*-----------------
* methods
*----------------- */
void konf_buf_delete(konf_buf_t *instance);
int konf_buf_read(konf_buf_t *instance);
int konf_buf_add(konf_buf_t *instance, void *str, size_t len);
char * konf_buf_string(char *instance, int len);
char * konf_buf_parse(konf_buf_t *instance);
char * konf_buf_preparse(konf_buf_t *instance);
int konf_buf_lseek(konf_buf_t *instance, int newpos);
int konf_buf__get_fd(const konf_buf_t *instance);
int konf_buf__get_len(const konf_buf_t *instance);
char * konf_buf__dup_line(const konf_buf_t *instance);
int konf_buftree_read(lub_bintree_t *instance, int fd);
char * konf_buftree_parse(lub_bintree_t *instance, int fd);
void konf_buftree_remove(lub_bintree_t *instance, int fd);
#endif /* _konf_buf_h */
/** @} clish_conf */
|
zzysjtu-klish
|
konf/buf.h
|
C
|
bsd
| 1,443
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <assert.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/un.h>
#include "konf/buf.h"
#include "konf/query.h"
#include "lub/string.h"
#include "private.h"
/* UNIX socket name in filesystem */
#ifndef UNIX_PATH_MAX
#define UNIX_PATH_MAX 108
#endif
/* OpenBSD has no MSG_NOSIGNAL flag.
* The SIGPIPE must be ignored in application.
*/
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
/*--------------------------------------------------------- */
konf_client_t *konf_client_new(const char *path)
{
konf_client_t *this;
if (!path)
return NULL;
if (!(this = malloc(sizeof(*this))))
return NULL;
this->sock = -1; /* socket is not created yet */
this->path = strdup(path);
return this;
}
/*--------------------------------------------------------- */
void konf_client_free(konf_client_t *this)
{
if (!this)
return;
if (this->sock != -1)
konf_client_disconnect(this);
free(this->path);
free(this);
}
/*--------------------------------------------------------- */
int konf_client_connect(konf_client_t *this)
{
struct sockaddr_un raddr;
if (this->sock >= 0)
return this->sock;
if ((this->sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
return this->sock;
raddr.sun_family = AF_UNIX;
strncpy(raddr.sun_path, this->path, UNIX_PATH_MAX);
raddr.sun_path[UNIX_PATH_MAX - 1] = '\0';
if (connect(this->sock, (struct sockaddr *)&raddr, sizeof(raddr))) {
close(this->sock);
this->sock = -1;
}
return this->sock;
}
/*--------------------------------------------------------- */
void konf_client_disconnect(konf_client_t *this)
{
if (this->sock >= 0) {
close(this->sock);
this->sock = -1;
}
}
/*--------------------------------------------------------- */
int konf_client_reconnect(konf_client_t *this)
{
konf_client_disconnect(this);
return konf_client_connect(this);
}
/*--------------------------------------------------------- */
int konf_client_send(konf_client_t *this, char *command)
{
if (this->sock < 0)
return this->sock;
return send(this->sock, command, strlen(command) + 1, MSG_NOSIGNAL);
}
/*--------------------------------------------------------- */
int konf_client__get_sock(konf_client_t *this)
{
return this->sock;
}
/*--------------------------------------------------------- */
konf_buf_t * konf_client_recv_data(konf_client_t * this, konf_buf_t *buf)
{
int processed = 0;
konf_buf_t *data;
char *str;
/* Check if socked is connected */
if ((konf_client_connect(this) < 0))
return NULL;
data = konf_buf_new(konf_client__get_sock(this));
do {
while ((str = konf_buf_parse(buf))) {
konf_buf_add(data, str, strlen(str) + 1);
if (strlen(str) == 0) {
processed = 1;
free(str);
break;
}
free(str);
}
} while ((!processed) && (konf_buf_read(buf)) > 0);
if (!processed) {
konf_buf_delete(data);
return NULL;
}
return data;
}
/*--------------------------------------------------------- */
static int process_answer(konf_client_t * this, char *str, konf_buf_t *buf, konf_buf_t **data)
{
int res;
konf_query_t *query;
/* Parse query */
query = konf_query_new();
res = konf_query_parse_str(query, str);
if (res < 0) {
konf_query_free(query);
#ifdef DEBUG
fprintf(stderr, "CONFIG error: Cannot parse answer string.\n");
#endif
return -1;
}
#ifdef DEBUG
fprintf(stderr, "ANSWER: %s\n", str);
/* konf_query_dump(query);
*/
#endif
switch (konf_query__get_op(query)) {
case KONF_QUERY_OP_OK:
res = 0;
break;
case KONF_QUERY_OP_ERROR:
res = -1;
break;
case KONF_QUERY_OP_STREAM:
if (!(*data = konf_client_recv_data(this, buf)))
res = -1;
else
res = 1; /* wait for another answer */
break;
default:
res = -1;
break;
}
/* Free resources */
konf_query_free(query);
return res;
}
/*--------------------------------------------------------- */
int konf_client_recv_answer(konf_client_t * this, konf_buf_t **data)
{
konf_buf_t *buf;
int nbytes;
char *str;
int retval = 0;
int processed = 0;
if ((konf_client_connect(this) < 0))
return -1;
buf = konf_buf_new(konf_client__get_sock(this));
while ((!processed) && (nbytes = konf_buf_read(buf)) > 0) {
while ((str = konf_buf_parse(buf))) {
konf_buf_t *tmpdata = NULL;
retval = process_answer(this, str, buf, &tmpdata);
free(str);
if (retval < 0) {
konf_buf_delete(buf);
return retval;
}
if (retval == 0)
processed = 1;
if (tmpdata) {
if (*data)
konf_buf_delete(*data);
*data = tmpdata;
}
}
}
konf_buf_delete(buf);
return retval;
}
|
zzysjtu-klish
|
konf/net/net.c
|
C
|
bsd
| 4,639
|
#ifndef _konf_net_private_h
#define _konf_net_private_h
#include "konf/net.h"
struct konf_client_s {
int sock;
char *path;
};
#endif
|
zzysjtu-klish
|
konf/net/private.h
|
C
|
bsd
| 138
|
#! /bin/sh
# Start conf server
/usr/bin/konfd >/dev/null 2>/dev/null &
# Initialize system with startup-config
/usr/bin/clish -x /etc/clish-enable -w configure-view /etc/startup-config
|
zzysjtu-klish
|
xml-examples/klish/etc/init.d/klish-init
|
Shell
|
bsd
| 188
|
/**
\ingroup tinyrl
\defgroup tinyrl_class tinyrl
@{
\brief This class provides instances which are capable of handling user input
from a CLI in a "readline" like fashion.
*/
#ifndef _tinyrl_tinyrl_h
#define _tinyrl_tinyrl_h
#include <stdio.h>
#include "lub/types.h"
#include "lub/c_decl.h"
#include "tinyrl/history.h"
_BEGIN_C_DECL typedef struct _tinyrl tinyrl_t;
typedef enum {
/**
* no possible completions were found
*/
TINYRL_NO_MATCH = 0,
/**
* the provided string was already an exact match
*/
TINYRL_MATCH,
/**
* the provided string was ambiguous and produced
* more than one possible completion
*/
TINYRL_AMBIGUOUS,
/**
* the provided string was unambiguous and a
* completion was performed
*/
TINYRL_COMPLETED_MATCH,
/**
* the provided string was ambiguous but a partial
* completion was performed.
*/
TINYRL_COMPLETED_AMBIGUOUS,
/**
* the provided string was an exact match for one
* possible value but there are other exetensions
* of the string available.
*/
TINYRL_MATCH_WITH_EXTENSIONS
} tinyrl_match_e;
/* virtual methods */
typedef char *tinyrl_compentry_func_t(tinyrl_t * instance,
const char *text, unsigned offset, unsigned state);
typedef int tinyrl_hook_func_t(tinyrl_t * instance);
typedef char **tinyrl_completion_func_t(tinyrl_t * instance,
const char *text, unsigned start, unsigned end);
typedef int tinyrl_timeout_fn_t(tinyrl_t *instance);
typedef int tinyrl_keypress_fn_t(tinyrl_t *instance, int key);
/**
* \return
* - BOOL_TRUE if the action associated with the key has
* been performed successfully
* - BOOL_FALSE if the action was not successful
*/
typedef bool_t tinyrl_key_func_t(tinyrl_t * instance, int key);
/* exported functions */
extern tinyrl_t *tinyrl_new(FILE * instream,
FILE * outstream,
unsigned stifle,
tinyrl_completion_func_t * complete_fn);
/*lint -esym(534,tinyrl_printf) Ignoring return value of function */
extern int tinyrl_printf(const tinyrl_t * instance, const char *fmt, ...);
extern void tinyrl_delete(tinyrl_t * instance);
extern tinyrl_history_t *tinyrl__get_history(const tinyrl_t * instance);
extern const char *tinyrl__get_prompt(const tinyrl_t * instance);
extern void tinyrl__set_prompt(tinyrl_t *instance, const char *prompt);
extern void tinyrl_done(tinyrl_t * instance);
extern void tinyrl_completion_over(tinyrl_t * instance);
extern void tinyrl_completion_error_over(tinyrl_t * instance);
extern bool_t tinyrl_is_completion_error_over(const tinyrl_t * instance);
extern void *tinyrl__get_context(const tinyrl_t * instance);
/**
* This operation returns the current line in use by the tinyrl instance
* NB. the pointer will become invalid after any further operation on the
* instance.
*/
extern const char *tinyrl__get_line(const tinyrl_t * instance);
extern void tinyrl__set_istream(tinyrl_t * instance, FILE * istream);
extern bool_t tinyrl__get_isatty(const tinyrl_t * instance);
extern FILE *tinyrl__get_istream(const tinyrl_t * instance);
extern FILE *tinyrl__get_ostream(const tinyrl_t * instance);
extern bool_t tinyrl__get_utf8(const tinyrl_t * instance);
extern void tinyrl__set_utf8(tinyrl_t * instance, bool_t utf8);
extern void tinyrl__set_timeout(tinyrl_t *instance, int timeout);
extern void tinyrl__set_timeout_fn(tinyrl_t *instance,
tinyrl_timeout_fn_t *fn);
extern void tinyrl__set_keypress_fn(tinyrl_t *instance,
tinyrl_keypress_fn_t *fn);
extern char *tinyrl_readline(tinyrl_t *instance, void *context);
extern char *tinyrl_forceline(tinyrl_t *instance,
void *context, const char *line);
extern bool_t tinyrl_bind_key(tinyrl_t *instance, int key,
tinyrl_key_func_t *fn);
extern void tinyrl_delete_matches(char **instance);
extern char **tinyrl_completion(tinyrl_t *instance,
const char *line, unsigned start, unsigned end,
tinyrl_compentry_func_t *generator);
extern void tinyrl_crlf(const tinyrl_t * instance);
extern void tinyrl_multi_crlf(const tinyrl_t * instance);
extern void tinyrl_ding(const tinyrl_t * instance);
extern void tinyrl_reset_line_state(tinyrl_t * instance);
extern bool_t tinyrl_insert_text(tinyrl_t * instance, const char *text);
extern void
tinyrl_delete_text(tinyrl_t * instance, unsigned start, unsigned end);
extern void tinyrl_redisplay(tinyrl_t * instance);
extern void
tinyrl_replace_line(tinyrl_t * instance, const char *text, int clear_undo);
/**
* Complete the current word in the input buffer, displaying
* a prompt to clarify any abiguity if necessary.
*
* \return
* - the type of match performed.
* \post
* - If the current word is ambiguous then a list of
* possible completions will be displayed.
*/
extern tinyrl_match_e tinyrl_complete(tinyrl_t * instance);
/**
* Complete the current word in the input buffer, displaying
* a prompt to clarify any abiguity or extra extensions if necessary.
*
* \return
* - the type of match performed.
* \post
* - If the current word is ambiguous then a list of
* possible completions will be displayed.
* - If the current word is complete but there are extra
* completions which are an extension of that word then
* a list of these will be displayed.
*/
extern tinyrl_match_e tinyrl_complete_with_extensions(tinyrl_t * instance);
/**
* Disable echoing of input characters when a line in input.
*
*/
extern void tinyrl_disable_echo(
/**
* The instance on which to operate
*/
tinyrl_t * instance,
/**
* The character to display instead of a key press.
*
* If this has the special value '/0' then the insertion point will not
* be moved when keys are pressed.
*/
char echo_char);
/**
* Enable key echoing for this instance. (This is the default behaviour)
*/
extern void tinyrl_enable_echo(
/**
* The instance on which to operate
*/
tinyrl_t * instance);
/**
* Indicate whether the current insertion point is quoting or not
*/
extern bool_t tinyrl_is_quoting(
/**
* The instance on which to operate
*/
const tinyrl_t * instance);
/**
* Indicate whether the current insertion is empty or not
*/
extern bool_t
tinyrl_is_empty(
/**
* The instance on which to operate
*/
const tinyrl_t *instance
);
/**
* Limit maximum line length
*/
extern void tinyrl_limit_line_length(
/**
* The instance on which to operate
*/
tinyrl_t * instance,
/**
* The length to limit to (0) is unlimited
*/
unsigned length);
extern unsigned tinyrl__get_width(const tinyrl_t *instance);
extern unsigned tinyrl__get_height(const tinyrl_t *instance);
extern int tinyrl__save_history(const tinyrl_t *instance, const char *fname);
extern int tinyrl__restore_history(tinyrl_t *instance, const char *fname);
extern void tinyrl__stifle_history(tinyrl_t *instance, unsigned int stifle);
_END_C_DECL
#endif /* _tinyrl_tinyrl_h */
/** @} tinyrl_tinyrl */
|
zzysjtu-klish
|
tinyrl/tinyrl.h
|
C
|
bsd
| 7,043
|
/*
* tinyrl.c
*/
/* make sure we can get fileno() */
#undef __STRICT_ANSI__
/* LIBC HEADERS */
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
/* POSIX HEADERS */
#include <unistd.h>
#include "lub/string.h"
#include "private.h"
/*-------------------------------------------------------- */
static void utf8_point_left(tinyrl_t * this)
{
if (!this->utf8)
return;
while (this->point &&
(UTF8_10 == (this->line[this->point] & UTF8_MASK)))
this->point--;
}
/*-------------------------------------------------------- */
static void utf8_point_right(tinyrl_t * this)
{
if (!this->utf8)
return;
while ((this->point < this->end) &&
(UTF8_10 == (this->line[this->point] & UTF8_MASK)))
this->point++;
}
/*-------------------------------------------------------- */
static unsigned utf8_nsyms(const tinyrl_t * this, const char *str, unsigned num)
{
unsigned nsym = 0;
unsigned i;
if (!this->utf8)
return num;
for (i = 0; i < num; i++) {
if ('\0' == str[i])
break;
if (UTF8_10 == (str[i] & UTF8_MASK))
continue;
nsym++;
}
return nsym;
}
/*----------------------------------------------------------------------- */
static void tty_set_raw_mode(tinyrl_t * this)
{
struct termios new_termios;
int fd;
int status;
if (!tinyrl_vt100__get_istream(this->term))
return;
fd = fileno(tinyrl_vt100__get_istream(this->term));
status = tcgetattr(fd, &this->default_termios);
if (-1 != status) {
status = tcgetattr(fd, &new_termios);
assert(-1 != status);
new_termios.c_iflag = 0;
new_termios.c_oflag = OPOST | ONLCR;
new_termios.c_lflag = 0;
new_termios.c_cc[VMIN] = 1;
new_termios.c_cc[VTIME] = 0;
/* Do the mode switch */
status = tcsetattr(fd, TCSADRAIN, &new_termios);
assert(-1 != status);
}
}
/*----------------------------------------------------------------------- */
static void tty_restore_mode(const tinyrl_t * this)
{
int fd;
if (!tinyrl_vt100__get_istream(this->term))
return;
fd = fileno(tinyrl_vt100__get_istream(this->term));
/* Do the mode switch */
(void)tcsetattr(fd, TCSADRAIN, &this->default_termios);
}
/*----------------------------------------------------------------------- */
/*
This is called whenever a line is edited in any way.
It signals that if we are currently viewing a history line we should transfer it
to the current buffer
*/
static void changed_line(tinyrl_t * this)
{
/* if the current line is not our buffer then make it so */
if (this->line != this->buffer) {
/* replace the current buffer with the new details */
free(this->buffer);
this->line = this->buffer = lub_string_dup(this->line);
this->buffer_size = strlen(this->buffer);
assert(this->line);
}
}
/*----------------------------------------------------------------------- */
static int tinyrl_timeout_default(tinyrl_t *this)
{
/* Return -1 to close session on timeout */
return -1;
}
/*----------------------------------------------------------------------- */
static bool_t tinyrl_key_default(tinyrl_t * this, int key)
{
bool_t result = BOOL_FALSE;
if (key > 31) {
char tmp[2];
tmp[0] = (key & 0xFF), tmp[1] = '\0';
/* inject this text into the buffer */
result = tinyrl_insert_text(this, tmp);
} else {
char tmp[10];
sprintf(tmp, "~%d", key);
/* inject control characters as ~N where N is the ASCII code */
result = tinyrl_insert_text(this, tmp);
}
return result;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_interrupt(tinyrl_t * this, int key)
{
tinyrl_crlf(this);
tinyrl_delete_text(this, 0, this->end);
this->done = BOOL_TRUE;
/* keep the compiler happy */
key = key;
return BOOL_TRUE;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_start_of_line(tinyrl_t * this, int key)
{
/* set the insertion point to the start of the line */
this->point = 0;
/* keep the compiler happy */
key = key;
return BOOL_TRUE;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_end_of_line(tinyrl_t * this, int key)
{
/* set the insertion point to the end of the line */
this->point = this->end;
/* keep the compiler happy */
key = key;
return BOOL_TRUE;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_kill(tinyrl_t * this, int key)
{
/* release any old kill string */
lub_string_free(this->kill_string);
/* store the killed string */
this->kill_string = lub_string_dup(&this->buffer[this->point]);
/* delete the text to the end of the line */
tinyrl_delete_text(this, this->point, this->end);
/* keep the compiler happy */
key = key;
return BOOL_TRUE;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_yank(tinyrl_t * this, int key)
{
bool_t result = BOOL_FALSE;
if (this->kill_string) {
/* insert the kill string at the current insertion point */
result = tinyrl_insert_text(this, this->kill_string);
}
/* keep the compiler happy */
key = key;
return result;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_crlf(tinyrl_t * this, int key)
{
tinyrl_crlf(this);
this->done = BOOL_TRUE;
/* keep the compiler happy */
key = key;
return BOOL_TRUE;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_up(tinyrl_t * this, int key)
{
bool_t result = BOOL_FALSE;
tinyrl_history_entry_t *entry = NULL;
if (this->line == this->buffer) {
/* go to the last history entry */
entry = tinyrl_history_getlast(this->history, &this->hist_iter);
} else {
/* already traversing the history list so get previous */
entry = tinyrl_history_getprevious(&this->hist_iter);
}
if (entry) {
/* display the entry moving the insertion point
* to the end of the line
*/
this->line = tinyrl_history_entry__get_line(entry);
this->point = this->end = strlen(this->line);
result = BOOL_TRUE;
}
/* keep the compiler happy */
key = key;
return result;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_down(tinyrl_t * this, int key)
{
bool_t result = BOOL_FALSE;
if (this->line != this->buffer) {
/* we are not already at the bottom */
/* the iterator will have been set up by the key_up() function */
tinyrl_history_entry_t *entry =
tinyrl_history_getnext(&this->hist_iter);
if (!entry) {
/* nothing more in the history list */
this->line = this->buffer;
} else {
this->line = tinyrl_history_entry__get_line(entry);
}
/* display the entry moving the insertion point
* to the end of the line
*/
this->point = this->end = strlen(this->line);
result = BOOL_TRUE;
}
/* keep the compiler happy */
key = key;
return result;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_left(tinyrl_t * this, int key)
{
bool_t result = BOOL_FALSE;
if (this->point > 0) {
this->point--;
utf8_point_left(this);
result = BOOL_TRUE;
}
/* keep the compiler happy */
key = key;
return result;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_right(tinyrl_t * this, int key)
{
bool_t result = BOOL_FALSE;
if (this->point < this->end) {
this->point++;
utf8_point_right(this);
result = BOOL_TRUE;
}
/* keep the compiler happy */
key = key;
return result;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_backspace(tinyrl_t *this, int key)
{
bool_t result = BOOL_FALSE;
if (this->point) {
unsigned end = --this->point;
utf8_point_left(this);
tinyrl_delete_text(this, this->point, end);
result = BOOL_TRUE;
}
/* keep the compiler happy */
key = key;
return result;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_backword(tinyrl_t *this, int key)
{
bool_t result = BOOL_FALSE;
/* remove current whitespace before cursor */
while (this->point > 0 && isspace(this->line[this->point - 1]))
tinyrl_key_backspace(this, KEY_BS);
/* delete word before cusor */
while (this->point > 0 && !isspace(this->line[this->point - 1]))
tinyrl_key_backspace(this, KEY_BS);
result = BOOL_TRUE;
/* keep the compiler happy */
key = key;
return result;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_delete(tinyrl_t * this, int key)
{
bool_t result = BOOL_FALSE;
if (this->point < this->end) {
unsigned begin = this->point++;
utf8_point_right(this);
tinyrl_delete_text(this, begin, this->point - 1);
result = BOOL_TRUE;
}
/* keep the compiler happy */
key = key;
return result;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_clear_screen(tinyrl_t * this, int key)
{
tinyrl_vt100_clear_screen(this->term);
tinyrl_vt100_cursor_home(this->term);
tinyrl_reset_line_state(this);
/* keep the compiler happy */
key = key;
this = this;
return BOOL_TRUE;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_erase_line(tinyrl_t * this, int key)
{
if (this->point) {
unsigned end = this->point - 1;
tinyrl_delete_text(this, 0, end);
this->point = 0;
}
/* keep the compiler happy */
key = key;
this = this;
return BOOL_TRUE;
}/*-------------------------------------------------------- */
static bool_t tinyrl_key_escape(tinyrl_t * this, int key)
{
bool_t result = BOOL_FALSE;
switch (tinyrl_vt100_escape_decode(this->term)) {
case tinyrl_vt100_CURSOR_UP:
result = tinyrl_key_up(this, key);
break;
case tinyrl_vt100_CURSOR_DOWN:
result = tinyrl_key_down(this, key);
break;
case tinyrl_vt100_CURSOR_LEFT:
result = tinyrl_key_left(this, key);
break;
case tinyrl_vt100_CURSOR_RIGHT:
result = tinyrl_key_right(this, key);
break;
case tinyrl_vt100_HOME:
result = tinyrl_key_start_of_line(this,key);
break;
case tinyrl_vt100_END:
result = tinyrl_key_end_of_line(this,key);
break;
case tinyrl_vt100_DELETE:
result = tinyrl_key_delete(this,key);
break;
case tinyrl_vt100_INSERT:
case tinyrl_vt100_PGDOWN:
case tinyrl_vt100_PGUP:
case tinyrl_vt100_UNKNOWN:
break;
}
return result;
}
/*-------------------------------------------------------- */
static bool_t tinyrl_key_tab(tinyrl_t * this, int key)
{
bool_t result = BOOL_FALSE;
tinyrl_match_e status = tinyrl_complete_with_extensions(this);
switch (status) {
case TINYRL_COMPLETED_MATCH:
case TINYRL_MATCH:
/* everything is OK with the world... */
result = tinyrl_insert_text(this, " ");
break;
case TINYRL_NO_MATCH:
case TINYRL_MATCH_WITH_EXTENSIONS:
case TINYRL_AMBIGUOUS:
case TINYRL_COMPLETED_AMBIGUOUS:
/* oops don't change the result and let the bell ring */
break;
}
/* keep the compiler happy */
key = key;
return result;
}
/*-------------------------------------------------------- */
static void tinyrl_fini(tinyrl_t * this)
{
/* delete the history session */
tinyrl_history_delete(this->history);
/* delete the terminal session */
tinyrl_vt100_delete(this->term);
/* free up any dynamic strings */
lub_string_free(this->buffer);
lub_string_free(this->kill_string);
lub_string_free(this->last_buffer);
lub_string_free(this->prompt);
}
/*-------------------------------------------------------- */
static void
tinyrl_init(tinyrl_t * this,
FILE * instream, FILE * outstream,
unsigned stifle, tinyrl_completion_func_t * complete_fn)
{
int i;
for (i = 0; i < NUM_HANDLERS; i++) {
this->handlers[i] = tinyrl_key_default;
}
/* default handlers */
this->handlers[KEY_CR] = tinyrl_key_crlf;
this->handlers[KEY_LF] = tinyrl_key_crlf;
this->handlers[KEY_ETX] = tinyrl_key_interrupt;
this->handlers[KEY_DEL] = tinyrl_key_backspace;
this->handlers[KEY_BS] = tinyrl_key_backspace;
this->handlers[KEY_EOT] = tinyrl_key_delete;
this->handlers[KEY_ESC] = tinyrl_key_escape;
this->handlers[KEY_FF] = tinyrl_key_clear_screen;
this->handlers[KEY_NAK] = tinyrl_key_erase_line;
this->handlers[KEY_SOH] = tinyrl_key_start_of_line;
this->handlers[KEY_ENQ] = tinyrl_key_end_of_line;
this->handlers[KEY_VT] = tinyrl_key_kill;
this->handlers[KEY_EM] = tinyrl_key_yank;
this->handlers[KEY_HT] = tinyrl_key_tab;
this->handlers[KEY_ETB] = tinyrl_key_backword;
this->line = NULL;
this->max_line_length = 0;
this->prompt = NULL;
this->prompt_size = 0;
this->buffer = NULL;
this->buffer_size = 0;
this->done = BOOL_FALSE;
this->completion_over = BOOL_FALSE;
this->point = 0;
this->end = 0;
this->attempted_completion_function = complete_fn;
this->timeout_fn = tinyrl_timeout_default;
this->keypress_fn = NULL;
this->state = 0;
this->kill_string = NULL;
this->echo_char = '\0';
this->echo_enabled = BOOL_TRUE;
if (instream)
this->isatty = isatty(fileno(instream)) ?
BOOL_TRUE : BOOL_FALSE;
else
this->isatty = BOOL_FALSE;
this->last_buffer = NULL;
this->last_point = 0;
this->utf8 = BOOL_FALSE;
/* create the vt100 terminal */
this->term = tinyrl_vt100_new(instream, outstream);
this->last_width = tinyrl_vt100__get_width(this->term);
/* create the history */
this->history = tinyrl_history_new(stifle);
}
/*-------------------------------------------------------- */
int tinyrl_printf(const tinyrl_t * this, const char *fmt, ...)
{
va_list args;
int len;
va_start(args, fmt);
len = tinyrl_vt100_vprintf(this->term, fmt, args);
va_end(args);
return len;
}
/*-------------------------------------------------------- */
void tinyrl_delete(tinyrl_t * this)
{
assert(this);
if (this) {
/* let the object tidy itself up */
tinyrl_fini(this);
/* release the memory associate with this instance */
free(this);
}
}
/*-------------------------------------------------------- */
/*#####################################
* EXPORTED INTERFACE
*##################################### */
/*----------------------------------------------------------------------- */
int tinyrl_getchar(const tinyrl_t * this)
{
return tinyrl_vt100_getchar(this->term);
}
/*----------------------------------------------------------------------- */
static void tinyrl_internal_print(const tinyrl_t * this, const char *text)
{
if (this->echo_enabled) {
/* simply echo the line */
tinyrl_vt100_printf(this->term, "%s", text);
} else {
/* replace the line with echo char if defined */
if (this->echo_char) {
unsigned i = strlen(text);
while (i--) {
tinyrl_vt100_printf(this->term, "%c",
this->echo_char);
}
}
}
}
/*----------------------------------------------------------------------- */
static void tinyrl_internal_position(const tinyrl_t *this, int prompt_len,
int line_len, unsigned int width)
{
int rows, cols;
rows = ((line_len + prompt_len) / width) - (prompt_len / width);
cols = ((line_len + prompt_len) % width) - (prompt_len % width);
if (cols > 0)
tinyrl_vt100_cursor_back(this->term, cols);
else if (cols < 0)
tinyrl_vt100_cursor_forward(this->term, -cols);
if (rows > 0)
tinyrl_vt100_cursor_up(this->term, rows);
else if (rows < 0)
tinyrl_vt100_cursor_down(this->term, -rows);
}
/*-------------------------------------------------------- */
/* Jump to first free line after current multiline input */
void tinyrl_multi_crlf(const tinyrl_t * this)
{
unsigned int line_size = strlen(this->last_buffer);
unsigned int line_len = utf8_nsyms(this, this->last_buffer, line_size);
unsigned int count = utf8_nsyms(this, this->last_buffer, this->last_point);
tinyrl_internal_position(this, this->prompt_len + line_len,
- (line_len - count), this->last_width);
tinyrl_crlf(this);
}
/*----------------------------------------------------------------------- */
void tinyrl_redisplay(tinyrl_t * this)
{
unsigned int line_size = strlen(this->line);
unsigned int line_len = utf8_nsyms(this, this->line, line_size);
unsigned int width = tinyrl_vt100__get_width(this->term);
unsigned int count, eq_chars = 0;
int cols;
/* Prepare print position */
if (this->last_buffer && (width == this->last_width)) {
unsigned int eq_len = 0;
/* If line and last line have the equal chars at begining */
eq_chars = lub_string_equal_part(this->line, this->last_buffer,
this->utf8);
eq_len = utf8_nsyms(this, this->last_buffer, eq_chars);
count = utf8_nsyms(this, this->last_buffer, this->last_point);
tinyrl_internal_position(this, this->prompt_len + eq_len,
count - eq_len, width);
} else {
/* Prepare to resize */
if (width != this->last_width) {
tinyrl_vt100_next_line(this->term);
tinyrl_vt100_erase_down(this->term);
}
tinyrl_vt100_printf(this->term, "%s", this->prompt);
}
/* Print current line */
tinyrl_internal_print(this, this->line + eq_chars);
cols = (this->prompt_len + line_len) % width;
if (!cols && (line_size - eq_chars))
tinyrl_vt100_next_line(this->term);
tinyrl_vt100_erase_down(this->term);
/* Move the cursor to the insertion point */
if (this->point < line_size) {
unsigned int pre_len = utf8_nsyms(this,
this->line, this->point);
count = utf8_nsyms(this, this->line + this->point,
line_size - this->point);
tinyrl_internal_position(this, this->prompt_len + pre_len,
count, width);
}
/* Update the display */
(void)tinyrl_vt100_oflush(this->term);
/* Save the last line buffer */
lub_string_free(this->last_buffer);
this->last_buffer = lub_string_dup(this->line);
this->last_point = this->point;
this->last_width = width;
}
/*----------------------------------------------------------------------- */
tinyrl_t *tinyrl_new(FILE * instream, FILE * outstream,
unsigned stifle, tinyrl_completion_func_t * complete_fn)
{
tinyrl_t *this = NULL;
this = malloc(sizeof(tinyrl_t));
if (this)
tinyrl_init(this, instream, outstream, stifle, complete_fn);
return this;
}
/*----------------------------------------------------------------------- */
static char *internal_insertline(tinyrl_t * this, char *buffer)
{
char *p;
char *s = buffer;
/* strip any spurious '\r' or '\n' */
if ((p = strchr(buffer, '\r')))
*p = '\0';
if ((p = strchr(buffer, '\n')))
*p = '\0';
/* skip any whitespace at the beginning of the line */
if (0 == this->point) {
while (*s && isspace(*s))
s++;
}
if (*s) {
/* append this string to the input buffer */
(void)tinyrl_insert_text(this, s);
}
/* echo the command to the output stream */
tinyrl_redisplay(this);
return s;
}
/*----------------------------------------------------------------------- */
static char *internal_readline(tinyrl_t * this,
void *context, const char *str)
{
FILE *istream = tinyrl_vt100__get_istream(this->term);
char *result = NULL;
int lerrno = 0;
/* initialise for reading a line */
this->done = BOOL_FALSE;
this->point = 0;
this->end = 0;
this->buffer = lub_string_dup("");
this->buffer_size = strlen(this->buffer);
this->line = this->buffer;
this->context = context;
if (this->isatty && !str) {
/* set the terminal into raw input mode */
tty_set_raw_mode(this);
tinyrl_reset_line_state(this);
while (!this->done) {
int key;
/* get a key */
key = tinyrl_getchar(this);
/* has the input stream terminated? */
if (key >= 0) { /* Real key pressed */
/* Common callback for any key */
if (this->keypress_fn)
this->keypress_fn(this, key);
/* Call the handler for this key */
if (!this->handlers[key](this, key))
tinyrl_ding(this);
if (this->done) {
/*
* If the last character in the line (other than
* the null) is a space remove it.
*/
if (this->end &&
isspace(this->line[this->end - 1]))
tinyrl_delete_text(this,
this->end - 1,
this->end);
} else {
/* Update the display if the key
is not first UTF8 byte */
if (!(this->utf8 &&
(UTF8_11 == (key & UTF8_MASK))))
tinyrl_redisplay(this);
}
} else { /* Error || EOF || Timeout */
if ((VT100_TIMEOUT == key) &&
!this->timeout_fn(this))
continue;
/* time to finish the session */
this->done = BOOL_TRUE;
this->line = NULL;
lerrno = ENOENT;
}
}
/* restores the terminal mode */
tty_restore_mode(this);
} else {
/* This is a non-interactive set of commands */
char *s = NULL, buffer[80];
size_t len = sizeof(buffer);
char *tmp = NULL;
/* manually reset the line state without redisplaying */
lub_string_free(this->last_buffer);
this->last_buffer = NULL;
if (str) {
tmp = lub_string_dup(str);
s = internal_insertline(this, tmp);
} else {
while (istream && (sizeof(buffer) == len) &&
(s = fgets(buffer, sizeof(buffer), istream))) {
s = internal_insertline(this, buffer);
len = strlen(buffer) + 1; /* account for the '\0' */
}
if (!s || ((this->line[0] == '\0') && feof(istream))) {
/* time to finish the session */
this->line = NULL;
lerrno = ENOENT;
}
}
/*
* check against fgets returning null as either error or end of file.
* This is a measure to stop potential task spin on encountering an
* error from fgets.
*/
if (this->line && !this->handlers[KEY_LF](this, KEY_LF)) {
/* an issue has occured */
this->line = NULL;
lerrno = ENOEXEC;
}
if (str)
lub_string_free(tmp);
}
/*
* duplicate the string for return to the client
* we have to duplicate as we may be referencing a
* history entry or our internal buffer
*/
result = this->line ? lub_string_dup(this->line) : NULL;
/* free our internal buffer */
free(this->buffer);
this->buffer = NULL;
if (!result)
errno = lerrno; /* get saved errno */
return result;
}
/*----------------------------------------------------------------------- */
char *tinyrl_readline(tinyrl_t * this, void *context)
{
return internal_readline(this, context, NULL);
}
/*----------------------------------------------------------------------- */
char *tinyrl_forceline(tinyrl_t * this, void *context, const char *line)
{
return internal_readline(this, context, line);
}
/*----------------------------------------------------------------------- */
/*
* Ensure that buffer has enough space to hold len characters,
* possibly reallocating it if necessary. The function returns BOOL_TRUE
* if the line is successfully extended, BOOL_FALSE if not.
*/
bool_t tinyrl_extend_line_buffer(tinyrl_t * this, unsigned len)
{
bool_t result = BOOL_TRUE;
char *new_buffer;
size_t new_len = len;
if (this->buffer_size >= len)
return result;
/*
* What we do depends on whether we are limited by
* memory or a user imposed limit.
*/
if (this->max_line_length == 0) {
/* make sure we don't realloc too often */
if (new_len < this->buffer_size + 10)
new_len = this->buffer_size + 10;
/* leave space for terminator */
new_buffer = realloc(this->buffer, new_len + 1);
if (!new_buffer) {
tinyrl_ding(this);
result = BOOL_FALSE;
} else {
this->buffer_size = new_len;
this->line = this->buffer = new_buffer;
}
} else {
if (new_len < this->max_line_length) {
/* Just reallocate once to the max size */
new_buffer = realloc(this->buffer,
this->max_line_length);
if (!new_buffer) {
tinyrl_ding(this);
result = BOOL_FALSE;
} else {
this->buffer_size =
this->max_line_length - 1;
this->line = this->buffer = new_buffer;
}
} else {
tinyrl_ding(this);
result = BOOL_FALSE;
}
}
return result;
}
/*----------------------------------------------------------------------- */
/*
* Insert text into the line at the current cursor position.
*/
bool_t tinyrl_insert_text(tinyrl_t * this, const char *text)
{
unsigned delta = strlen(text);
/*
* If the client wants to change the line ensure that the line and buffer
* references are in sync
*/
changed_line(this);
if ((delta + this->end) > (this->buffer_size)) {
/* extend the current buffer */
if (BOOL_FALSE ==
tinyrl_extend_line_buffer(this, this->end + delta))
return BOOL_FALSE;
}
if (this->point < this->end) {
/* move the current text to the right (including the terminator) */
memmove(&this->buffer[this->point + delta],
&this->buffer[this->point],
(this->end - this->point) + 1);
} else {
/* terminate the string */
this->buffer[this->end + delta] = '\0';
}
/* insert the new text */
strncpy(&this->buffer[this->point], text, delta);
/* now update the indexes */
this->point += delta;
this->end += delta;
return BOOL_TRUE;
}
/*----------------------------------------------------------------------- */
/*
* A convenience function for displaying a list of strings in columnar
* format on Readline's output stream. matches is the list of strings,
* in argv format, such as a list of completion matches. len is the number
* of strings in matches, and max is the length of the longest string in matches.
* This function uses the setting of print-completions-horizontally to select
* how the matches are displayed
*/
void
tinyrl_display_matches(const tinyrl_t * this,
char *const *matches, unsigned len, size_t max)
{
unsigned r, c;
unsigned width = tinyrl_vt100__get_width(this->term);
unsigned cols = width / (max + 1); /* allow for a space between words */
unsigned rows = len / cols + 1;
assert(matches);
if (matches) {
len--, matches++; /* skip the subtitution string */
/* print out a table of completions */
for (r = 0; r < rows && len; r++) {
for (c = 0; c < cols && len; c++) {
const char *match = *matches++;
len--;
tinyrl_vt100_printf(this->term, "%-*s ", max,
match);
}
tinyrl_crlf(this);
}
}
}
/*----------------------------------------------------------------------- */
/*
* Delete the text between start and end in the current line. (inclusive)
* This adjusts the rl_point and rl_end indexes appropriately.
*/
void tinyrl_delete_text(tinyrl_t * this, unsigned start, unsigned end)
{
unsigned delta;
/*
* If the client wants to change the line ensure that the line and buffer
* references are in sync
*/
changed_line(this);
/* make sure we play it safe */
if (start > end) {
unsigned tmp = end;
start = end;
end = tmp;
}
if (end > this->end)
end = this->end;
delta = (end - start) + 1;
/* move any text which is left */
memmove(&this->buffer[start],
&this->buffer[start + delta], this->end - end);
/* now adjust the indexs */
if (this->point >= start) {
if (this->point > end) {
/* move the insertion point back appropriately */
this->point -= delta;
} else {
/* move the insertion point to the start */
this->point = start;
}
}
if (this->end > end)
this->end -= delta;
else
this->end = start;
/* put a terminator at the end of the buffer */
this->buffer[this->end] = '\0';
}
/*----------------------------------------------------------------------- */
bool_t tinyrl_bind_key(tinyrl_t * this, int key, tinyrl_key_func_t * fn)
{
bool_t result = BOOL_FALSE;
if ((key >= 0) && (key < 256)) {
/* set the key handling function */
this->handlers[key] = fn;
result = BOOL_TRUE;
}
return result;
}
/*-------------------------------------------------------- */
/*
* Returns an array of strings which is a list of completions for text.
* If there are no completions, returns NULL. The first entry in the
* returned array is the substitution for text. The remaining entries
* are the possible completions. The array is terminated with a NULL pointer.
*
* entry_func is a function of two args, and returns a char *.
* The first argument is text. The second is a state argument;
* it is zero on the first call, and non-zero on subsequent calls.
* entry_func returns a NULL pointer to the caller when there are no
* more matches.
*/
char **tinyrl_completion(tinyrl_t * this,
const char *line, unsigned start, unsigned end,
tinyrl_compentry_func_t * entry_func)
{
unsigned state = 0;
size_t size = 1;
unsigned offset = 1; /* need at least one entry for the substitution */
char **matches = NULL;
char *match;
/* duplicate the string upto the insertion point */
char *text = lub_string_dupn(line, end);
/* now try and find possible completions */
while ((match = entry_func(this, text, start, state++))) {
if (size == offset) {
/* resize the buffer if needed - the +1 is for the NULL terminator */
size += 10;
matches =
realloc(matches, (sizeof(char *) * (size + 1)));
}
/* not much we can do... */
if (!matches)
break;
matches[offset] = match;
/*
* augment the substitute string with this entry
*/
if (1 == offset) {
/* let's be optimistic */
matches[0] = lub_string_dup(match);
} else {
char *p = matches[0];
size_t match_len = strlen(p);
/* identify the common prefix */
while ((tolower(*p) == tolower(*match)) && match_len--) {
p++, match++;
}
/* terminate the prefix string */
*p = '\0';
}
offset++;
}
/* be a good memory citizen */
lub_string_free(text);
if (matches)
matches[offset] = NULL;
return matches;
}
/*-------------------------------------------------------- */
void tinyrl_delete_matches(char **this)
{
char **matches = this;
while (*matches) {
/* release the memory for each contained string */
free(*matches++);
}
/* release the memory for the array */
free(this);
}
/*-------------------------------------------------------- */
void tinyrl_crlf(const tinyrl_t * this)
{
tinyrl_vt100_printf(this->term, "\n");
}
/*-------------------------------------------------------- */
/*
* Ring the terminal bell, obeying the setting of bell-style.
*/
void tinyrl_ding(const tinyrl_t * this)
{
tinyrl_vt100_ding(this->term);
}
/*-------------------------------------------------------- */
void tinyrl_reset_line_state(tinyrl_t * this)
{
/* start from scratch */
lub_string_free(this->last_buffer);
this->last_buffer = NULL;
tinyrl_redisplay(this);
}
/*-------------------------------------------------------- */
void tinyrl_replace_line(tinyrl_t * this, const char *text, int clear_undo)
{
size_t new_len = strlen(text);
/* ignored for now */
clear_undo = clear_undo;
/* ensure there is sufficient space */
if (tinyrl_extend_line_buffer(this, new_len)) {
/* overwrite the current contents of the buffer */
strcpy(this->buffer, text);
/* set the insert point and end point */
this->point = this->end = new_len;
}
tinyrl_redisplay(this);
}
/*-------------------------------------------------------- */
static tinyrl_match_e
tinyrl_do_complete(tinyrl_t * this, bool_t with_extensions)
{
tinyrl_match_e result = TINYRL_NO_MATCH;
char **matches = NULL;
unsigned start, end;
bool_t completion = BOOL_FALSE;
bool_t prefix = BOOL_FALSE;
int i = 0;
/* find the start and end of the current word */
start = end = this->point;
while (start && !isspace(this->line[start - 1]))
start--;
if (this->attempted_completion_function) {
this->completion_over = BOOL_FALSE;
this->completion_error_over = BOOL_FALSE;
/* try and complete the current line buffer */
matches = this->attempted_completion_function(this,
this->line, start, end);
}
if (!matches && (BOOL_FALSE == this->completion_over)) {
/* insert default completion call here... */
}
if (!matches)
return result;
/* identify and insert a common prefix if there is one */
if (0 != strncmp(matches[0], &this->line[start],
strlen(matches[0]))) {
/*
* delete the original text not including
* the current insertion point character
*/
if (this->end != end)
end--;
tinyrl_delete_text(this, start, end);
if (BOOL_FALSE == tinyrl_insert_text(this, matches[0]))
return TINYRL_NO_MATCH;
completion = BOOL_TRUE;
}
for (i = 1; matches[i]; i++) {
/* this is just a prefix string */
if (0 == lub_string_nocasecmp(matches[0], matches[i]))
prefix = BOOL_TRUE;
}
/* is there more than one completion? */
if (matches[2]) {
char **tmp = matches;
unsigned max, len;
max = len = 0;
while (*tmp) {
size_t size = strlen(*tmp++);
len++;
if (size > max)
max = size;
}
if (completion)
result = TINYRL_COMPLETED_AMBIGUOUS;
else if (prefix)
result = TINYRL_MATCH_WITH_EXTENSIONS;
else
result = TINYRL_AMBIGUOUS;
if (with_extensions || !prefix) {
/* Either we always want to show extensions or
* we haven't been able to complete the current line
* and there is just a prefix, so let the user see the options
*/
tinyrl_crlf(this);
tinyrl_display_matches(this, matches, len, max);
tinyrl_reset_line_state(this);
}
} else {
result = completion ?
TINYRL_COMPLETED_MATCH : TINYRL_MATCH;
}
/* free the memory */
tinyrl_delete_matches(matches);
/* redisplay the line */
tinyrl_redisplay(this);
return result;
}
/*-------------------------------------------------------- */
tinyrl_match_e tinyrl_complete_with_extensions(tinyrl_t * this)
{
return tinyrl_do_complete(this, BOOL_TRUE);
}
/*-------------------------------------------------------- */
tinyrl_match_e tinyrl_complete(tinyrl_t * this)
{
return tinyrl_do_complete(this, BOOL_FALSE);
}
/*-------------------------------------------------------- */
void *tinyrl__get_context(const tinyrl_t * this)
{
return this->context;
}
/*--------------------------------------------------------- */
const char *tinyrl__get_line(const tinyrl_t * this)
{
return this->line;
}
/*--------------------------------------------------------- */
tinyrl_history_t *tinyrl__get_history(const tinyrl_t * this)
{
return this->history;
}
/*--------------------------------------------------------- */
void tinyrl_completion_over(tinyrl_t * this)
{
this->completion_over = BOOL_TRUE;
}
/*--------------------------------------------------------- */
void tinyrl_completion_error_over(tinyrl_t * this)
{
this->completion_error_over = BOOL_TRUE;
}
/*--------------------------------------------------------- */
bool_t tinyrl_is_completion_error_over(const tinyrl_t * this)
{
return this->completion_error_over;
}
/*--------------------------------------------------------- */
void tinyrl_done(tinyrl_t * this)
{
this->done = BOOL_TRUE;
}
/*--------------------------------------------------------- */
void tinyrl_enable_echo(tinyrl_t * this)
{
this->echo_enabled = BOOL_TRUE;
}
/*--------------------------------------------------------- */
void tinyrl_disable_echo(tinyrl_t * this, char echo_char)
{
this->echo_enabled = BOOL_FALSE;
this->echo_char = echo_char;
}
/*--------------------------------------------------------- */
void tinyrl__set_istream(tinyrl_t * this, FILE * istream)
{
tinyrl_vt100__set_istream(this->term, istream);
if (istream)
this->isatty = isatty(fileno(istream)) ? BOOL_TRUE : BOOL_FALSE;
else
this->isatty = BOOL_FALSE;
}
/*-------------------------------------------------------- */
bool_t tinyrl__get_isatty(const tinyrl_t * this)
{
return this->isatty;
}
/*-------------------------------------------------------- */
FILE *tinyrl__get_istream(const tinyrl_t * this)
{
return tinyrl_vt100__get_istream(this->term);
}
/*-------------------------------------------------------- */
FILE *tinyrl__get_ostream(const tinyrl_t * this)
{
return tinyrl_vt100__get_ostream(this->term);
}
/*-------------------------------------------------------- */
const char *tinyrl__get_prompt(const tinyrl_t * this)
{
return this->prompt;
}
/*-------------------------------------------------------- */
void tinyrl__set_prompt(tinyrl_t *this, const char *prompt)
{
if (this->prompt) {
lub_string_free(this->prompt);
this->prompt_size = 0;
this->prompt_len = 0;
}
this->prompt = lub_string_dup(prompt);
if (this->prompt) {
this->prompt_size = strlen(this->prompt);
this->prompt_len = utf8_nsyms(this, this->prompt,
this->prompt_size);
}
}
/*-------------------------------------------------------- */
bool_t tinyrl__get_utf8(const tinyrl_t * this)
{
return this->utf8;
}
/*-------------------------------------------------------- */
void tinyrl__set_utf8(tinyrl_t * this, bool_t utf8)
{
this->utf8 = utf8;
}
/*-------------------------------------------------------- */
void tinyrl__set_timeout(tinyrl_t *this, int timeout)
{
tinyrl_vt100__set_timeout(this->term, timeout);
}
/*-------------------------------------------------------- */
void tinyrl__set_timeout_fn(tinyrl_t *this,
tinyrl_timeout_fn_t *fn)
{
this->timeout_fn = fn;
}
/*-------------------------------------------------------- */
void tinyrl__set_keypress_fn(tinyrl_t *this,
tinyrl_keypress_fn_t *fn)
{
this->keypress_fn = fn;
}
/*-------------------------------------------------------- */
bool_t tinyrl_is_quoting(const tinyrl_t * this)
{
bool_t result = BOOL_FALSE;
/* count the quotes upto the current insertion point */
unsigned i = 0;
while (i < this->point) {
if (result && (this->line[i] == '\\')) {
i++;
if (i >= this->point)
break;
i++;
continue;
}
if (this->line[i++] == '"') {
result = result ? BOOL_FALSE : BOOL_TRUE;
}
}
return result;
}
/*-------------------------------------------------------- */
bool_t tinyrl_is_empty(const tinyrl_t *this)
{
return (this->point == 0) ? BOOL_TRUE : BOOL_FALSE;
}
/*--------------------------------------------------------- */
void tinyrl_limit_line_length(tinyrl_t * this, unsigned length)
{
this->max_line_length = length;
}
/*--------------------------------------------------------- */
extern unsigned tinyrl__get_width(const tinyrl_t *this)
{
return tinyrl_vt100__get_width(this->term);
}
/*--------------------------------------------------------- */
extern unsigned tinyrl__get_height(const tinyrl_t *this)
{
return tinyrl_vt100__get_height(this->term);
}
/*----------------------------------------------------------*/
int tinyrl__save_history(const tinyrl_t *this, const char *fname)
{
return tinyrl_history_save(this->history, fname);
}
/*----------------------------------------------------------*/
int tinyrl__restore_history(tinyrl_t *this, const char *fname)
{
return tinyrl_history_restore(this->history, fname);
}
/*----------------------------------------------------------*/
void tinyrl__stifle_history(tinyrl_t *this, unsigned int stifle)
{
tinyrl_history_stifle(this->history, stifle);
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
tinyrl/tinyrl.c
|
C
|
bsd
| 38,140
|
#undef __STRICT_ANSI__ /* we need to use fileno() */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/select.h>
#include <errno.h>
#include "private.h"
typedef struct {
const char* sequence;
tinyrl_vt100_escape_t code;
} vt100_decode_t;
/* This table maps the vt100 escape codes to an enumeration */
static vt100_decode_t cmds[] = {
{"[A", tinyrl_vt100_CURSOR_UP},
{"[B", tinyrl_vt100_CURSOR_DOWN},
{"[C", tinyrl_vt100_CURSOR_RIGHT},
{"[D", tinyrl_vt100_CURSOR_LEFT},
{"[H", tinyrl_vt100_HOME},
{"[1~", tinyrl_vt100_HOME},
{"[F", tinyrl_vt100_END},
{"[4~", tinyrl_vt100_END},
{"[2~", tinyrl_vt100_INSERT},
{"[3~", tinyrl_vt100_DELETE},
{"[5~", tinyrl_vt100_PGUP},
{"[6~", tinyrl_vt100_PGDOWN},
};
/*--------------------------------------------------------- */
static void _tinyrl_vt100_setInputNonBlocking(const tinyrl_vt100_t * this)
{
#if defined(STDIN_FILENO)
int flags = (fcntl(STDIN_FILENO, F_GETFL, 0) | O_NONBLOCK);
fcntl(STDIN_FILENO, F_SETFL, flags);
#endif /* STDIN_FILENO */
}
/*--------------------------------------------------------- */
static void _tinyrl_vt100_setInputBlocking(const tinyrl_vt100_t * this)
{
#if defined(STDIN_FILENO)
int flags = (fcntl(STDIN_FILENO, F_GETFL, 0) & ~O_NONBLOCK);
fcntl(STDIN_FILENO, F_SETFL, flags);
#endif /* STDIN_FILENO */
}
/*--------------------------------------------------------- */
tinyrl_vt100_escape_t tinyrl_vt100_escape_decode(const tinyrl_vt100_t * this)
{
tinyrl_vt100_escape_t result = tinyrl_vt100_UNKNOWN;
char sequence[10], *p = sequence;
int c;
unsigned i;
if (!this->istream)
return tinyrl_vt100_UNKNOWN;
/* before the while loop, set the input as non-blocking */
_tinyrl_vt100_setInputNonBlocking(this);
/* dump the control sequence into our sequence buffer
* ANSI standard control sequences will end
* with a character between 64 - 126
*/
while (1) {
c = getc(this->istream);
/* ignore no-character condition */
if (-1 != c) {
*p++ = (c & 0xFF);
if ((c != '[') && (c > 63)) {
/* this is an ANSI control sequence terminator code */
result = tinyrl_vt100_CURSOR_UP; /* just a non-UNKNOWN value */
break;
}
} else {
result = tinyrl_vt100_UNKNOWN;
break;
}
}
/* terminate the string */
*p = '\0';
/* restore the blocking status */
_tinyrl_vt100_setInputBlocking(this);
if (tinyrl_vt100_UNKNOWN != result) {
p = sequence;
result = tinyrl_vt100_UNKNOWN;
/* now decode the sequence */
for (i = 0; i < sizeof(cmds) / sizeof(vt100_decode_t); i++) {
if (strcmp(cmds[i].sequence, p) == 0) {
/* found the code in the lookup table */
result = cmds[i].code;
break;
}
}
}
return result;
}
/*-------------------------------------------------------- */
int tinyrl_vt100_printf(const tinyrl_vt100_t * this, const char *fmt, ...)
{
va_list args;
int len;
if (!this->ostream)
return 0;
va_start(args, fmt);
len = tinyrl_vt100_vprintf(this, fmt, args);
va_end(args);
return len;
}
/*-------------------------------------------------------- */
int
tinyrl_vt100_vprintf(const tinyrl_vt100_t * this, const char *fmt, va_list args)
{
if (!this->ostream)
return 0;
return vfprintf(this->ostream, fmt, args);
}
/*-------------------------------------------------------- */
int tinyrl_vt100_getchar(const tinyrl_vt100_t *this)
{
unsigned char c;
int istream_fd;
fd_set rfds;
struct timeval tv;
int retval;
ssize_t res;
if (!this->istream)
return VT100_ERR;
istream_fd = fileno(this->istream);
/* Just wait for the input if no timeout */
if (this->timeout <= 0) {
while (((res = read(istream_fd, &c, 1)) < 0) &&
(EAGAIN == errno));
/* EOF or error */
if (res < 0)
return VT100_ERR;
if (!res)
return VT100_EOF;
return c;
}
/* Set timeout for the select() */
FD_ZERO(&rfds);
FD_SET(istream_fd, &rfds);
tv.tv_sec = this->timeout;
tv.tv_usec = 0;
while (((retval = select(istream_fd + 1, &rfds, NULL, NULL, &tv)) < 0) &&
(EAGAIN == errno));
/* Error or timeout */
if (retval < 0)
return VT100_ERR;
if (!retval)
return VT100_TIMEOUT;
res = read(istream_fd, &c, 1);
/* EOF or error */
if (res < 0)
return VT100_ERR;
if (!res)
return VT100_EOF;
return c;
}
/*-------------------------------------------------------- */
int tinyrl_vt100_oflush(const tinyrl_vt100_t * this)
{
if (!this->ostream)
return 0;
return fflush(this->ostream);
}
/*-------------------------------------------------------- */
int tinyrl_vt100_ierror(const tinyrl_vt100_t * this)
{
if (!this->istream)
return 0;
return ferror(this->istream);
}
/*-------------------------------------------------------- */
int tinyrl_vt100_oerror(const tinyrl_vt100_t * this)
{
if (!this->ostream)
return 0;
return ferror(this->ostream);
}
/*-------------------------------------------------------- */
int tinyrl_vt100_ieof(const tinyrl_vt100_t * this)
{
if (!this->istream)
return 0;
return feof(this->istream);
}
/*-------------------------------------------------------- */
int tinyrl_vt100_eof(const tinyrl_vt100_t * this)
{
if (!this->istream)
return 0;
return feof(this->istream);
}
/*-------------------------------------------------------- */
unsigned int tinyrl_vt100__get_width(const tinyrl_vt100_t *this)
{
#ifdef TIOCGWINSZ
struct winsize ws;
int res;
#endif
if(!this->ostream)
return 80;
#ifdef TIOCGWINSZ
ws.ws_col = 0;
res = ioctl(fileno(this->ostream), TIOCGWINSZ, &ws);
if (res || !ws.ws_col)
return 80;
return ws.ws_col;
#else
return 80;
#endif
}
/*-------------------------------------------------------- */
unsigned int tinyrl_vt100__get_height(const tinyrl_vt100_t *this)
{
#ifdef TIOCGWINSZ
struct winsize ws;
int res;
#endif
if(!this->ostream)
return 25;
#ifdef TIOCGWINSZ
ws.ws_row = 0;
res = ioctl(fileno(this->ostream), TIOCGWINSZ, &ws);
if (res || !ws.ws_row)
return 25;
return ws.ws_row;
#else
return 25;
#endif
}
/*-------------------------------------------------------- */
static void
tinyrl_vt100_init(tinyrl_vt100_t * this, FILE * istream, FILE * ostream)
{
this->istream = istream;
this->ostream = ostream;
this->timeout = -1; /* No timeout by default */
}
/*-------------------------------------------------------- */
static void tinyrl_vt100_fini(tinyrl_vt100_t * this)
{
/* nothing to do yet... */
this = this;
}
/*-------------------------------------------------------- */
tinyrl_vt100_t *tinyrl_vt100_new(FILE * istream, FILE * ostream)
{
tinyrl_vt100_t *this = NULL;
this = malloc(sizeof(tinyrl_vt100_t));
if (this) {
tinyrl_vt100_init(this, istream, ostream);
}
return this;
}
/*-------------------------------------------------------- */
void tinyrl_vt100_delete(tinyrl_vt100_t * this)
{
tinyrl_vt100_fini(this);
/* release the memory */
free(this);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_ding(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c", KEY_BEL);
(void)tinyrl_vt100_oflush(this);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_attribute_reset(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c[0m", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_attribute_bright(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c[1m", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_attribute_dim(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c[2m", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_attribute_underscore(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c[4m", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_attribute_blink(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c[5m", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_attribute_reverse(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c[7m", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_attribute_hidden(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c[8m", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_erase_line(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c[2K", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_clear_screen(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c[2J", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_cursor_save(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c7", KEY_ESC); /* VT100 */
/* tinyrl_vt100_printf(this, "%c[s", KEY_ESC); */ /* ANSI */
}
/*-------------------------------------------------------- */
void tinyrl_vt100_cursor_restore(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c8", KEY_ESC); /* VT100 */
/* tinyrl_vt100_printf(this, "%c[u", KEY_ESC); */ /* ANSI */
}
/*-------------------------------------------------------- */
void tinyrl_vt100_cursor_forward(const tinyrl_vt100_t * this, unsigned count)
{
tinyrl_vt100_printf(this, "%c[%dC", KEY_ESC, count);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_cursor_back(const tinyrl_vt100_t * this, unsigned count)
{
tinyrl_vt100_printf(this, "%c[%dD", KEY_ESC, count);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_cursor_up(const tinyrl_vt100_t * this, unsigned count)
{
tinyrl_vt100_printf(this, "%c[%dA", KEY_ESC, count);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_cursor_down(const tinyrl_vt100_t * this, unsigned count)
{
tinyrl_vt100_printf(this, "%c[%dB", KEY_ESC, count);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_scroll_up(const tinyrl_vt100_t *this)
{
tinyrl_vt100_printf(this, "%cD", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_scroll_down(const tinyrl_vt100_t *this)
{
tinyrl_vt100_printf(this, "%cM", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_next_line(const tinyrl_vt100_t *this)
{
tinyrl_vt100_printf(this, "%cE", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_cursor_home(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c[H", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100_erase(const tinyrl_vt100_t * this, unsigned count)
{
tinyrl_vt100_printf(this, "%c[%dP", KEY_ESC, count);
}
/*-------------------------------------------------------- */
void tinyrl_vt100__set_timeout(tinyrl_vt100_t *this, int timeout)
{
this->timeout = timeout;
}
/*-------------------------------------------------------- */
void tinyrl_vt100_erase_down(const tinyrl_vt100_t * this)
{
tinyrl_vt100_printf(this, "%c[J", KEY_ESC);
}
/*-------------------------------------------------------- */
void tinyrl_vt100__set_istream(tinyrl_vt100_t * this, FILE * istream)
{
this->istream = istream;
}
/*-------------------------------------------------------- */
FILE *tinyrl_vt100__get_istream(const tinyrl_vt100_t * this)
{
return this->istream;
}
/*-------------------------------------------------------- */
FILE *tinyrl_vt100__get_ostream(const tinyrl_vt100_t * this)
{
return this->ostream;
}
/*-------------------------------------------------------- */
|
zzysjtu-klish
|
tinyrl/vt100/vt100.c
|
C
|
bsd
| 11,676
|
#include "tinyrl/vt100.h"
struct _tinyrl_vt100 {
FILE *istream;
FILE *ostream;
int timeout; /* Input timeout in seconds */
};
|
zzysjtu-klish
|
tinyrl/vt100/private.h
|
C
|
bsd
| 132
|
/*
* vt100.h
*
* A simple class representing a vt100 terminal
*/
/**
\ingroup tinyrl
\defgroup tinyrl_vt100 vt100
@{
\brief A simple class for controlling and interacting with a VT100 compatible
terminal.
This class has been implemented pragmatically in an as needed fashion, so
doesn't support all the features of a VT100 terminal.
*/
#ifndef _tinyrl_vt100_h
#define _tinyrl_vt100_h
#include <stdio.h>
#include <stdarg.h>
#include "lub/c_decl.h"
#include "lub/types.h"
_BEGIN_C_DECL typedef struct _tinyrl_vt100 tinyrl_vt100_t;
/* define the Key codes */
#define KEY_NUL 0 /**< ^@ Null character */
#define KEY_SOH 1 /**< ^A Start of heading, = console interrupt */
#define KEY_STX 2 /**< ^B Start of text, maintenance mode on HP console */
#define KEY_ETX 3 /**< ^C End of text */
#define KEY_EOT 4 /**< ^D End of transmission, not the same as ETB */
#define KEY_ENQ 5 /**< ^E Enquiry, goes with ACK; old HP flow control */
#define KEY_ACK 6 /**< ^F Acknowledge, clears ENQ logon hand */
#define KEY_BEL 7 /**< ^G Bell, rings the bell... */
#define KEY_BS 8 /**< ^H Backspace, works on HP terminals/computers */
#define KEY_HT 9 /**< ^I Horizontal tab, move to next tab stop */
#define KEY_LF 10 /**< ^J Line Feed */
#define KEY_VT 11 /**< ^K Vertical tab */
#define KEY_FF 12 /**< ^L Form Feed, page eject */
#define KEY_CR 13 /**< ^M Carriage Return*/
#define KEY_SO 14 /**< ^N Shift Out, alternate character set */
#define KEY_SI 15 /**< ^O Shift In, resume defaultn character set */
#define KEY_DLE 16 /**< ^P Data link escape */
#define KEY_DC1 17 /**< ^Q XON, with XOFF to pause listings; "okay to send". */
#define KEY_DC2 18 /**< ^R Device control 2, block-mode flow control */
#define KEY_DC3 19 /**< ^S XOFF, with XON is TERM=18 flow control */
#define KEY_DC4 20 /**< ^T Device control 4 */
#define KEY_NAK 21 /**< ^U Negative acknowledge */
#define KEY_SYN 22 /**< ^V Synchronous idle */
#define KEY_ETB 23 /**< ^W End transmission block, not the same as EOT */
#define KEY_CAN 24 /**< ^X Cancel line, MPE echoes !!! */
#define KEY_EM 25 /**< ^Y End of medium, Control-Y interrupt */
#define KEY_SUB 26 /**< ^Z Substitute */
#define KEY_ESC 27 /**< ^[ Escape, next character is not echoed */
#define KEY_FS 28 /**< ^\ File separator */
#define KEY_GS 29 /**< ^] Group separator */
#define KEY_RS 30 /**< ^^ Record separator, block-mode terminator */
#define KEY_US 31 /**< ^_ Unit separator */
#define KEY_DEL 127 /**< Delete (not a real control character...) */
/**
* This enumeration is used to identify the types of escape code
*/
typedef enum {
tinyrl_vt100_UNKNOWN, /**< Undefined escape sequence */
tinyrl_vt100_CURSOR_UP, /**< Move the cursor up */
tinyrl_vt100_CURSOR_DOWN, /**< Move the cursor down */
tinyrl_vt100_CURSOR_LEFT, /**< Move the cursor left */
tinyrl_vt100_CURSOR_RIGHT, /**< Move the cursor right */
tinyrl_vt100_HOME, /**< Move the cursor to the beginning of the line */
tinyrl_vt100_END, /**< Move the cursor to the end of the line */
tinyrl_vt100_INSERT, /**< No action at the moment */
tinyrl_vt100_DELETE, /**< Delete character on the right */
tinyrl_vt100_PGUP, /**< No action at the moment */
tinyrl_vt100_PGDOWN /**< No action at the moment */
} tinyrl_vt100_escape_t;
/* Return values from vt100_getchar() */
#define VT100_EOF -1
#define VT100_TIMEOUT -2
#define VT100_ERR -3
extern tinyrl_vt100_t *tinyrl_vt100_new(FILE * instream, FILE * outstream);
extern void tinyrl_vt100_delete(tinyrl_vt100_t * instance);
/*lint -esym(534,tinyrl_vt100_printf) Ignoring return value of function */
extern int tinyrl_vt100_printf(const tinyrl_vt100_t * instance, const char *fmt, ...
);
extern int
tinyrl_vt100_vprintf(const tinyrl_vt100_t * instance,
const char *fmt, va_list args);
extern int tinyrl_vt100_oflush(const tinyrl_vt100_t * instance);
extern int tinyrl_vt100_ierror(const tinyrl_vt100_t * instance);
extern int tinyrl_vt100_oerror(const tinyrl_vt100_t * instance);
extern int tinyrl_vt100_ieof(const tinyrl_vt100_t * instance);
extern int tinyrl_vt100_getchar(const tinyrl_vt100_t * instance);
extern unsigned tinyrl_vt100__get_width(const tinyrl_vt100_t * instance);
extern unsigned tinyrl_vt100__get_height(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100__set_timeout(tinyrl_vt100_t *instance, int timeout);
extern void
tinyrl_vt100__set_istream(tinyrl_vt100_t * instance, FILE * istream);
extern FILE *tinyrl_vt100__get_istream(const tinyrl_vt100_t * instance);
extern FILE *tinyrl_vt100__get_ostream(const tinyrl_vt100_t * instance);
extern tinyrl_vt100_escape_t
tinyrl_vt100_escape_decode(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_ding(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_attribute_reset(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_attribute_bright(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_attribute_dim(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_attribute_underscore(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_attribute_blink(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_attribute_reverse(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_attribute_hidden(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_erase_line(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_clear_screen(const tinyrl_vt100_t * instance);
extern void
tinyrl_vt100_cursor_back(const tinyrl_vt100_t * instance, unsigned count);
extern void
tinyrl_vt100_cursor_forward(const tinyrl_vt100_t * instance, unsigned count);
extern void
tinyrl_vt100_cursor_up(const tinyrl_vt100_t * instance, unsigned count);
extern void
tinyrl_vt100_cursor_down(const tinyrl_vt100_t * instance, unsigned count);
extern void tinyrl_vt100_scroll_up(const tinyrl_vt100_t *instance);
extern void tinyrl_vt100_scroll_down(const tinyrl_vt100_t *instance);
extern void tinyrl_vt100_next_line(const tinyrl_vt100_t *instance);
extern void tinyrl_vt100_cursor_home(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_cursor_save(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_cursor_restore(const tinyrl_vt100_t * instance);
extern void tinyrl_vt100_erase(const tinyrl_vt100_t * instance, unsigned count);
extern void tinyrl_vt100_erase_down(const tinyrl_vt100_t * instance);
_END_C_DECL
#endif /* _tinyrl_vt100_h */
/** @} tinyrl_vt100 */
|
zzysjtu-klish
|
tinyrl/vt100.h
|
C
|
bsd
| 6,361
|
#include <termios.h>
#include "tinyrl/tinyrl.h"
#include "tinyrl/vt100.h"
/* define the class member data and virtual methods */
struct _tinyrl {
const char *line;
unsigned max_line_length;
char *prompt;
size_t prompt_size; /* strlen() */
size_t prompt_len; /* Symbol positions */
char *buffer;
size_t buffer_size;
bool_t done;
bool_t completion_over;
bool_t completion_error_over;
unsigned point;
unsigned end;
tinyrl_completion_func_t *attempted_completion_function;
tinyrl_timeout_fn_t *timeout_fn; /* timeout callback */
tinyrl_keypress_fn_t *keypress_fn; /* keypress callback */
int state;
#define RL_STATE_COMPLETING (0x00000001)
char *kill_string;
#define NUM_HANDLERS 256
tinyrl_key_func_t *handlers[NUM_HANDLERS];
tinyrl_history_t *history;
tinyrl_history_iterator_t hist_iter;
tinyrl_vt100_t *term;
void *context; /* context supplied by caller
* to tinyrl_readline()
*/
char echo_char;
bool_t echo_enabled;
struct termios default_termios;
bool_t isatty;
char *last_buffer; /* hold record of the previous
buffer for redisplay purposes */
unsigned int last_point; /* hold record of the previous
cursor position for redisplay purposes */
unsigned int last_width; /* Last terminal width. For resize */
bool_t utf8; /* Is the encoding UTF-8 */
};
|
zzysjtu-klish
|
tinyrl/private.h
|
C
|
bsd
| 1,305
|
/* tinyrl_history_entry.c */
#include "private.h"
#include "lub/string.h"
#include <stdlib.h>
struct _tinyrl_history_entry {
char *line;
unsigned index;
};
/*------------------------------------- */
static void
entry_init(tinyrl_history_entry_t * this, const char *line, unsigned index)
{
this->line = lub_string_dup(line);
this->index = index;
}
/*------------------------------------- */
static void entry_fini(tinyrl_history_entry_t * this)
{
lub_string_free(this->line);
this->line = NULL;
}
/*------------------------------------- */
tinyrl_history_entry_t *tinyrl_history_entry_new(const char *line,
unsigned index)
{
tinyrl_history_entry_t *this = malloc(sizeof(tinyrl_history_entry_t));
if (NULL != this) {
entry_init(this, line, index);
}
return this;
}
/*------------------------------------- */
void tinyrl_history_entry_delete(tinyrl_history_entry_t * this)
{
entry_fini(this);
free(this);
}
/*------------------------------------- */
const char *tinyrl_history_entry__get_line(const tinyrl_history_entry_t * this)
{
return this->line;
}
/*------------------------------------- */
unsigned tinyrl_history_entry__get_index(const tinyrl_history_entry_t * this)
{
return this->index;
}
/*------------------------------------- */
|
zzysjtu-klish
|
tinyrl/history/history_entry.c
|
C
|
bsd
| 1,268
|
/* private.h */
#include "tinyrl/history.h"
/**************************************
* protected interface to tinyrl_history_entry class
************************************** */
extern tinyrl_history_entry_t *tinyrl_history_entry_new(const char *line,
unsigned index);
extern void tinyrl_history_entry_delete(tinyrl_history_entry_t * instance);
|
zzysjtu-klish
|
tinyrl/history/private.h
|
C
|
bsd
| 355
|
/*
* history.c
*
* Simple non-readline hooks for the cli library
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <errno.h>
#include "private.h"
#include "lub/string.h"
#include "tinyrl/history.h"
struct _tinyrl_history {
tinyrl_history_entry_t **entries; /* pointer entries */
unsigned length; /* Number of elements within this array */
unsigned size; /* Number of slots allocated in this array */
unsigned current_index;
unsigned stifle;
};
/*------------------------------------- */
void tinyrl_history_init(tinyrl_history_t * this, unsigned stifle)
{
this->entries = NULL;
this->stifle = stifle;
this->current_index = 1;
this->length = 0;
this->size = 0;
}
/*------------------------------------- */
void tinyrl_history_fini(tinyrl_history_t * this)
{
tinyrl_history_entry_t *entry;
tinyrl_history_iterator_t iter;
/* release the resource associated with each entry */
for (entry = tinyrl_history_getfirst(this, &iter);
entry; entry = tinyrl_history_getnext(&iter)) {
tinyrl_history_entry_delete(entry);
}
/* release the list */
free(this->entries);
this->entries = NULL;
}
/*------------------------------------- */
tinyrl_history_t *tinyrl_history_new(unsigned stifle)
{
tinyrl_history_t *this = malloc(sizeof(tinyrl_history_t));
if (NULL != this) {
tinyrl_history_init(this, stifle);
}
return this;
}
/*------------------------------------- */
void tinyrl_history_delete(tinyrl_history_t * this)
{
tinyrl_history_fini(this);
free(this);
}
/*
HISTORY LIST MANAGEMENT
*/
/*------------------------------------- */
/* insert a new entry at the current offset */
static void insert_entry(tinyrl_history_t * this, const char *line)
{
tinyrl_history_entry_t *new_entry =
tinyrl_history_entry_new(line, this->current_index++);
assert(this->length);
assert(this->entries);
if (new_entry) {
this->entries[this->length - 1] = new_entry;
}
}
/*------------------------------------- */
/*
* This frees the specified entries from the
* entries vector. NB it doesn't perform any shuffling.
* This function is inclusive of start and end
*/
static void
free_entries(const tinyrl_history_t * this, unsigned start, unsigned end)
{
unsigned i;
assert(start <= end);
assert(end < this->length);
for (i = start; i <= end; i++) {
tinyrl_history_entry_t *entry = this->entries[i];
tinyrl_history_entry_delete(entry);
entry = NULL;
}
}
/*------------------------------------- */
/*
* This removes the specified entries from the
* entries vector. Shuffling up the array as necessary
* This function is inclusive of start and end
*/
static void
remove_entries(tinyrl_history_t * this, unsigned start, unsigned end)
{
unsigned delta = (end - start) + 1; /* number of entries being deleted */
/* number of entries to shuffle */
unsigned num_entries = (this->length - end) - 1;
assert(start <= end);
assert(end < this->length);
if (num_entries) {
/* move the remaining entries down to close the array */
memmove(&this->entries[start],
&this->entries[end + 1],
sizeof(tinyrl_history_entry_t *) * num_entries);
}
/* now fix up the length variables */
this->length -= delta;
}
/*------------------------------------- */
/*
Search the current history buffer for the specified
line and if found remove it.
*/
static bool_t remove_duplicate(tinyrl_history_t * this, const char *line)
{
bool_t result = BOOL_FALSE;
unsigned i;
for (i = 0; i < this->length; i++) {
tinyrl_history_entry_t *entry = this->entries[i];
if (0 == strcmp(line, tinyrl_history_entry__get_line(entry))) {
free_entries(this, i, i);
remove_entries(this, i, i);
result = BOOL_TRUE;
break;
}
}
return result;
}
/*------------------------------------- */
/*
add an entry to the end of the current array
if there is no space returns -1 else 0
*/
static void append_entry(tinyrl_history_t * this, const char *line)
{
if (this->length < this->size) {
this->length++;
insert_entry(this, line);
}
}
/*------------------------------------- */
/*
add a new history entry replacing the oldest one
*/
static void add_n_replace(tinyrl_history_t * this, const char *line)
{
if (BOOL_FALSE == remove_duplicate(this, line)) {
/* free the oldest entry */
free_entries(this, 0, 0);
/* shuffle the array */
remove_entries(this, 0, 0);
}
/* add the new entry */
append_entry(this, line);
}
/*------------------------------------- */
/* add a new history entry growing the array if necessary */
static void add_n_grow(tinyrl_history_t * this, const char *line)
{
if (this->size == this->length) {
/* increment the history memory by 10 entries each time we grow */
unsigned new_size = this->size + 10;
size_t nbytes;
tinyrl_history_entry_t **new_entries;
nbytes = sizeof(tinyrl_history_entry_t *) * new_size;
new_entries = realloc(this->entries, nbytes);
if (NULL != new_entries) {
this->size = new_size;
this->entries = new_entries;
}
}
(void)remove_duplicate(this, line);
append_entry(this, line);
}
/*------------------------------------- */
void tinyrl_history_add(tinyrl_history_t * this, const char *line)
{
if (this->length && (this->length == this->stifle)) {
add_n_replace(this, line);
} else {
add_n_grow(this, line);
}
}
/*------------------------------------- */
tinyrl_history_entry_t *tinyrl_history_remove(tinyrl_history_t * this,
unsigned offset)
{
tinyrl_history_entry_t *result = NULL;
if (offset < this->length) {
result = this->entries[offset];
/* do the biz */
remove_entries(this, offset, offset);
}
return result;
}
/*------------------------------------- */
void tinyrl_history_clear(tinyrl_history_t * this)
{
/* free all the entries */
free_entries(this, 0, this->length - 1);
/* and shuffle the array */
remove_entries(this, 0, this->length - 1);
}
/*------------------------------------- */
void tinyrl_history_stifle(tinyrl_history_t * this, unsigned stifle)
{
/*
* if we are stifling (i.e. non zero value) then
* delete the obsolete entries
*/
if (stifle) {
if (stifle < this->length) {
unsigned num_deletes = this->length - stifle;
/* free the entries */
free_entries(this, 0, num_deletes - 1);
/* shuffle the array shut */
remove_entries(this, 0, num_deletes - 1);
}
this->stifle = stifle;
}
}
/*------------------------------------- */
unsigned tinyrl_history_unstifle(tinyrl_history_t * this)
{
unsigned result = this->stifle;
this->stifle = 0;
return result;
}
/*------------------------------------- */
bool_t tinyrl_history_is_stifled(const tinyrl_history_t * this)
{
return this->stifle ? BOOL_TRUE : BOOL_FALSE;
}
/*
INFORMATION ABOUT THE HISTORY LIST
*/
tinyrl_history_entry_t *tinyrl_history_get(const tinyrl_history_t * this,
unsigned position)
{
unsigned i;
tinyrl_history_entry_t *entry = NULL;
for (i = 0; i < this->length; i++) {
entry = this->entries[i];
if (position == tinyrl_history_entry__get_index(entry)) {
/* found it */
break;
}
entry = NULL;
}
return entry;
}
/*------------------------------------- */
tinyrl_history_expand_t
tinyrl_history_expand(const tinyrl_history_t * this,
const char *string, char **output)
{
tinyrl_history_expand_t result = tinyrl_history_NO_EXPANSION; /* no expansion */
const char *p, *start;
char *buffer = NULL;
unsigned len;
for (p = string, start = string, len = 0; *p; p++, len++) {
/* perform pling substitution */
if (*p == '!') {
/* assume the last command to start with... */
unsigned offset = this->current_index - 1;
unsigned skip;
tinyrl_history_entry_t *entry;
/* this could be an escape sequence */
if (p[1] != '!') {
int tmp;
int res;
/* read the numeric identifier */
res = sscanf(p, "!%d", &tmp);
if ((0 == res) || (EOF == res)) {
/* error so ignore it */
break;
}
if (tmp < 0) {
/* this is a relative reference */
/*lint -e737 Loss of sign in promotion from int to unsigend int */
offset += tmp; /* adding a negative substracts... */
/*lint +e737 */
} else {
/* this is an absolute reference */
offset = (unsigned)tmp;
}
}
if (len > 0) {
/* we need to add in some previous plain text */
lub_string_catn(&buffer, start, len);
}
/* skip the escaped chars */
p += skip = strspn(p, "!-0123456789");
/* try and find the history entry */
entry = tinyrl_history_get(this, offset);
if (NULL != entry) {
/* reset the non-escaped references */
start = p;
len = 0;
/* add the expanded text to the buffer */
result = tinyrl_history_EXPANDED;
lub_string_cat(&buffer,
tinyrl_history_entry__get_line
(entry));
} else {
/* we simply leave the unexpanded sequence */
len += skip;
}
}
}
/* add any left over plain text */
lub_string_catn(&buffer, start, len);
*output = buffer;
return result;
}
/*-------------------------------------*/
tinyrl_history_entry_t *tinyrl_history_getfirst(const tinyrl_history_t * this,
tinyrl_history_iterator_t *
iter)
{
tinyrl_history_entry_t *result = NULL;
iter->history = this;
iter->offset = 0;
if (this->length) {
result = this->entries[iter->offset];
}
return result;
}
/*-------------------------------------*/
tinyrl_history_entry_t *tinyrl_history_getnext(tinyrl_history_iterator_t * iter)
{
tinyrl_history_entry_t *result = NULL;
if (iter->offset < iter->history->length - 1) {
iter->offset++;
result = iter->history->entries[iter->offset];
}
return result;
}
/*-------------------------------------*/
tinyrl_history_entry_t *tinyrl_history_getlast(const tinyrl_history_t * this,
tinyrl_history_iterator_t * iter)
{
iter->history = this;
iter->offset = this->length;
return tinyrl_history_getprevious(iter);
}
/*-------------------------------------*/
tinyrl_history_entry_t *tinyrl_history_getprevious(tinyrl_history_iterator_t *
iter)
{
tinyrl_history_entry_t *result = NULL;
if (iter->offset) {
iter->offset--;
result = iter->history->entries[iter->offset];
}
return result;
}
/*-------------------------------------*/
/* Save command history to specified file */
int tinyrl_history_save(const tinyrl_history_t *this, const char *fname)
{
tinyrl_history_entry_t *entry;
tinyrl_history_iterator_t iter;
FILE *f;
if (!fname) {
errno = EINVAL;
return -1;
}
if (!(f = fopen(fname, "w")))
return -1;
for (entry = tinyrl_history_getfirst(this, &iter);
entry; entry = tinyrl_history_getnext(&iter)) {
if (fprintf(f, "%s\n", tinyrl_history_entry__get_line(entry)) < 0)
return -1;
}
fclose(f);
return 0;
}
/*-------------------------------------*/
/* Restore command history from specified file */
int tinyrl_history_restore(tinyrl_history_t *this, const char *fname)
{
FILE *f;
char *p;
int part_len = 300;
char *buf;
int buf_len = part_len;
int res = 0;
if (!fname) {
errno = EINVAL;
return -1;
}
if (!(f = fopen(fname, "r")))
return 0; /* Can't find history file */
buf = malloc(buf_len);
p = buf;
while (fgets(p, buf_len - (p - buf), f)) {
char *ptmp = NULL;
char *el = strchr(buf, '\n');
if (el) { /* The whole line was readed */
*el = '\0';
tinyrl_history_add(this, buf);
p = buf;
continue;
}
buf_len += part_len;
ptmp = realloc(buf, buf_len);
if (!ptmp) {
res = -1;
goto end;
}
buf = ptmp;
p = buf + buf_len - part_len - 1;
}
end:
free(buf);
fclose(f);
return res;
}
/*-------------------------------------*/
|
zzysjtu-klish
|
tinyrl/history/history.c
|
C
|
bsd
| 11,573
|
/**
\ingroup tinyrl
\defgroup tinyrl_history history
@{
\brief This class handles the maintenance of a historical list of command lines.
*/
#ifndef _tinyrl_history_h
#define _tinyrl_history_h
#include "lub/c_decl.h"
#include "lub/types.h"
_BEGIN_C_DECL
/**************************************
* tinyrl_history_entry class interface
************************************** */
typedef struct _tinyrl_history_entry tinyrl_history_entry_t;
extern const char *tinyrl_history_entry__get_line(const tinyrl_history_entry_t *
instance);
extern unsigned tinyrl_history_entry__get_index(const tinyrl_history_entry_t *
instance);
/**************************************
* tinyrl_history class interface
************************************** */
typedef struct _tinyrl_history tinyrl_history_t;
/**
* This type is used for the iteration of history entries
*/
typedef struct _tinyrl_history_iterator tinyrl_history_iterator_t;
/**
* CLIENTS MUST NOT USE THESE FIELDS DIRECTLY
*/
struct _tinyrl_history_iterator {
const tinyrl_history_t *history;
unsigned offset;
};
extern tinyrl_history_t *tinyrl_history_new(unsigned stifle);
extern void tinyrl_history_delete(tinyrl_history_t * instance);
extern void tinyrl_history_add(tinyrl_history_t * instance, const char *line);
extern tinyrl_history_entry_t *tinyrl_history_getfirst(const tinyrl_history_t *
instance,
tinyrl_history_iterator_t
* iter);
extern tinyrl_history_entry_t *tinyrl_history_getlast(const tinyrl_history_t *
instance,
tinyrl_history_iterator_t
* iter);
extern tinyrl_history_entry_t *tinyrl_history_getnext(tinyrl_history_iterator_t
* iter);
extern tinyrl_history_entry_t
*tinyrl_history_getprevious(tinyrl_history_iterator_t * iter);
/*
HISTORY LIST MANAGEMENT
*/
extern tinyrl_history_entry_t *tinyrl_history_remove(tinyrl_history_t *
instance, unsigned offset);
extern void tinyrl_history_clear(tinyrl_history_t * instance);
extern void tinyrl_history_stifle(tinyrl_history_t * instance, unsigned stifle);
extern unsigned tinyrl_history_unstifle(tinyrl_history_t * instance);
extern bool_t tinyrl_history_is_stifled(const tinyrl_history_t * instance);
extern int tinyrl_history_save(const tinyrl_history_t *instance, const char *fname);
extern int tinyrl_history_restore(tinyrl_history_t *instance, const char *fname);
/*
INFORMATION ABOUT THE HISTORY LIST
*/
extern tinyrl_history_entry_t **tinyrl_history_list(const tinyrl_history_t *
instance);
extern tinyrl_history_entry_t *tinyrl_history_get(const tinyrl_history_t *
instance, unsigned offset);
/*
* HISTORY EXPANSION
*/
typedef enum {
tinyrl_history_NO_EXPANSION,
tinyrl_history_EXPANDED
} tinyrl_history_expand_t;
extern tinyrl_history_expand_t
tinyrl_history_expand(const tinyrl_history_t * instance,
const char *string, char **output);
_END_C_DECL
#endif /* _tinyrl_history_h */
/** @} tinyrl_history */
|
zzysjtu-klish
|
tinyrl/history.h
|
C
|
bsd
| 3,017
|
## Process this file with automake to generate Makefile.in
AUTOMAKE_OPTIONS = foreign nostdinc
ACLOCAL_AMFLAGS = -I m4
AM_CPPFLAGS = -I. -I$(top_srcdir)
AM_LD = $(CC)
if DEBUG
DEBUG_CFLAGS = -DDEBUG
endif
AM_CFLAGS = -pedantic -Wall $(DEBUG_CFLAGS)
#AM_CFLAGS = -ansi -pedantic -Werror -Wall -D_POSIX_C_SOURCE=199309 -DVERSION=$(VERSION) $(DEBUG_CFLAGS)
bin_PROGRAMS =
lib_LTLIBRARIES =
lib_LIBRARIES =
nobase_include_HEADERS =
EXTRA_DIST = \
bin/module.am \
clish/module.am \
lub/module.am \
tinyrl/module.am \
konf/module.am \
contrib \
xml-examples \
clish.xsd \
LICENCE \
README \
CHANGES \
ISSUES
include $(top_srcdir)/lub/module.am
include $(top_srcdir)/tinyrl/module.am
include $(top_srcdir)/konf/module.am
include $(top_srcdir)/clish/module.am
include $(top_srcdir)/bin/module.am
|
zzysjtu-klish
|
Makefile.am
|
Makefile
|
bsd
| 808
|
/*
* dump.c
* Provides indented printf functionality
*/
#include "private.h"
#include <stdio.h>
#include <stdarg.h>
static int indent = 0;
/*--------------------------------------------------------- */
int lub_dump_printf(const char *fmt, ...)
{
va_list args;
int len;
va_start(args, fmt);
fprintf(stderr, "%*s", indent, "");
len = vfprintf(stderr, fmt, args);
va_end(args);
return len;
}
/*--------------------------------------------------------- */
static void lub_dump_divider(char c)
{
int i;
lub_dump_printf("");
for (i = 0; i < (80 - indent); i++) {
fputc(c, stderr);
}
fputc('\n', stderr);
}
/*--------------------------------------------------------- */
void lub_dump_indent(void)
{
indent += 2;
lub_dump_divider('_');
}
/*--------------------------------------------------------- */
void lub_dump_undent(void)
{
lub_dump_divider('^');
indent -= 2;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/dump/dump.c
|
C
|
bsd
| 955
|
/*
* private.h
*/
#include "lub/dump.h"
|
zzysjtu-klish
|
lub/dump/private.h
|
C
|
bsd
| 42
|
/*
* argv_new.c
*/
#include "private.h"
#include "lub/string.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
/*--------------------------------------------------------- */
static void lub_argv_init(lub_argv_t * this, const char *line, size_t offset)
{
size_t len;
const char *word;
lub_arg_t *arg;
size_t quoted;
this->argv = NULL;
this->argc = 0;
if (!line)
return;
/* first of all count the words in the line */
this->argc = lub_argv_wordcount(line);
if (0 == this->argc)
return;
/* allocate space to hold the vector */
arg = this->argv = malloc(sizeof(lub_arg_t) * this->argc);
assert(arg);
/* then fill out the array with the words */
for (word = lub_argv_nextword(line, &len, &offset, "ed);
*word || quoted;
word = lub_argv_nextword(word + len, &len, &offset, "ed)) {
(*arg).arg = lub_string_ndecode(word, len);
(*arg).offset = offset;
(*arg).quoted = quoted ? BOOL_TRUE : BOOL_FALSE;
offset += len;
if (quoted) {
len += quoted - 1; /* account for terminating quotation mark */
offset += quoted; /* account for quotation marks */
}
arg++;
}
}
/*--------------------------------------------------------- */
lub_argv_t *lub_argv_new(const char *line, size_t offset)
{
lub_argv_t *this;
this = malloc(sizeof(lub_argv_t));
if (this)
lub_argv_init(this, line, offset);
return this;
}
/*--------------------------------------------------------- */
void lub_argv_add(lub_argv_t * this, const char *text)
{
lub_arg_t * arg;
if (!text)
return;
/* allocate space to hold the vector */
arg = realloc(this->argv, sizeof(lub_arg_t) * (this->argc + 1));
assert(arg);
this->argv = arg;
(this->argv[this->argc++]).arg = strdup(text);
}
/*--------------------------------------------------------- */
static void lub_argv_fini(lub_argv_t * this)
{
unsigned i;
for (i = 0; i < this->argc; i++)
free(this->argv[i].arg);
free(this->argv);
this->argv = NULL;
}
/*--------------------------------------------------------- */
void lub_argv_delete(lub_argv_t * this)
{
lub_argv_fini(this);
free(this);
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/argv/argv_new.c
|
C
|
bsd
| 2,155
|
/*
* argv__get_arg.c
*/
#include "private.h"
/*--------------------------------------------------------- */
const char *lub_argv__get_arg(const lub_argv_t * this, unsigned index)
{
const char *result = NULL;
if (this->argc > index)
result = this->argv[index].arg;
return result;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/argv/argv__get_arg.c
|
C
|
bsd
| 355
|
/*
* argv_nextword.c
*/
#include <stddef.h>
#include <ctype.h>
#include "private.h"
#include "lub/types.h"
/*--------------------------------------------------------- */
const char *lub_argv_nextword(const char *string,
size_t * len, size_t * offset, size_t * quoted)
{
const char *word;
*quoted = 0;
/* find the start of a word (not including an opening quote) */
while (*string && isspace(*string)) {
string++;
(*offset)++;
}
if (*string == '\\') {
string++;
if (*string)
string++;
}
/* is this the start of a quoted string ? */
if (*string == '"') {
*quoted = 1;
string++;
}
word = string;
*len = 0;
/* find the end of the word */
while (*string) {
if (*string == '\\') {
string++;
(*len)++;
if (*string) {
(*len)++;
string++;
}
continue;
}
/* end of word */
if (!*quoted && isspace(*string))
break;
if (*string == '"') {
/* end of a quoted string */
*quoted = 2;
break;
}
(*len)++;
string++;
}
return word;
}
/*--------------------------------------------------------- */
unsigned lub_argv_wordcount(const char *line)
{
const char *word;
unsigned result = 0;
size_t len = 0, offset = 0;
size_t quoted;
for (word = lub_argv_nextword(line, &len, &offset, "ed);
*word || quoted;
word = lub_argv_nextword(word + len, &len, &offset, "ed)) {
/* account for the terminating quotation mark */
len += quoted ? quoted - 1 : 0;
result++;
}
return result;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/argv/argv_nextword.c
|
C
|
bsd
| 1,533
|
/*
* private.h
*
* Class to deal with splitting a command line into multiple arguments.
* This class deals with full quoted text "like this" as a single argument.
*/
#include "lub/argv.h"
typedef struct lub_arg_s lub_arg_t;
struct lub_arg_s {
char *arg;
size_t offset;
bool_t quoted;
};
struct lub_argv_s {
unsigned argc;
lub_arg_t *argv;
};
/*-------------------------------------
* PRIVATE META FUNCTIONS
*------------------------------------- */
const char *lub_argv_nextword(const char *string,
size_t * len, size_t * offset, size_t * quoted);
|
zzysjtu-klish
|
lub/argv/private.h
|
C
|
bsd
| 563
|
/*
* argv__get_argv.c
*/
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "lub/string.h"
#include "private.h"
/*--------------------------------------------------------- */
char *lub_argv__get_line(const lub_argv_t * this)
{
int space = 0;
const char *p;
unsigned i;
char *line = NULL;
for (i = 0; i < this->argc; i++) {
if (i != 0)
lub_string_cat(&line, " ");
space = 0;
/* Search for spaces */
for (p = this->argv[i].arg; *p; p++) {
if (isspace(*p)) {
space = 1;
break;
}
}
if (space)
lub_string_cat(&line, "\"");
lub_string_cat(&line, this->argv[i].arg);
if (space)
lub_string_cat(&line, "\"");
}
return line;
}
/*--------------------------------------------------------- */
char **lub_argv__get_argv(const lub_argv_t * this, const char *argv0)
{
char **result = NULL;
unsigned i;
unsigned a = 0;
if (argv0)
a = 1;
result = malloc(sizeof(char *) * (this->argc + 1 + a));
if (argv0)
result[0] = strdup(argv0);
for (i = 0; i < this->argc; i++)
result[i + a] = strdup(this->argv[i].arg);
result[i + a] = NULL;
return result;
}
/*--------------------------------------------------------- */
void lub_argv__free_argv(char **argv)
{
unsigned i;
if (!argv)
return;
for (i = 0; argv[i]; i++)
free(argv[i]);
free(argv);
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/argv/argv__get_argv.c
|
C
|
bsd
| 1,383
|
/*
* argv__get_count.c
*/
#include "private.h"
/*--------------------------------------------------------- */
unsigned lub_argv__get_count(const lub_argv_t * this)
{
return this->argc;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/argv/argv__get_count.c
|
C
|
bsd
| 254
|
/*
* argv__get_offset.c
*/
#include "private.h"
/*--------------------------------------------------------- */
size_t lub_argv__get_offset(const lub_argv_t * this, unsigned index)
{
size_t result = 0;
if (this->argc > index)
result = this->argv[index].offset;
return result;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/argv/argv__get_offset.c
|
C
|
bsd
| 351
|
/*
* argv__get_quoted.c
*/
#include "private.h"
/*--------------------------------------------------------- */
bool_t lub_argv__get_quoted(const lub_argv_t * this, unsigned index)
{
bool_t result = BOOL_FALSE;
if (this->argc > index)
result = this->argv[index].quoted;
return result;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/argv/argv__get_quoted.c
|
C
|
bsd
| 360
|
/**
\ingroup lub
\defgroup lub_bintree bintree
@{
\brief This interface provides a facility which enables a client to
order and access a set of arbitary data in a binary "tree"
Each "tree" is defined by a number of "clientnodes" which are
ordered according to a client defined "key".
A "clientkey" is a client specific entity which can be compared
with a "clientnode" to determine which is the "greatest". In order
to do this the client needs provide a comparison function for
comparing a "clientnode" with a "clientkey", and a function to
convert a "clientnode" into a "clientkey".
The client is responsible for providing each "clientnode" in a
tree. This will typically contain some client specific data, but
will also need to contain a bintree "node" which is used to
structurally relate each node to one another in the tree. A
specific "node" may only belong to one tree at a time, but an
individual "clientnode" may contain multiple of these if necessary.
\par Implementation
The implementation of this interface uses a top-down splaying algorithm.
\par
"Splay trees", or "self-adjusting search trees" are a simple and
efficient data structure for storing an ordered set. The data
structure consists of a binary tree, without parent pointers, and
no additional fields. It allows searching, insertion, deletion,
deletemin, deletemax, splitting, joining, and many other
operations, all with amortized logarithmic performance. Since the
trees adapt to the sequence of requests, their performance on real
access patterns is typically even better. Splay trees are
described in a number of texts and papers [1,2,3,4,5].
\par
The code here is adapted from simple top-down splay, at the bottom
of page 669 of [3]. It can be obtained via anonymous ftp from
spade.pc.cs.cmu.edu in directory /usr/sleator/public.
\par
The chief modification here is that the splay operation works even
if the item being splayed is not in the tree, and even if the tree
root of the tree is NULL. So the line:
\par
t = splay(i, t);
\par
causes it to search for item with key i in the tree rooted at t.
If it's there, it is splayed to the root. If it isn't there,
then the node put at the root is the last one before NULL that
would have been reached in a normal binary search for i. (It's a
neighbor of i in the tree.) This allows many other operations to
be easily implemented.
\par
[1] "Fundamentals of data structures in C", Horowitz, Sahni,
and Anderson-Freed, Computer Science Press, pp 542-547.
\par
[2] "Data Structures and Their Algorithms", Lewis and Denenberg,
Harper Collins, 1991, pp 243-251.
\par
[3] "Self-adjusting Binary Search Trees" Sleator and Tarjan,
JACM Volume 32, No 3, July 1985, pp 652-686.
\par
[4] "Data Structure and Algorithm Analysis", Mark Weiss,
Benjamin Cummins, 1992, pp 119-130.
\par
[5] "Data Structures, Algorithms, and Performance", Derick Wood,
Addison-Wesley, 1993, pp 367-375.
\par
The splay function is based on one written by Daniel Sleator, which is released
in the public domain.
\author Graeme McKerrell
\date Created On : Fri Jan 23 12:50:18 2004
\version TESTED
*/
/*---------------------------------------------------------------
HISTORY
7-Dec-2004 Graeme McKerrell
Updated to use the "lub" prefix
27-Feb-2004 Graeme McKerrell
updated to simplify node initialisation
9-Feb-2004 Graeme McKerrell
updated to make the comparision function compare a "clientnode" and
"key"
Updated getkey() function to fill out a provides "key" from a "clientnode"
23-Jan-2004 Graeme McKerrell
Initial version
--------------------------------------------------------------
Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#ifndef _lub_bintree_h
#define _lub_bintree_h
#include <stddef.h>
/****************************************************************
* TYPE DEFINITIONS
**************************************************************** */
/**
* This type represents a bintree "node".
* Typically the client will have a "clientnode" structure which
* contains it's data. A bintree "node" is made one of the data
* elements of that structure. When the tree is initialised the
* client provides the offset into the structure of the
* "node" which is to be used for that tree.
*/
typedef struct lub_bintree_node_s lub_bintree_node_t;
/**
* CLIENTS MUSTN'T TOUCH THE CONTENTS OF THIS STRUCTURE
*/
struct lub_bintree_node_s {
/** internal */ lub_bintree_node_t *left;
/** internal */ lub_bintree_node_t *right;
};
/**
* This type defines a callback function which will compare two "keys"
* with each other
*
* \param clientnode the client node to compare
* \param clientkey the key to compare with a node
*
* \return
* <0 if clientnode < clientkey;
* 0 if clientnode == clientkey;
* >0 if clientnode > clientkey
*/
typedef int
lub_bintree_compare_fn(const void *clientnode, const void *clientkey);
/**
* This is used to size the key storage area for an opaque key.
* If any client requires a greater storage size then this will need to
* be increased.
*/
#define lub_bintree_MAX_KEY_STORAGE (200)
/**
* This is used to declare an opaque key structure
* Typically a client would declare their own non-opaque structure
* which they would fill out appropriately
*/
typedef struct lub_bintree_key_s lub_bintree_key_t;
/**
* CLIENTS MUSTN'T TOUCH THE CONTENTS OF THIS STRUCTURE
*/
struct lub_bintree_key_s {
/** internal */ char storage[lub_bintree_MAX_KEY_STORAGE];
/** internal */ int magic;
};
/**
* This type defines a callback function which will convert a client's "node"
* into a search "key"
*
* \param clientnode the node from which to derive a key
* \param key a reference to the key to fill out
*
* \return
* A "key" which corresponds the "node" in this view
*/
typedef void
lub_bintree_getkey_fn(const void *clientnode, lub_bintree_key_t * key);
/**
* This type represents an binary tree instance
*/
typedef struct lub_bintree_s lub_bintree_t;
/**
* CLIENTS MUSTN'T TOUCH THE CONTENTS OF THIS STRUCTURE
*/
struct lub_bintree_s {
/** internal */ lub_bintree_node_t *root;
/** internal */ size_t node_offset;
/** internal */ lub_bintree_compare_fn *compareFn;
/** internal */ lub_bintree_getkey_fn *getkeyFn;
};
/**
* This is used to perform iterations of a tree
*/
typedef struct lub_bintree_iterator_s lub_bintree_iterator_t;
/**
* CLIENTS MUSTN'T TOUCH THE CONTENTS OF THIS STRUCTURE
*/
struct lub_bintree_iterator_s {
/** internal */ lub_bintree_t *tree;
/** internal */ lub_bintree_key_t key;
};
/****************************************************************
* BINTREE OPERATIONS
**************************************************************** */
/**
* This operation initialises an instance of a binary tree.
*
* \pre none
*
* \post The tree is ready to have client nodes inserted.
*/
extern void lub_bintree_init(
/**
* the "tree" instance to initialise
*/
lub_bintree_t * tree,
/**
* the offset of the bintree "node" structure within the
* "clientnode" structure. This is typically passed
* using the offsetof() macro.
*/
size_t node_offset,
/**
* a comparison function for comparing a "clientnode"
* with a "clientkey"
*/
lub_bintree_compare_fn compareFn,
/**
* a function which will fill out a "key" from a clientnode
*/
lub_bintree_getkey_fn getkeyFn);
/**
* This operation is called to initialise a "clientnode" ready for
* insertion into a tree. This is only required once after the memory
* for a node has been allocated.
*
* \pre none
*
* \post The node is ready to be inserted into a tree.
*/
extern void lub_bintree_node_init(
/**
* the bintree node to initialise
*/
lub_bintree_node_t * node);
/*****************************************
* NODE MANIPULATION OPERATIONS
***************************************** */
/**
* This operation adds a client node to the specified tree.
*
* \pre The tree must be initialised
* \pre The clientnode must be initialised
*
* \return
* 0 if the "clientnode" is added correctly to the tree.
* If another "clientnode" already exists in the tree with the same key, then
* -1 is returned, and the tree remains unchanged.
*
* \post If the bintree "node" is already part of a tree, then an
* assert will fire.
*/
extern int lub_bintree_insert(
/**
* the "tree" instance to invoke this operation upon
*/
lub_bintree_t * tree,
/**
* a pointer to a client node. NB the tree can find the
* necessary lub_BintreeNodeT from it's stored offset.
*/
void *clientnode);
/**
* This operation removes a "clientnode" from the specified "tree"
*
* \pre The tree must be initialised
* \pre The clientnode must be initialised
*
* \post The "clientnode" will no longer be part of the specified tree, and will be
* made available for re-insertion
* \post If the clientnode is not present in the specified tree, then an
* assert will fire.
*/
extern void lub_bintree_remove(
/**
* the "tree" instance to invoke this operation upon
*/
lub_bintree_t * tree,
/**
* the node to remove
*/
void *clientnode);
/*****************************************
* NODE RETRIEVAL OPERATIONS
***************************************** */
/**
* This operation returns the first "clientnode" present in the specified "tree"
*
* \pre The tree must be initialised
*
* \return
* "clientnode" instance or NULL if no nodes are present in this tree.
*/
extern void *lub_bintree_findfirst(
/**
* the "tree" instance to invoke this operation upon
*/
lub_bintree_t * tree);
/**
* This operation returns the last "clientnode" present in the specified "tree"
*
* \pre The tree must be initialised
*
* \return
* "clientnode" instance or NULL if no nodes are present in this tree.
*/
extern void *lub_bintree_findlast(
/**
* the "tree" instance to invoke this operation upon
*/
lub_bintree_t * tree);
/**
* This operation searches the specified "tree" for a "clientnode" which matches the
* specified "key"
*
* \pre The tree must be initialised
*
* \return
* "clientnode" instance or NULL if no node is found.
*/
extern void *lub_bintree_find(
/**
* the "tree" instance to invoke this operation upon
*/
lub_bintree_t * tree,
/**
* the "key" to search with
*/
const void *key);
/**
* This operation searches the specified "tree" for a "clientnode" which is
* the one which logically follows the specified "key"
*
* A "clientnode" with the specified "key" doesn't need to be in the tree.
*
* \pre The tree must be initialised
*
* \return
* "clientnode" instance or NULL if no node is found.
*/
extern void *lub_bintree_findnext(
/**
* the "tree" instance to invoke this operation upon
*/
lub_bintree_t * tree,
/**
* the "key" to search with
*/
const void *key);
/**
* This operation searches the specified "tree" for a "clientnode" which is
* the one which logically preceeds the specified "key"
*
* A "clientnode" with the specified "key" doesn't need to be in the tree.
*
* \pre The tree must be initialised
*
* \return
* "clientnode" instance or NULL if no node is found.
*/
extern void *lub_bintree_findprevious(
/**
* the "tree" instance to invoke this operation upon
*/
lub_bintree_t * tree,
/**
* the "key" to search with
*/
const void *key);
/*****************************************
* ITERATION OPERATIONS
***************************************** */
/**
* This operation initialises an iterator. This can then be
* subsequently used for iterating through a tree. This will work
* even if the "clientnode" which defined the current iterator has been
* removed before the next iterator operation.
*
* \pre The tree must be initialised
* \pre The clientnode must be initialised and valid at the time of this call
*
* \post The interator instance will be updated to reference the position in the tree for the clientnode.
*/
extern void lub_bintree_iterator_init(
/**
* the iterator instance to initialise
*/
lub_bintree_iterator_t * iter,
/**
* the tree to associate with this iterator
*/
lub_bintree_t * tree,
/**
* the starting point for the iteration
*/
const void *clientnode);
/**
* This operation returns the next "clientnode" in an iteration.
*
* \pre The interator instance must have been initialised
*
* \return
* "clientnode" instance or NULL if the iteration has reached the end of the
* tree.
*
* \post The interator instance will be updated to reference the position in the tree for the returned value.
*/
extern void *lub_bintree_iterator_next(
/**
* the iterator instance to invoke this operation upon.
*/
lub_bintree_iterator_t * iter);
/**
* This operation returns the previous "clientnode" in an iteration.
*
* \pre The interator instance must have been initialised
*
* \return
* "clientnode" instance or NULL if the iteration has reached the beginning
* of the tree.
*
* \post The interator instance will be updated to reference the position in the tree for the returned value.
*/
extern void *lub_bintree_iterator_previous(
/**
* the iterator instance to invoke this operation upon.
*/
lub_bintree_iterator_t *
iter);
/**
* This operation dumps the node list of the specified tree to stdout
*
* \pre The tree must be initialised
*
* \post The structure of the tree will be unaltered.
*/
extern void lub_bintree_dump(
/**
* the "tree" instance to invoke this operation upon
*/
lub_bintree_t * tree);
#endif /* _lub_bintree_h */
/** @} */
|
zzysjtu-klish
|
lub/bintree.h
|
C
|
bsd
| 13,947
|
/* It must be here to include config.h before another headers */
#include "lub/db.h"
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include <unistd.h>
struct passwd *lub_db_getpwnam(const char *name)
{
size_t size;
char *buf;
struct passwd *pwbuf;
struct passwd *pw = NULL;
int res = 0;
#ifdef _SC_GETPW_R_SIZE_MAX
size = sysconf(_SC_GETPW_R_SIZE_MAX);
#else
size = 1024;
#endif
pwbuf = malloc(sizeof(*pwbuf) + size);
if (!pwbuf)
return NULL;
buf = (char *)pwbuf + sizeof(*pwbuf);
res = getpwnam_r(name, pwbuf, buf, size, &pw);
if (res || !pw) {
free(pwbuf);
if (res != 0)
errno = res;
else
errno = ENOENT;
return NULL;
}
return pw;
}
struct passwd *lub_db_getpwuid(uid_t uid)
{
size_t size;
char *buf;
struct passwd *pwbuf;
struct passwd *pw = NULL;
int res = 0;
#ifdef _SC_GETPW_R_SIZE_MAX
size = sysconf(_SC_GETPW_R_SIZE_MAX);
#else
size = 1024;
#endif
pwbuf = malloc(sizeof(*pwbuf) + size);
if (!pwbuf)
return NULL;
buf = (char *)pwbuf + sizeof(*pwbuf);
res = getpwuid_r(uid, pwbuf, buf, size, &pw);
if (NULL == pw) {
free(pwbuf);
if (res != 0)
errno = res;
else
errno = ENOENT;
return NULL;
}
return pw;
}
struct group *lub_db_getgrnam(const char *name)
{
size_t size;
char *buf;
struct group *grbuf;
struct group *gr = NULL;
int res = 0;
#ifdef _SC_GETGR_R_SIZE_MAX
size = sysconf(_SC_GETGR_R_SIZE_MAX);
#else
size = 1024;
#endif
grbuf = malloc(sizeof(*grbuf) + size);
if (!grbuf)
return NULL;
buf = (char *)grbuf + sizeof(*grbuf);
res = getgrnam_r(name, grbuf, buf, size, &gr);
if (NULL == gr) {
free(grbuf);
if (res != 0)
errno = res;
else
errno = ENOENT;
return NULL;
}
return gr;
}
struct group *lub_db_getgrgid(gid_t gid)
{
size_t size;
char *buf;
struct group *grbuf;
struct group *gr = NULL;
int res = 0;
#ifdef _SC_GETGR_R_SIZE_MAX
size = sysconf(_SC_GETGR_R_SIZE_MAX);
#else
size = 1024;
#endif
grbuf = malloc(sizeof(struct group) + size);
if (!grbuf)
return NULL;
buf = (char *)grbuf + sizeof(struct group);
res = getgrgid_r(gid, grbuf, buf, size, &gr);
if (!gr) {
free(grbuf);
if (res != 0)
errno = res;
else
errno = ENOENT;
return NULL;
}
return gr;
}
|
zzysjtu-klish
|
lub/db/db.c
|
C
|
bsd
| 2,266
|
#ifndef _lub_list_h
#define _lub_list_h
#include <stddef.h>
#include "lub/c_decl.h"
/****************************************************************
* TYPE DEFINITIONS
**************************************************************** */
typedef struct lub_list_node_s lub_list_node_t;
/**
* This type defines a callback function which will compare two nodes
* with each other
*
* \param clientnode the client node to compare
* \param clientkey the key to compare with a node
*
* \return
* <0 if clientnode < clientkey;
* 0 if clientnode == clientkey;
* >0 if clientnode > clientkey
*/
typedef int lub_list_compare_fn(const void *first, const void *second);
/**
* This type represents a list instance
*/
typedef struct lub_list_s lub_list_t;
/**
* This is used to perform iterations of a list
*/
typedef struct lub_list_node_s lub_list_iterator_t;
_BEGIN_C_DECL
/****************************************************************
* LIST OPERATIONS
**************************************************************** */
/**
* This operation initialises an instance of a list.
*/
lub_list_t *lub_list_new(lub_list_compare_fn compareFn);
lub_list_node_t *lub_list_node_new(void *data);
void lub_list_free(lub_list_t *list);
void lub_list_node_free(lub_list_node_t *node);
lub_list_node_t *lub_list__get_head(lub_list_t *list);
lub_list_node_t *lub_list__get_tail(lub_list_t *list);
lub_list_node_t *lub_list_node__get_prev(lub_list_node_t *node);
lub_list_node_t *lub_list_node__get_next(lub_list_node_t *node);
void *lub_list_node__get_data(lub_list_node_t *node);
lub_list_node_t *lub_list_iterator_init(lub_list_t *list);
lub_list_node_t *lub_list_iterator_next(lub_list_node_t *node);
lub_list_node_t *lub_list_iterator_prev(lub_list_node_t *node);
lub_list_node_t *lub_list_add(lub_list_t *list, void *data);
void lub_list_del(lub_list_t *list, lub_list_node_t *node);
void lub_list_node_copy(lub_list_node_t *dst, lub_list_node_t *src);
_END_C_DECL
#endif /* _lub_list_h */
|
zzysjtu-klish
|
lub/list.h
|
C
|
bsd
| 2,021
|
/*
* string.h
*/
/**
\ingroup lub
\defgroup lub_string string
@{
\brief This utility provides some simple string manipulation functions which
augment those found in the standard ANSI-C library.
As a rule of thumb if a function returns "char *" then the calling client becomes responsible for invoking
lub_string_free() to release the dynamically allocated memory.
If a "const char *" is returned then the client has no responsiblity for releasing memory.
*/
/*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Updated to use the "lub" prefix
* 6-Feb-2004 Graeme McKerrell
* removed init_fn type definition and parameter, the client had
* more flexiblity in defining their own initialisation operation with
* arguments rather than use a "one-size-fits-all" approach.
* Modified blockpool structure to support FIFO block allocation.
* 23-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
*--------------------------------------------------------------- */
#ifndef _lub_string_h
#define _lub_string_h
#include <stddef.h>
#include "lub/c_decl.h"
#include "lub/types.h"
#define UTF8_MASK 0xC0
#define UTF8_11 0xC0 /* First UTF8 byte */
#define UTF8_10 0x80 /* Next UTF8 bytes */
_BEGIN_C_DECL
/**
* This operation duplicates the specified string.
*
* \pre
* - none
*
* \return
* A dynamically allocated string containing the same content as that specified.
*
* \post
* - The client is responsible for calling lub_string_free() with the
* returned string when they are finished using it.
*/
char *lub_string_dup(
/**
* The string to duplicate
*/
const char *string);
/**
* This operation concatinates the specified text onto an existing string.
*
* \pre
* - 'string_ptr' must contain reference to NULL or to a dynamically
* allocated string.
*
* \post
* - The old string referenced by 'string_ptr' will be automatically released
* - 'string_ptr' will be updated to point to a dynamically allocated string
* containing the concatinated text.
* - If there is insufficient resource to extend the string then it will not
* be extended.
* - The client maintains responsibility for releasing the string reference
* by string_ptr when they are finished using it.
*/
void lub_string_cat(
/**
* A pointer to the string to concatinate
*/
char **string_ptr,
/**
* The text to be appended
*/
const char *text);
/**
* This operation concatinates a specified length of some text onto an
* existing string.
*
* \pre
* - 'string_ptr' must contain reference to NULL or to a dynamically allocated
* string.
*
* \post
* - The old string referenced by 'string_ptr' will be automatically
* released.
* - 'string_ptr' will be updated to point to a dynamically allocated
* string containing the concatinated text.
* - If there is insufficient resource to extend the string then it will not
* be extended.
* - If there length passed in is greater than that of the specified 'text'
* then the length of the 'text' will be assumed.
* - The client maintains responsibility for releasing the string reference
* by string_ptr when they are finished using it.
*/
void lub_string_catn(
/**
* A pointer to the string to concatinate
*/
char **string_ptr,
/**
* The text to be appended
*/
const char *text,
/**
* The length of text to be appended
*/
size_t length);
/**
* This operation dupicates a specified length of some text into a
* new string.
*
* \pre
* - none
*
* \return
* A dynamically allocated string containing the same content as that specified.
*
* \post
* - The client is responsible for calling lub_string_free() with the
* returned string when they are finished using it.
*/
char *lub_string_dupn(
/**
* The string containing the text to duplicate
*/
const char *string,
/**
* The length of text to be duplicated
*/
unsigned length);
/**
* This operation returns a pointer to the last (space separated) word in the
* specified string.
*
* \pre
* - none
*
* \return
* A pointer to the last word in the string.
*
* \post
* - none
*/
const char *lub_string_suffix(
/**
* The string from which to extract a suffix
*/
const char *string);
/**
* This operation compares string cs to string ct in a case insensitive manner.
*
* \pre
* - none
*
* \return
* - < 0 if cs < ct
* - 0 if cs == ct
* - > 0 if cs > ct
*
* \post
* - none
*/
int lub_string_nocasecmp(
/**
* The first string for the comparison
*/
const char *cs,
/**
* The second string for the comparison
*/
const char *ct);
/**
* This operation performs a case insensitive search for a substring within
* another string.
*
* \pre
* - none
*
* \return
* pointer to first occurance of a case insensitive version of the string ct,
* or NULL if not present.
*
* \post
* - none
*/
const char *lub_string_nocasestr(
/**
* The string within which to find a substring
*/
const char *cs,
/**
* The substring for which to search
*/
const char *ct);
/**
* This operation releases the resources associated with a dynamically allocated
* string.
*
* \pre
* - The calling client must have responsibility for the passed string.
*
* \return
* none
*
* \post
* - The string is no longer usable, any references to it must be discarded.
*/
void lub_string_free(
/**
* The string to be released
*/
char *string);
/*
* These are the escape characters which are used by default when
* expanding variables. These characters will be backslash escaped
* to prevent them from being interpreted in a script.
*
* This is a security feature to prevent users from arbitarily setting
* parameters to contain special sequences.
*/
extern const char *lub_string_esc_default;
extern const char *lub_string_esc_regex;
extern const char *lub_string_esc_quoted;
/**
* This operation decode the escaped string.
*
* \pre
* - none
*
* \return
* - The allocated string without escapes.
*
* \post
* - The result string must be freed after using.
*/
char *lub_string_decode(const char *string);
char *lub_string_ndecode(const char *string, unsigned int len);
/**
* This operation encode the string using escape.
*
* \pre
* - none
*
* \return
* - The allocated string with escapes.
*
* \post
* - The result string must be freed after using.
*/
char *lub_string_encode(const char *string, const char *escape_chars);
char *lub_string_tolower(const char *str);
unsigned int lub_string_equal_part(const char *str1, const char *str2,
bool_t utf8);
_END_C_DECL
#endif /* _lub_string_h */
/** @} */
|
zzysjtu-klish
|
lub/string.h
|
C
|
bsd
| 7,077
|
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "private.h"
/*--------------------------------------------------------- */
static inline void lub_list_init(lub_list_t * this,
lub_list_compare_fn compareFn)
{
this->head = NULL;
this->compareFn = compareFn;
}
/*--------------------------------------------------------- */
lub_list_t *lub_list_new(lub_list_compare_fn compareFn)
{
lub_list_t *this;
this = malloc(sizeof(*this));
assert(this);
lub_list_init(this, compareFn);
return this;
}
/*--------------------------------------------------------- */
void inline lub_list_free(lub_list_t *this)
{
free(this);
}
/*--------------------------------------------------------- */
inline lub_list_node_t *lub_list__get_head(lub_list_t *this)
{
return this->head;
}
/*--------------------------------------------------------- */
inline lub_list_node_t *lub_list__get_tail(lub_list_t *this)
{
return this->tail;
}
/*--------------------------------------------------------- */
static inline void lub_list_node_init(lub_list_node_t *this,
void *data)
{
this->prev = this->next = NULL;
this->data = data;
}
/*--------------------------------------------------------- */
lub_list_node_t *lub_list_node_new(void *data)
{
lub_list_node_t *this;
this = malloc(sizeof(*this));
assert(this);
lub_list_node_init(this, data);
return this;
}
/*--------------------------------------------------------- */
inline lub_list_node_t *lub_list_iterator_init(lub_list_t *this)
{
return this->head;
}
/*--------------------------------------------------------- */
inline lub_list_node_t *lub_list_node__get_prev(lub_list_node_t *this)
{
return this->prev;
}
/*--------------------------------------------------------- */
inline lub_list_node_t *lub_list_node__get_next(lub_list_node_t *this)
{
return this->next;
}
/*--------------------------------------------------------- */
inline lub_list_node_t *lub_list_iterator_next(lub_list_node_t *this)
{
return lub_list_node__get_next(this);
}
/*--------------------------------------------------------- */
inline lub_list_node_t *lub_list_iterator_prev(lub_list_node_t *this)
{
return lub_list_node__get_prev(this);
}
/*--------------------------------------------------------- */
void inline lub_list_node_free(lub_list_node_t *this)
{
free(this);
}
/*--------------------------------------------------------- */
inline void *lub_list_node__get_data(lub_list_node_t *this)
{
return this->data;
}
/*--------------------------------------------------------- */
lub_list_node_t *lub_list_add(lub_list_t *this, void *data)
{
lub_list_node_t *node = lub_list_node_new(data);
lub_list_node_t *iter;
/* Empty list */
if (!this->head) {
this->head = node;
this->tail = node;
return node;
}
/* Not sorted list. Add to the tail. */
if (!this->compareFn) {
node->prev = this->tail;
node->next = NULL;
this->tail->next = node;
this->tail = node;
return node;
}
/* Sorted list */
iter = this->tail;
while (iter) {
if (this->compareFn(node->data, iter->data) >= 0) {
node->next = iter->next;
node->prev = iter;
iter->next = node;
if (node->next)
node->next->prev = node;
break;
}
iter = iter->prev;
}
/* Insert node into the list head */
if (!iter) {
node->next = this->head;
node->prev = NULL;
this->head->prev = node;
this->head = node;
}
if (!node->next)
this->tail = node;
return node;
}
/*--------------------------------------------------------- */
void lub_list_del(lub_list_t *this, lub_list_node_t *node)
{
if (node->prev)
node->prev->next = node->next;
else
this->head = node->next;
if (node->next)
node->next->prev = node->prev;
else
this->tail = node->prev;
}
inline void lub_list_node_copy(lub_list_node_t *dst, lub_list_node_t *src)
{
memcpy(dst, src, sizeof(lub_list_node_t));
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/list/list.c
|
C
|
bsd
| 3,917
|
#include "lub/list.h"
struct lub_list_node_s {
lub_list_node_t *prev;
lub_list_node_t *next;
void *data;
};
struct lub_list_s {
lub_list_node_t *head;
lub_list_node_t *tail;
lub_list_compare_fn *compareFn;
};
|
zzysjtu-klish
|
lub/list/private.h
|
C
|
bsd
| 217
|
/*
* types.h
*/
/**
\ingroup lub
\defgroup lub_types types
\brief This provides some primative types not found in ANSI-C.
@{
*/
#ifndef _lub_types_h
#define _lub_types_h
/**
* A boolean type for ANSI-C
*/
typedef enum {
BOOL_FALSE,
BOOL_TRUE
} bool_t;
/** @} */
#endif /* _lub_types_h */
|
zzysjtu-klish
|
lub/types.h
|
C
|
bsd
| 302
|
/*
* argv.h
*/
/**
\ingroup lub
\defgroup lub_argv argv
@{
\brief This utility provides a simple means of manipulating a vector of
command textual words.
A word is either separated by whitespace, or if quotes are used a word is
defined by the scope of the quotes.
e.g.
\verbatim
one two "this is the third word" four
\endverbatim
contains four "words" the third of which is a string.
*/
#ifndef _lub_argv_h
#define _lub_argv_h
#include <stddef.h>
#include "c_decl.h"
#include "types.h"
_BEGIN_C_DECL
/**
* This type is used to reference an instance of an argument vector
*/
typedef struct lub_argv_s lub_argv_t;
/*=====================================
* ARGV INTERFACE
*===================================== */
/**
* \pre
* - none
*
* \return
* The number of space separated words in the specified string.
*
* \post
* - none
*/
unsigned lub_argv_wordcount(
/**
* The string to analyse
*/
const char *line);
/**
* This operation is used to construct an instance of this class. The client
* species a string and an offset within that string, from which to start
* collecting "words" to place into the vector instance.
*
* \pre
* - none
*
* \return
* - A instance of an argument vector, which represents the words contained in
* the provided string.
* - NULL if there is insuffcient resource
*
* \post
* - The client becomes resposible for releasing the instance when they are
* finished with it, by calling lub_argv_delete()
*/
lub_argv_t *lub_argv_new(
/**
* The string to analyse
*/
const char *line,
/**
* The offset in the string to start from
*/
size_t offset);
void lub_argv_delete(lub_argv_t * instance);
unsigned lub_argv__get_count(const lub_argv_t * instance);
const char *lub_argv__get_arg(const lub_argv_t * instance, unsigned index);
size_t lub_argv__get_offset(const lub_argv_t * instance, unsigned index);
bool_t lub_argv__get_quoted(const lub_argv_t * instance, unsigned index);
void lub_argv__set_arg(lub_argv_t * instance, unsigned index, const char *arg);
char **lub_argv__get_argv(const lub_argv_t * instance, const char *argv0);
void lub_argv__free_argv(char **argv);
char *lub_argv__get_line(const lub_argv_t * instance);
void lub_argv_add(lub_argv_t * instance, const char *text);
_END_C_DECL
#endif /* _lub_argv_h */
/** @} lub_argv */
|
zzysjtu-klish
|
lub/argv.h
|
C
|
bsd
| 2,366
|
/*
* ctype_isspace.c
*/
#include "lub/ctype.h"
#include <ctype.h>
/*--------------------------------------------------------- */
bool_t lub_ctype_isspace(char c)
{
unsigned char tmp = (unsigned char)c;
return isspace(tmp) ? BOOL_TRUE : BOOL_FALSE;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/ctype/ctype_isspace.c
|
C
|
bsd
| 319
|
/*
* ctype_isdigit.c
*/
#include "lub/ctype.h"
#include <ctype.h>
/*--------------------------------------------------------- */
bool_t lub_ctype_isdigit(char c)
{
unsigned char tmp = (unsigned char)c;
return isdigit(tmp) ? BOOL_TRUE : BOOL_FALSE;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/ctype/ctype_isdigit.c
|
C
|
bsd
| 319
|
/*
* ctype_toupper.c
*/
#include "lub/ctype.h"
#include <ctype.h>
/*--------------------------------------------------------- */
char lub_ctype_toupper(char c)
{
unsigned char tmp = (unsigned char)c;
return toupper(tmp);
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/ctype/ctype_toupper.c
|
C
|
bsd
| 292
|
/*
* ctype_tolower.c
*/
#include "lub/ctype.h"
#include <ctype.h>
/*--------------------------------------------------------- */
char lub_ctype_tolower(char c)
{
unsigned char tmp = (unsigned char)c;
return tolower(tmp);
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/ctype/ctype_tolower.c
|
C
|
bsd
| 292
|
/*
* string_free.c
*/
#include "private.h"
#include <stdlib.h>
/*--------------------------------------------------------- */
void lub_string_free(char *ptr)
{
free(ptr);
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/string/string_free.c
|
C
|
bsd
| 242
|
/*
* string_nocasecmp.c
*/
#include <string.h>
#include <ctype.h>
#include "private.h"
#include "lub/ctype.h"
/*--------------------------------------------------------- */
int lub_string_nocasecmp(const char *cs, const char *ct)
{
int result = 0;
while ((0 == result) && *cs && *ct) {
/*lint -e155 Ignoring { }'ed sequence within an expression, 0 assumed
* MACRO implementation uses braces to prevent multiple increments
* when called.
*/
int s = lub_ctype_tolower(*cs++);
int t = lub_ctype_tolower(*ct++);
result = s - t;
}
/*lint -e774 Boolean within 'if' always evealuates to True
* not the case because of tolower() evaluating to 0 under lint
* (see above)
*/
if (0 == result) {
/* account for different string lengths */
result = *cs - *ct;
}
return result;
}
/*--------------------------------------------------------- */
char *lub_string_tolower(const char *str)
{
char *tmp = strdup(str);
char *p = tmp;
while (*p) {
*p = tolower(*p);
p++;
}
return tmp;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/string/string_nocasecmp.c
|
C
|
bsd
| 1,084
|
/*
* string_escape.c
*/
#include "private.h"
#include <stdlib.h>
#include <string.h>
const char *lub_string_esc_default = "`|$<>&()#;\\\"!";
const char *lub_string_esc_regex = "^$.*+[](){}";
const char *lub_string_esc_quoted = "\\\"";
/*--------------------------------------------------------- */
char *lub_string_ndecode(const char *string, unsigned int len)
{
const char *s = string;
char *res, *p;
int esc = 0;
if (!string)
return NULL;
/* Allocate enough memory for result */
p = res = malloc(len + 1);
while (*s && (s < (string +len))) {
if (!esc) {
if ('\\' == *s)
esc = 1;
else
*p = *s;
} else {
/* switch (*s) {
case 'r':
case 'n':
*p = '\n';
break;
case 't':
*p = '\t';
break;
default:
*p = *s;
break;
}
*/ *p = *s;
esc = 0;
}
if (!esc)
p++;
s++;
}
*p = '\0';
return res;
}
/*--------------------------------------------------------- */
inline char *lub_string_decode(const char *string)
{
return lub_string_ndecode(string, strlen(string));
}
/*----------------------------------------------------------- */
/*
* This needs to escape any dangerous characters within the command line
* to prevent gaining access to the underlying system shell.
*/
char *lub_string_encode(const char *string, const char *escape_chars)
{
char *result = NULL;
const char *p;
if (!escape_chars)
return lub_string_dup(string);
if (string && !(*string)) /* Empty string */
return lub_string_dup(string);
for (p = string; p && *p; p++) {
/* find any special characters and prefix them with '\' */
size_t len = strcspn(p, escape_chars);
lub_string_catn(&result, p, len);
p += len;
if (*p) {
lub_string_catn(&result, "\\", 1);
lub_string_catn(&result, p, 1);
} else {
break;
}
}
return result;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/string/string_escape.c
|
C
|
bsd
| 1,879
|
/*
* string_nocasestr.c
*
* Find a string within another string in a case insensitive manner
*/
#include "private.h"
#include "lub/ctype.h"
/*--------------------------------------------------------- */
const char *lub_string_nocasestr(const char *cs, const char *ct)
{
const char *p = NULL;
const char *result = NULL;
while (*cs) {
const char *q = cs;
p = ct;
/*lint -e155 Ignoring { }'ed sequence within an expression, 0 assumed
* MACRO implementation uses braces to prevent multiple increments
* when called.
*/
/*lint -e506 Constant value Boolean
* not the case because of tolower() evaluating to 0 under lint
* (see above)
*/
while (*p && *q
&& (lub_ctype_tolower(*p) == lub_ctype_tolower(*q))) {
p++, q++;
}
if (0 == *p) {
break;
}
cs++;
}
if (p && !*p) {
/* we've found the first match of ct within cs */
result = cs;
}
return result;
}
/*--------------------------------------------------------- */
unsigned int lub_string_equal_part(const char *str1, const char *str2,
bool_t utf8)
{
unsigned int cnt = 0;
if (!str1 || !str2)
return cnt;
while (*str1 && *str2) {
if (*str1 != *str2)
break;
cnt++;
str1++;
str2++;
}
if (!utf8)
return cnt;
/* UTF8 features */
if (cnt && (UTF8_11 == (*(str1 - 1) & UTF8_MASK)))
cnt--;
return cnt;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/string/string_nocasestr.c
|
C
|
bsd
| 1,404
|
/*
* string_dup.c
*/
#include <stdlib.h>
#include <string.h>
#include "private.h"
/*--------------------------------------------------------- */
char *lub_string_dup(const char *string)
{
if (!string)
return NULL;
return strdup(string);
}
/*--------------------------------------------------------- */
char *lub_string_dupn(const char *string, unsigned int len)
{
char *res = NULL;
if (!string)
return res;
res = malloc(len + 1);
strncpy(res, string, len);
res[len] = '\0';
return res;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/string/string_dup.c
|
C
|
bsd
| 572
|
/*
* string_cat.c
*/
#include "private.h"
#include <string.h>
/*--------------------------------------------------------- */
void lub_string_cat(char **string, const char *text)
{
size_t len = text ? strlen(text) : 0;
lub_string_catn(string, text, len);
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/string/string_cat.c
|
C
|
bsd
| 325
|
/*
* private.h
*/
#include "lub/string.h"
|
zzysjtu-klish
|
lub/string/private.h
|
C
|
bsd
| 44
|
/*
* string_cat.c
*/
#include "private.h"
#include <string.h>
#include <stdlib.h>
/*--------------------------------------------------------- */
void lub_string_catn(char **string, const char *text, size_t len)
{
if (text) {
char *q;
size_t length, initlen, textlen = strlen(text);
/* make sure the client cannot give us duff details */
len = (len < textlen) ? len : textlen;
/* remember the size of the original string */
initlen = *string ? strlen(*string) : 0;
/* account for '\0' */
length = initlen + len + 1;
/* allocate the memory for the result */
q = realloc(*string, length);
if (NULL != q) {
*string = q;
/* move to the end of the initial string */
q += initlen;
while (len--) {
*q++ = *text++;
}
*q = '\0';
}
}
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/string/string_catn.c
|
C
|
bsd
| 845
|
/*
* string_suffix.c
*/
#include "private.h"
#include "lub/ctype.h"
/*--------------------------------------------------------- */
const char *lub_string_suffix(const char *string)
{
const char *p1, *p2;
p1 = p2 = string;
while (*p1) {
if (lub_ctype_isspace(*p1)) {
p2 = p1;
p2++;
}
p1++;
}
return p2;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/string/string_suffix.c
|
C
|
bsd
| 388
|
/*
* system_file.c
*/
#include <stdlib.h>
#include <string.h>
#include "private.h"
#include "lub/string.h"
/*-------------------------------------------------------- */
/* perform a simple tilde substitution for the home directory
* defined in HOME
*/
char *lub_system_tilde_expand(const char *path)
{
char *home_dir = getenv("HOME");
char *result = NULL;
char *tilde;
while ((tilde = strchr(path, '~'))) {
lub_string_catn(&result, path, tilde - path);
lub_string_cat(&result, home_dir);
path = tilde + 1;
}
lub_string_cat(&result, path);
return result;
}
|
zzysjtu-klish
|
lub/system/system_file.c
|
C
|
bsd
| 578
|
/*
* system_test.c
*/
#include <stdlib.h>
#include "private.h"
/*--------------------------------------------------------- */
bool_t lub_system_test(int argc, char **argv)
{
return testcmd(argc, argv) ? BOOL_FALSE : BOOL_TRUE;
}
/*--------------------------------------------------------- */
bool_t lub_system_line_test(const char *line)
{
bool_t res;
lub_argv_t *argv;
argv = lub_argv_new(line, 0);
res = lub_system_argv_test(argv);
lub_argv_delete(argv);
return res;
}
/*--------------------------------------------------------- */
bool_t lub_system_argv_test(const lub_argv_t * argv)
{
bool_t res;
char **str_argv;
int str_argc;
/* Make args */
str_argv = lub_argv__get_argv(argv, "");
str_argc = lub_argv__get_count(argv) + 1;
/* Test it */
res = lub_system_test(str_argc, str_argv);
lub_argv__free_argv(str_argv);
return res;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/system/system_test.c
|
C
|
bsd
| 926
|
/*
* private.h
*/
#include "lub/types.h"
#include "lub/argv.h"
#include "lub/system.h"
int testcmd(int argc, char *argv[]);
|
zzysjtu-klish
|
lub/system/private.h
|
C
|
bsd
| 127
|
/* $OpenBSD: test.c,v 1.11 2009/10/27 23:59:22 deraadt Exp $ */
/* $NetBSD: test.c,v 1.15 1995/03/21 07:04:06 cgd Exp $ */
/*
* test(1); version 7-like -- author Erik Baalbergen
* modified by Eric Gisin to be used as built-in.
* modified by Arnold Robbins to add SVR3 compatibility
* (-x -c -b -p -u -g -k) plus Korn's -L -nt -ot -ef and new -S (socket).
* modified by J.T. Conklin for NetBSD.
*
* This program is in the Public Domain.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
#ifndef __dead
#define __dead __attribute__((noreturn))
#endif
#define main testcmd
/* test(1) accepts the following grammar:
oexpr ::= aexpr | aexpr "-o" oexpr ;
aexpr ::= nexpr | nexpr "-a" aexpr ;
nexpr ::= primary | "!" primary
primary ::= unary-operator operand
| operand binary-operator operand
| operand
| "(" oexpr ")"
;
unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"|
"-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S";
binary-operator ::= "="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
"-nt"|"-ot"|"-ef";
operand ::= <any legal UNIX file name>
*/
enum token {
EOI,
FILRD,
FILWR,
FILEX,
FILEXIST,
FILREG,
FILDIR,
FILCDEV,
FILBDEV,
FILFIFO,
FILSOCK,
FILSYM,
FILGZ,
FILTT,
FILSUID,
FILSGID,
FILSTCK,
FILNT,
FILOT,
FILEQ,
FILUID,
FILGID,
STREZ,
STRNZ,
STREQ,
STRNE,
STRLT,
STRGT,
INTEQ,
INTNE,
INTGE,
INTGT,
INTLE,
INTLT,
UNOT,
BAND,
BOR,
LPAREN,
RPAREN,
OPERAND
};
enum token_types {
UNOP,
BINOP,
BUNOP,
BBINOP,
PAREN
};
struct t_op {
const char *op_text;
short op_num, op_type;
} const ops[] = {
{"-r", FILRD, UNOP},
{"-w", FILWR, UNOP},
{"-x", FILEX, UNOP},
{"-e", FILEXIST, UNOP},
{"-f", FILREG, UNOP},
{"-d", FILDIR, UNOP},
{"-c", FILCDEV, UNOP},
{"-b", FILBDEV, UNOP},
{"-p", FILFIFO, UNOP},
{"-u", FILSUID, UNOP},
{"-g", FILSGID, UNOP},
{"-k", FILSTCK, UNOP},
{"-s", FILGZ, UNOP},
{"-t", FILTT, UNOP},
{"-z", STREZ, UNOP},
{"-n", STRNZ, UNOP},
{"-h", FILSYM, UNOP}, /* for backwards compat */
{"-O", FILUID, UNOP},
{"-G", FILGID, UNOP},
{"-L", FILSYM, UNOP},
{"-S", FILSOCK, UNOP},
{"=", STREQ, BINOP},
{"!=", STRNE, BINOP},
{"<", STRLT, BINOP},
{">", STRGT, BINOP},
{"-eq", INTEQ, BINOP},
{"-ne", INTNE, BINOP},
{"-ge", INTGE, BINOP},
{"-gt", INTGT, BINOP},
{"-le", INTLE, BINOP},
{"-lt", INTLT, BINOP},
{"-nt", FILNT, BINOP},
{"-ot", FILOT, BINOP},
{"-ef", FILEQ, BINOP},
{"!", UNOT, BUNOP},
{"-a", BAND, BBINOP},
{"-o", BOR, BBINOP},
{"(", LPAREN, PAREN},
{")", RPAREN, PAREN},
{0, 0, 0}
};
char **t_wp;
struct t_op const *t_wp_op;
static enum token t_lex(char *);
static enum token_types t_lex_type(char *);
static int oexpr(enum token n);
static int aexpr(enum token n);
static int nexpr(enum token n);
static int binop(void);
static int primary(enum token n);
static int filstat(char *nm, enum token mode);
static int getn(const char *s);
static int newerf(const char *, const char *);
static int olderf(const char *, const char *);
static int equalf(const char *, const char *);
#define syntax(op,msg) {return 2;}
int main(int argc, char *argv[])
{
int res;
if (strcmp(argv[0], "[") == 0) {
if (strcmp(argv[--argc], "]"))
syntax(NULL, "missing ]");
argv[argc] = NULL;
}
/* Implement special cases from POSIX.2, section 4.62.4 */
switch (argc) {
case 1:
return 1;
case 2:
return (*argv[1] == '\0');
case 3:
if (argv[1][0] == '!' && argv[1][1] == '\0') {
return !(*argv[2] == '\0');
}
break;
case 4:
if (argv[1][0] != '!' || argv[1][1] != '\0') {
if (t_lex(argv[2]),
t_wp_op && t_wp_op->op_type == BINOP) {
t_wp = &argv[1];
return (binop() == 0);
}
}
break;
case 5:
if (argv[1][0] == '!' && argv[1][1] == '\0') {
if (t_lex(argv[3]),
t_wp_op && t_wp_op->op_type == BINOP) {
t_wp = &argv[2];
return !(binop() == 0);
}
}
break;
}
t_wp = &argv[1];
res = !oexpr(t_lex(*t_wp));
if (*t_wp != NULL && *++t_wp != NULL)
syntax(*t_wp, "unknown operand");
return res;
}
static int oexpr(enum token n)
{
int res;
res = aexpr(n);
if (t_lex(*++t_wp) == BOR)
return oexpr(t_lex(*++t_wp)) || res;
t_wp--;
return res;
}
static int aexpr(enum token n)
{
int res;
res = nexpr(n);
if (t_lex(*++t_wp) == BAND)
return aexpr(t_lex(*++t_wp)) && res;
t_wp--;
return res;
}
static int nexpr(enum token n)
{
if (n == UNOT)
return !nexpr(t_lex(*++t_wp));
return primary(n);
}
static int primary(enum token n)
{
int res;
if (n == EOI)
syntax(NULL, "argument expected");
if (n == LPAREN) {
res = oexpr(t_lex(*++t_wp));
if (t_lex(*++t_wp) != RPAREN)
syntax(NULL, "closing paren expected");
return res;
}
/*
* We need this, if not binary operations with more than 4
* arguments will always fall into unary.
*/
if (t_lex_type(t_wp[1]) == BINOP) {
t_lex(t_wp[1]);
if (t_wp_op && t_wp_op->op_type == BINOP)
return binop();
}
if (t_wp_op && t_wp_op->op_type == UNOP) {
/* unary expression */
if (*++t_wp == NULL)
syntax(t_wp_op->op_text, "argument expected");
switch (n) {
case STREZ:
return strlen(*t_wp) == 0;
case STRNZ:
return strlen(*t_wp) != 0;
case FILTT:
return isatty(getn(*t_wp));
default:
return filstat(*t_wp, n);
}
}
return strlen(*t_wp) > 0;
}
static int binop(void)
{
const char *opnd1, *opnd2;
struct t_op const *op;
opnd1 = *t_wp;
(void)t_lex(*++t_wp);
op = t_wp_op;
if ((opnd2 = *++t_wp) == NULL)
syntax(op->op_text, "argument expected");
switch (op->op_num) {
case STREQ:
return strcmp(opnd1, opnd2) == 0;
case STRNE:
return strcmp(opnd1, opnd2) != 0;
case STRLT:
return strcmp(opnd1, opnd2) < 0;
case STRGT:
return strcmp(opnd1, opnd2) > 0;
case INTEQ:
return getn(opnd1) == getn(opnd2);
case INTNE:
return getn(opnd1) != getn(opnd2);
case INTGE:
return getn(opnd1) >= getn(opnd2);
case INTGT:
return getn(opnd1) > getn(opnd2);
case INTLE:
return getn(opnd1) <= getn(opnd2);
case INTLT:
return getn(opnd1) < getn(opnd2);
case FILNT:
return newerf(opnd1, opnd2);
case FILOT:
return olderf(opnd1, opnd2);
case FILEQ:
return equalf(opnd1, opnd2);
}
/* NOTREACHED */
return 1; /* to make compiler happy */
}
static enum token_types t_lex_type(char *s)
{
struct t_op const *op = ops;
if (s == NULL)
return -1;
while (op->op_text) {
if (strcmp(s, op->op_text) == 0)
return op->op_type;
op++;
}
return -1;
}
static int filstat(char *nm, enum token mode)
{
struct stat s;
mode_t i;
if (mode == FILSYM) {
#ifdef S_IFLNK
if (lstat(nm, &s) == 0) {
i = S_IFLNK;
goto filetype;
}
#endif
return 0;
}
if (stat(nm, &s) != 0)
return 0;
switch (mode) {
case FILRD:
return access(nm, R_OK) == 0;
case FILWR:
return access(nm, W_OK) == 0;
case FILEX:
return access(nm, X_OK) == 0;
case FILEXIST:
return access(nm, F_OK) == 0;
case FILREG:
i = S_IFREG;
goto filetype;
case FILDIR:
i = S_IFDIR;
goto filetype;
case FILCDEV:
i = S_IFCHR;
goto filetype;
case FILBDEV:
i = S_IFBLK;
goto filetype;
case FILFIFO:
#ifdef S_IFIFO
i = S_IFIFO;
goto filetype;
#else
return 0;
#endif
case FILSOCK:
#ifdef S_IFSOCK
i = S_IFSOCK;
goto filetype;
#else
return 0;
#endif
case FILSUID:
i = S_ISUID;
goto filebit;
case FILSGID:
i = S_ISGID;
goto filebit;
case FILSTCK:
i = S_ISVTX;
goto filebit;
case FILGZ:
return s.st_size > 0L;
case FILUID:
return s.st_uid == geteuid();
case FILGID:
return s.st_gid == getegid();
default:
return 1;
}
filetype:
return ((s.st_mode & S_IFMT) == i);
filebit:
return ((s.st_mode & i) != 0);
}
static enum token t_lex(char *s)
{
struct t_op const *op = ops;
if (s == 0) {
t_wp_op = NULL;
return EOI;
}
while (op->op_text) {
if (strcmp(s, op->op_text) == 0) {
t_wp_op = op;
return op->op_num;
}
op++;
}
t_wp_op = NULL;
return OPERAND;
}
/* atoi with error detection */
static int getn(const char *s)
{
char *p;
long r;
errno = 0;
r = strtol(s, &p, 10);
if (errno != 0)
syntax(NULL, "out of range");
while (isspace(*p))
p++;
if (*p)
syntax(NULL, "bad number");
return (int)r;
}
static int newerf(const char *f1, const char *f2)
{
struct stat b1, b2;
return (stat(f1, &b1) == 0 &&
stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
}
static int olderf(const char *f1, const char *f2)
{
struct stat b1, b2;
return (stat(f1, &b1) == 0 &&
stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
}
static int equalf(const char *f1, const char *f2)
{
struct stat b1, b2;
return (stat(f1, &b1) == 0 &&
stat(f2, &b2) == 0 &&
b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
}
|
zzysjtu-klish
|
lub/system/test.c
|
C
|
bsd
| 8,753
|
#ifndef _lub_passwd_h
#define _lub_passwd_h
#include <stddef.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#ifdef HAVE_GRP_H
#include <grp.h>
#endif
/* Wrappers for ugly getpwnam_r()-like functions */
#ifdef HAVE_PWD_H
struct passwd *lub_db_getpwnam(const char *name);
struct passwd *lub_db_getpwuid(uid_t uid);
#endif
#ifdef HAVE_GRP_H
struct group *lub_db_getgrnam(const char *name);
struct group *lub_db_getgrgid(gid_t gid);
#endif
#endif
|
zzysjtu-klish
|
lub/db.h
|
C
|
bsd
| 515
|
/*
* bintree_dump.c
*/
#include <stdio.h>
#include "private.h"
/*--------------------------------------------------------- */
void _lub_bintree_dump(lub_bintree_t * this, lub_bintree_node_t * node)
{
if (node->left) {
_lub_bintree_dump(this, node->left);
}
printf(" %s%p",
(this->root == node) ? "(R)" : "",
lub_bintree_getclientnode(this, node));
if (node->right) {
_lub_bintree_dump(this, node->right);
}
}
/*--------------------------------------------------------- */
void lub_bintree_dump(lub_bintree_t * this)
{
if (this->root) {
_lub_bintree_dump(this, this->root);
}
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_dump.c
|
C
|
bsd
| 674
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_findprevious.c
*---------------------------------------------------------------
* Description
* ===========
* This operation searches the specified "tree" for a "clientnode" which is
* the one which logically preceeds the specified "key"
*
* A "clientnode" with the specified "key" doesn't need to be in the tree.
*
* tree - the "tree" instance to invoke this operation upon
* key - the "key" to search with
*
* RETURNS
* "clientnode" instance or NULL if no node is found.
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 10:33:12 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 27-Feb-2004 Graeme McKerrell
* Fixed to account for empty tree
* 9-Feb-2004 Graeme McKerrell
* updated to use new node,key comparison ordering
* 28-Jan-2004 Graeme McKerrell
* Initial verison
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include "private.h"
/*--------------------------------------------------------- */
void *lub_bintree_findprevious(lub_bintree_t * this, const void *clientkey)
{
lub_bintree_node_t *t = this->root;
int comp;
/*
* have a look for a direct match
*/
t = this->root = lub_bintree_splay(this, t, clientkey);
if (NULL != t) {
/* now look at what we have got */
comp = lub_bintree_compare(this, t, clientkey);
if (comp >= 0) {
/*
* time to fiddle with the left hand side of the tree
* we need the closest node from the left hand side
*/
t = t->left =
lub_bintree_splay(this, t->left, clientkey);
}
}
if (NULL == t) {
return NULL;
} else {
return lub_bintree_getclientnode(this, t);
}
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_findprevious.c
|
C
|
bsd
| 2,178
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_init.c
*---------------------------------------------------------------
* Description
* ===========
* This operations initialise an instance of a binary tree at runtime.
*
* this - the "tree" instance to initialise
*
* offset - the offset of the node structure within the clients
* structure. This is typically passed using the offsetof() macro.
*
* compareFn - a comparison function for comparing a "clientnode"
* with a "clientkey"
*
* getkeyFn - a function which will fill out a "key" from a clientnode
*
* RETURNS
* none
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 09:54:37 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 9-Feb-2004 Graeme McKerrell
* update to remove spurious key_storage parameter
* 28-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include "private.h"
/*--------------------------------------------------------- */
void
lub_bintree_init(lub_bintree_t * this,
size_t node_offset,
lub_bintree_compare_fn compareFn,
lub_bintree_getkey_fn getkeyFn)
{
this->root = NULL;
this->node_offset = node_offset;
this->compareFn = compareFn;
this->getkeyFn = getkeyFn;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_init.c
|
C
|
bsd
| 1,808
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_splay.c
*---------------------------------------------------------------
* Description
* ===========
* An implementation of top-down splaying
* D. Sleator <sleator@cs.cmu.edu>
* March 1992
*
* "Splay trees", or "self-adjusting search trees" are a simple and
* efficient data structure for storing an ordered set. The data
* structure consists of a binary tree, without parent pointers, and
* no additional fields. It allows searching, insertion, deletion,
* deletemin, deletemax, splitting, joining, and many other
* operations, all with amortized logarithmic performance. Since the
* trees adapt to the sequence of requests, their performance on real
* access patterns is typically even better. Splay trees are
* described in a number of texts and papers [1,2,3,4,5].
*
* The code here is adapted from simple top-down splay, at the bottom
* of page 669 of [3]. It can be obtained via anonymous ftp from
* spade.pc.cs.cmu.edu in directory /usr/sleator/public.
*
* The chief modification here is that the splay operation works even
* if the item being splayed is not in the tree, and even if the tree
* root of the tree is NULL. So the line:
*
* t = splay(i, t);
*
* causes it to search for item with key i in the tree rooted at t.
* If it's there, it is splayed to the root. If it isn't there,
* then the node put at the root is the last one before NULL that
* would have been reached in a normal binary search for i. (It's a
* neighbor of i in the tree.) This allows many other operations to
* be easily implemented, as shown below.
*
* [1] "Fundamentals of data structures in C", Horowitz, Sahni,
* and Anderson-Freed, Computer Science Press, pp 542-547.
* [2] "Data Structures and Their Algorithms", Lewis and Denenberg,
* Harper Collins, 1991, pp 243-251.
* [3] "Self-adjusting Binary Search Trees" Sleator and Tarjan,
* JACM Volume 32, No 3, July 1985, pp 652-686.
* [4] "Data Structure and Algorithm Analysis", Mark Weiss,
* Benjamin Cummins, 1992, pp 119-130.
* [5] "Data Structures, Algorithms, and Performance", Derick Wood,
* Addison-Wesley, 1993, pp 367-375.
*
* The following code was written by Daniel Sleator, and is released
* in the public domain.
*
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 16:29:28 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 2-Mar-2004 Graeme McKerrell
* Fixed to account for comparision logic being (node - key)
* original algorithm expected (key - node)
* 9-Feb-2004 Graeme McKerrell
* updated to use new node,key comparison ordering
* 28-Jan-2004 Graeme McKerrell
* Adapted from original public domain code
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include "private.h"
/*--------------------------------------------------------- */
lub_bintree_node_t *lub_bintree_splay(const lub_bintree_t * this,
lub_bintree_node_t * t, const void *key)
{
/* Simple top down splay, not requiring "key" to be in the tree t. */
/* What it does is described above. */
lub_bintree_node_t N, *leftTreeMax, *rightTreeMin, *y;
int comp;
if (t == NULL)
return t;
N.left = N.right = NULL;
leftTreeMax = rightTreeMin = &N;
for (;;) {
comp = lub_bintree_compare(this, t, key);
if (comp > 0) {
if (t->left == NULL)
break;
if (lub_bintree_compare(this, t->left, key) > 0) {
y = t->left; /* rotate right */
t->left = y->right;
y->right = t;
t = y;
if (t->left == NULL)
break;
}
rightTreeMin->left = t; /* link right */
rightTreeMin = t;
t = t->left;
} else if (comp < 0) {
if (t->right == NULL)
break;
if (lub_bintree_compare(this, t->right, key) < 0) {
y = t->right; /* rotate left */
t->right = y->left;
y->left = t;
t = y;
if (t->right == NULL)
break;
}
leftTreeMax->right = t; /* link left */
leftTreeMax = t;
t = t->right;
} else {
break;
}
}
leftTreeMax->right = t->left; /* assemble */
rightTreeMin->left = t->right;
t->left = N.right;
t->right = N.left;
/* return the new root */
return t;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_splay.c
|
C
|
bsd
| 4,778
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_iterator_previous.c
*---------------------------------------------------------------
* Description
* ===========
* This operation returns the previous "clientnode" in an iteration.
*
* iter - the iterator instance to invoke this operation upon.
*
* RETURNS
* "clientnode" instance or NULL if the iteration has reached the beginning
* of the tree.
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 10:35:19 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 9-Feb-2004 Graeme McKerrell
* updated to use new key structure
* 28-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include "private.h"
/*--------------------------------------------------------- */
void *lub_bintree_iterator_previous(lub_bintree_iterator_t * this)
{
void *clientnode = lub_bintree_findprevious(this->tree, &this->key);
/* make sure that next time we've move onward */
lub_bintree_iterator_init(this, this->tree, clientnode);
return clientnode;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_iterator_previous.c
|
C
|
bsd
| 1,585
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_findnext.c
*---------------------------------------------------------------
* Description
* ===========
* This operation searches the specified "tree" for a "clientnode" which is
* the one which logically follows the specified "key"
*
* A "clientnode" with the specified "key" doesn't need to be in the tree.
*
* tree - the "tree" instance to invoke this operation upon
* key - the "key" to search with
*
* RETURNS
* "clientnode" instance or NULL if no node is found.
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 10:32:28 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 27-Feb-2004 Graeme McKerrell
* Fixed to account for empty tree
* 9-Feb-2004 Graeme McKerrell
* updated to use new node,key comparison ordering
* 28-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include "private.h"
/*--------------------------------------------------------- */
void *lub_bintree_findnext(lub_bintree_t * this, const void *clientkey)
{
lub_bintree_node_t *t = this->root;
int comp;
/*
* have a look for a direct match
*/
t = this->root = lub_bintree_splay(this, t, clientkey);
if (NULL != t) {
/* now look at what we have got */
comp = lub_bintree_compare(this, t, clientkey);
if (comp <= 0) {
/*
* time to fiddle with the right hand side of the tree
* we need the closest node from the right hand side
*/
t = t->right =
lub_bintree_splay(this, t->right, clientkey);
}
}
if (NULL == t) {
return NULL;
} else {
return lub_bintree_getclientnode(this, t);
}
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_findnext.c
|
C
|
bsd
| 2,173
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_iterator_init.c
*---------------------------------------------------------------
* Description
* ===========
* This operation initialises an iterator. This can then be
* subsequently used for iterating through a tree. This will work
* even if the "clientnode" which defined the current iterator has been
* removed before the next iterator operation.
*
* iter - the iterator instance to initialise
* tree - the tree to associate with this iterator
* clientnode - the starting point for the iteration
*
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 10:33:42 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 3-Nov-2004 Graeme McKerrell
* Added key bounds checking code
* 5-May-2004 Graeme McKerrell
* updates following review
* 9-Feb-2004 Graeme McKerrell
* updated to use new getkey prototype
* 28-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include "private.h"
#include <assert.h>
#define MAGIC_NUMBER 0x12345678
/*--------------------------------------------------------- */
void
lub_bintree_iterator_init(lub_bintree_iterator_t * this,
lub_bintree_t * tree, const void *clientnode)
{
if (clientnode != NULL) {
this->tree = tree;
this->key.magic = MAGIC_NUMBER;
/* fill out the iterator's key */
this->tree->getkeyFn(clientnode, &this->key);
/*
* this assert will fire if the client tries to store more than
* the current storage permits
*/
assert(this->key.magic == MAGIC_NUMBER);
}
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_iterator_init.c
|
C
|
bsd
| 2,047
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_findlast.c
*---------------------------------------------------------------
* Description
* ===========
* This operation returns the last "clientnode" present in the
* specified "tree"
*
* tree - the "tree" instance to invoke this operation upon
*
* RETURNS
* "clientnode" instance or NULL if no nodes are present in this view.
*
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 10:17:17 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 2-Mar-2004 Graeme McKerrell
* fixed comparison logic
* 9-Feb-2004 Graeme McKerrell
* update to use new getkey prototype, removed the now spurious
* nullgetkey() function
* 28-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include "private.h"
/* forward declare these functions */
static lub_bintree_compare_fn compareright;
/*--------------------------------------------------------- */
void *lub_bintree_findlast(lub_bintree_t * this)
{
lub_bintree_compare_fn *client_compare = this->compareFn;
/*
* put dummy functions in place
* This will make the search faster and direct it to the right most
* node
*/
this->compareFn = compareright;
/*
* the key doesn't matter here cos we've cobbled the compare function
*/
this->root = lub_bintree_splay(this, this->root, NULL);
/* restore the client functions */
this->compareFn = client_compare;
if (NULL == this->root)
return NULL;
else
return lub_bintree_getclientnode(this, this->root);
}
/*--------------------------------------------------------- */
/*
* This comparison operation always returns -1 hence will force a
* search to the left most node.
*
* key1 - first node to compare (not used)
* key2 - second node to compare (not used)
*/
static int compareright(const void *clientnode, const void *clientkey)
{
clientnode = clientnode;
clientkey = clientkey;
return -1;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_findlast.c
|
C
|
bsd
| 2,473
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_findfirst.c
*---------------------------------------------------------------
* Description
* ===========
* This operation returns the first "clientnode" present in the specified "tree"
*
* tree - the "tree" instance to invoke this operation upon
*
* RETURNS
* "clientnode" instance or NULL if no nodes are present in this view.
*
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 10:15:00 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 2-Mar-2004 Graeme McKerrell
* fixed comparison logic
* 9-Feb-2004 Graeme McKerrell
* update to use new getkey prototype, removed the now spurious
* nullgetkey() function
* 28-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include "private.h"
/* forward declare these functions */
static lub_bintree_compare_fn compareleft;
/*--------------------------------------------------------- */
void *lub_bintree_findfirst(lub_bintree_t * this)
{
lub_bintree_compare_fn *client_compare = this->compareFn;
/*
* put dummy functions in place
* This will make the search faster and direct it to the left most
* node
*/
this->compareFn = compareleft;
/*
* the key doesn't matter here cos we've cobbled the compare function
*/
this->root = lub_bintree_splay(this, this->root, NULL);
/* restore the client functions */
this->compareFn = client_compare;
if (NULL == this->root)
return NULL;
else
return lub_bintree_getclientnode(this, this->root);
}
/*--------------------------------------------------------- */
/*
* This comparison operation always returns 1 hence will force a
* search to the left most node.
*
* clientnode - node to compare (not used)
* clientkey - key to compare (not used)
*/
static int compareleft(const void *clientnode, const void *clientkey)
{
clientnode = clientnode;
clientkey = clientkey;
return 1;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_findfirst.c
|
C
|
bsd
| 2,464
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_insert.c
*---------------------------------------------------------------
* Description
* ===========
* This operation adds a client node to the specified tree.
*
* tree - the "tree" instance to invoke this operation upon
* clientnode - a pointer to a client node. NB the tree can find the
* necessary util_BintreeNodeT from it's stored offset.
*
* RETURNS
* 0 if the "clientnode" is added correctly to the tree.
*
* If another "clientnode" already exists in the tree with the same key, then
* -1 is returned, and the tree remains unchanged.
*
* If the "clientnode" had not been initialised, then an assert will fire.
*
* If the bintree "node" is already part of a tree, then an assert will fire.
*
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 10:05:11 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 2-Mar-2004 Graeme McKerrell
* fixed so that the insertion order is correct
* 9-Feb-2004 Graeme McKerrell
* updated to use the new getkey prototype and new node, key ordering
* 28-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include <assert.h>
#include "private.h"
/*--------------------------------------------------------- */
int lub_bintree_insert(lub_bintree_t * this, void *clientnode)
{
int result = -1;
lub_bintree_node_t *new;
lub_bintree_key_t key;
assert(clientnode);
if (NULL != clientnode) {
/* obtain the control block from the clientnode */
new = lub_bintree_getnode(this, clientnode);
/* check this node is not currently in another tree */
assert(new->left == NULL);
assert(new->right == NULL);
/* add this node to the splay tree */
/* Insert "node" into the tree , unless it's already there. */
if (NULL == this->root) {
this->root = new;
this->root->left = this->root->right = NULL;
result = 0;
} else {
int comp;
/* get a key from the node */
this->getkeyFn(clientnode, &key);
/* do the biz */
this->root = lub_bintree_splay(this, this->root, &key);
/*
* compare the new key with the detail found
* in the tree
*/
comp = lub_bintree_compare(this, this->root, &key);
if (comp > 0) {
new->left = this->root->left;
new->right = this->root;
this->root->left = NULL;
result = 0;
} else if (comp < 0) {
new->right = this->root->right;
new->left = this->root;
this->root->right = NULL;
result = 0;
} else {
/* We get here if it's already in the tree */
}
}
if (0 == result) {
/* update the tree root */
this->root = new;
}
}
/* added OK */
return result;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_insert.c
|
C
|
bsd
| 3,208
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_remove.c
*---------------------------------------------------------------
* Description
* ===========
* This operation removes a "node" from the specified "tree"
*
* tree - the "tree" instance to invoke this operation upon
* clientnode - the node to remove
*
* RETURNS
* none
*
* POST CONDITIONS
* The "node" will no longer be part of the specified tree, and can be
* subsequently re-inserted
*
* If the node is not present in the specified tree, then an assert
* will fire.
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 10:06:58 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 27-Dec-2004 Graeme McKerrell
* added assert to catch removal of invalid node
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 23-Mar-2004 Graeme McKerrell
* fixed to ensure that control block is re-initialised.
* 16-Mar-2004 Graeme McKerrell
* removed assert.
* 27-Feb-2004 Graeme McKerrell
* removed spurious call to node_init
* 9-Feb-2004 Graeme McKerrell
* updated to use new node,key comparison ordering
* 28-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include <assert.h>
#include "private.h"
/*--------------------------------------------------------- */
void lub_bintree_remove(lub_bintree_t * this, void *clientnode)
{
lub_bintree_node_t *x, *t;
lub_bintree_key_t key;
int comp;
/* get the key from the node */
this->getkeyFn(clientnode, &key);
/* bring the node in question to the root of the tree */
t = lub_bintree_splay(this, this->root, &key);
/* check that the node was there to remove */
comp = lub_bintree_compare(this, t, &key);
assert(0 == comp);
if (0 == comp) {
if (t->left == NULL) {
x = t->right;
} else {
x = lub_bintree_splay(this, t->left, &key);
x->right = t->right;
}
/* set the new root */
this->root = x;
/* re-initialise the node control block for re-use */
lub_bintree_node_init(lub_bintree_getnode(this, clientnode));
}
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_remove.c
|
C
|
bsd
| 2,539
|
/*********************** -*- Mode: C -*- ***********************
* File : private.h
*---------------------------------------------------------------
* Description
* ===========
* This defines the private interface used internally by this component
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 08:45:01 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 9-Feb-2004 Graeme McKerrell
* modified compare MACRO
* 28-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include "lub/bintree.h"
/*************************************************************
* PRIVATE OPERATIONS
************************************************************* */
/*------------------------------------------------------------ */
/* This is the operation which performs a top-down splay. It is
* the core workhorse for this tree implementation.
*
* tree - the instance to invoke this operation upon
* t - the root node to splay to.
* key - the value with which to splay
*/
extern lub_bintree_node_t *lub_bintree_splay(const lub_bintree_t * tree,
lub_bintree_node_t * t,
const void *key);
/*------------------------------------------------------------ */
/* This operation converts a "node" into a "clientnode"
* subtracting the offset gives the base pointer to the node
*
* this - the tree to invoke this operation upon
* node - the node to convert
*/
#define lub_bintree_getclientnode(this,node)\
(void *)(((char*)node) - this->node_offset)
/*------------------------------------------------------------ */
/* This operation converts a "clientnode" into a "node"
* adding the offset gives the base pointer to the node
*
* this - the tree to invoke this operation upon
* clientnode - the clientnode to convert
*/
#define lub_bintree_getnode(this,clientnode)\
(lub_bintree_node_t *)(((char*)clientnode) + this->node_offset) /*lint -e826 */
/*------------------------------------------------------------ */
/* This operation compares a key with a "node"
* it returns
* <0 if key < node
* 0 if key == node
* >0 if key > node
*
* this - the tree to invoke this operation upon
* node - the "node" to compare
* key - the key to compare
*/
#define lub_bintree_compare(this,node,key)\
(this)->compareFn(lub_bintree_getclientnode(this,node),key)
/*------------------------------------------------------------ */
|
zzysjtu-klish
|
lub/bintree/private.h
|
C
|
bsd
| 2,843
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_find.c
*---------------------------------------------------------------
* Description
* ===========
* This operation searches the specified "tree" for a "clientnode"
* which matches the specified "key"
*
* tree - the "tree" instance to invoke this operation upon
* key - the "key" to search with
*
* RETURNS
* "clientnode" instance or NULL if no node is found.
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 10:29:54 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 27-Feb-2004 Graeme McKerrell
* Fixed to account for empty tree
* 9-Feb-2004 Graeme McKerrell
* update to use new node,key comparison ordering
* 28-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include "private.h"
/*--------------------------------------------------------- */
void *lub_bintree_find(lub_bintree_t * this, const void *clientkey)
{
this->root = lub_bintree_splay(this, this->root, clientkey);
if (NULL != this->root) {
if (lub_bintree_compare(this, this->root, clientkey) == 0)
return lub_bintree_getclientnode(this, this->root);
}
return NULL;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_find.c
|
C
|
bsd
| 1,711
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_node_init.c
*---------------------------------------------------------------
* Description
* ===========
* This operation is called to initialise a "clientnode" ready for
* insertion into a tree. This is only required once after the memory
* for a node has been allocated.
*
* tree - the tree instance to invoke this operation upon
* clientnode - the node to initialise.
*
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 09:57:06 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 27-Feb-2004 Graeme McKerrell
* Updated to simplify the initialisation of nodes
* 28-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include <assert.h>
#include "private.h"
/*--------------------------------------------------------- */
void lub_bintree_node_init(lub_bintree_node_t * node)
{
assert(node);
if (node) {
node->left = NULL;
node->right = NULL;
}
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_node_init.c
|
C
|
bsd
| 1,516
|
/*********************** -*- Mode: C -*- ***********************
* File : bintree_iterator_next.c
*---------------------------------------------------------------
* Description
* ===========
* This operation returns the next "clientnode" in an iteration.
*
* iter - the iterator instance to invoke this operation upon.
*
* RETURNS
* "clientnode" instance or NULL if the iteration has reached the end of the
* tree.
*---------------------------------------------------------------
* Author : Graeme McKerrell
* Created On : Wed Jan 28 10:34:26 2004
* Status : TESTED
*---------------------------------------------------------------
* HISTORY
* 7-Dec-2004 Graeme McKerrell
* Renamed to the "lub_" namespace
* 5-May-2004 Graeme McKerrell
* updates following review
* 9-Feb-2004 Graeme McKerrell
* updated to use new key structure
* 28-Jan-2004 Graeme McKerrell
* Initial version
*---------------------------------------------------------------
* Copyright (C) 2004 3Com Corporation. All Rights Reserved.
**************************************************************** */
#include "private.h"
/*--------------------------------------------------------- */
void *lub_bintree_iterator_next(lub_bintree_iterator_t * this)
{
void *clientnode = lub_bintree_findnext(this->tree, &this->key);
/* make sure that next time we've move onward */
lub_bintree_iterator_init(this, this->tree, clientnode);
return clientnode;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
lub/bintree/bintree_iterator_next.c
|
C
|
bsd
| 1,563
|
/*
* system.h
*
*/
#ifndef _lub_system_h
#define _lub_system_h
#include <stddef.h>
#include "lub/c_decl.h"
#include "lub/types.h"
#include "lub/argv.h"
_BEGIN_C_DECL bool_t lub_system_test(int argc, char **argv);
bool_t lub_system_argv_test(const lub_argv_t * argv);
bool_t lub_system_line_test(const char *line);
char *lub_system_tilde_expand(const char *path);
_END_C_DECL
#endif /* _lub_system_h */
|
zzysjtu-klish
|
lub/system.h
|
C
|
bsd
| 412
|
/*
* dump.h
*/
/**
\ingroup lub
\defgroup lub_dump dump
@{
\brief This utility provides a simple hierachical debugging mechanism.
By indenting and undenting the output, printing nested debug messages is made
easy.
*/
#ifndef _lub_dump_h
#define _lub_dump_h
#include <stdarg.h>
/*=====================================
* DUMP INTERFACE
*===================================== */
/**
* This operation behaves identically to the standard printf() function
* with the exception that the offset at the begining of the line is
* determined by the current indent settings.
* \pre
* - none
*
* \return
* The number of characters sent to stdout.
*
* \post
* - The formatted message will be sent to stdout.
*/
/*lint -esym(534,lub_dump_printf) Ignoring return value of function */
int lub_dump_printf(
/**
* printf-like format string
*/
const char *fmt, ...
);
/**
* This operation indicates that the offset for messages should be increased by
* one level.
*
* \pre
* - none
*
* \post
* - An indentation divider will be sent to stdout to emphasise the change
* in offset.
* - Subsequent calls to lub_dump_printf() will output at this new offset.
* - Client may call lub_undent() to restore offset.
*/
void lub_dump_indent(void);
/**
* This operation indicates that the offset for messages should be decreased by
* one level.
*
* \pre
* - lub_dump_indent() should have been called at least one more time than
* this function.
*
* \post
* - An indentation divider will be sent to stdout to emphasise the change
* in offset.
* - Subsequent calls to lub_dump_printf() will output at this new offset.
*/
void lub_dump_undent(void);
#endif /* _lub_dump_h */
/** @} lub_dump */
|
zzysjtu-klish
|
lub/dump.h
|
C
|
bsd
| 1,758
|
/*
* c_decl.h
*
* a simple set of macros to ease declaration of C interfaces.
*/
/**
\ingroup lub
\defgroup lub_c_decl C linkage macros
@{
These two macros are used to simplify the declaration of C-linkage code.
Rather than worry about preprocessor directives similar to
\code
#ifdef __cplusplus
extern "C" {
#endif
int foobar(void);
#ifdef __cplusplus
}
#endif
\endcode
you simply need to use the _BEGIN_C_DECL and _END_C_DECL macros instead.
\code
#include "lub/c_decl.h"
_BEGIN_C_DECL
int foobar(void);
_END_C_DECL
\endcode
*/
#ifndef _lub_c_decl_h
#define _lub_c_decl_h
#ifdef __cplusplus
#define _BEGIN_C_DECL extern "C" {
#define _END_C_DECL }
#else /* not __cplusplus */
#define _BEGIN_C_DECL
#define _END_C_DECL
#endif /* not __cplusplus */
/** @} */
#endif /* _lub_c_decl_h */
|
zzysjtu-klish
|
lub/c_decl.h
|
C
|
bsd
| 814
|
#
# Copyright (C) 2012 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
PKG_NAME:=klish
PKG_VERSION:=1.5.4
PKG_RELEASE:=1
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.bz2
PKG_SOURCE_URL:=http://klish.googlecode.com/files
PKG_MD5SUM:=c98a1c65f7538c3f4687c6f8039295df
PKG_INSTALL:=1
include $(INCLUDE_DIR)/package.mk
define Package/klish/default
SECTION:=utils
CATEGORY:=Utilities
TITLE:=Kommand Line Interface SHell ($(1))
URL:=http://code.google.com/p/klish/
endef
define Package/klish
$(call Package/klish/default,main tool)
DEPENDS:=+libstdcpp
endef
define Package/konf
$(call Package/klish/default,konf tool)
DEPENDS:=klish
endef
define Package/klish/description
The klish is a framework for implementing a CISCO-like CLI on a UNIX
systems. It is configurable by XML files. The KLISH stands for Kommand
Line Interface Shell.
The klish is a fork of clish 0.7.3 developed by Graeme McKerrell.
It defines new features but it's compatible (as much as possible) with
clish's XML configuration files.
klish is able to run using clish XML configuration files although
current clish users may expect some changes in behavior.
endef
define Package/konf/description
The klish is a framework for implementing a CISCO-like CLI on a UNIX
systems. It is configurable by XML files. The KLISH stands for Kommand
Line Interface Shell.
Konf and konfd are klish utilities that are used to store configuration
informations in a way which is similar to what's found on CISCO devices.
More information about these tools is to be found on the klish web site.
endef
define Package/klish/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/clish $(1)/usr/bin/
$(INSTALL_DIR) $(1)/usr/lib
$(CP) $(PKG_INSTALL_DIR)/usr/lib/*.so* $(1)/usr/lib/
endef
define Package/konf/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/konf $(1)/usr/bin/
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/konfd $(1)/usr/bin/
$(INSTALL_DIR) $(1)/usr/lib
$(CP) $(PKG_INSTALL_DIR)/usr/lib/libkonf.so* $(1)/usr/lib/
$(CP) $(PKG_INSTALL_DIR)/usr/lib/liblub.so* $(1)/usr/lib/
endef
$(eval $(call BuildPackage,klish))
$(eval $(call BuildPackage,konf))
define Package/klish-xml-files
SECTION:=utils
CATEGORY:=Utilities
DEPENDS:=klish
TITLE:=klish sample XML files
URL:=http://code.google.com/p/klish/
endef
define Package/klish-xml-files/description
This is a set of sample XML files for klish. This specific sample set
is compatible with the original clish.
endef
define Package/klish-xml-files/install
$(INSTALL_DIR) $(1)/etc/clish
$(CP) $(PKG_BUILD_DIR)/xml-examples/clish $(1)/etc/clish/
endef
$(eval $(call BuildPackage,klish-xml-files))
|
zzysjtu-klish
|
contrib/openwrt/Makefile
|
Makefile
|
bsd
| 2,849
|
#############################################################
#
# klish
#
#############################################################
ifeq ($(BR2_PACKAGE_KLISH_SVN),y)
KLISH_VERSION:=HEAD
KLISH_SITE:=http://klish.googlecode.com/svn/trunk
KLISH_SITE_METHOD:=svn
else
KLISH_VERSION = 1.6.0
KLISH_SOURCE = klish-$(KLISH_VERSION).tar.bz2
KLISH_SITE = http://klish.googlecode.com/files
endif
KLISH_INSTALL_STAGING = YES
KLISH_INSTALL_TARGET = YES
KLISH_CONF_OPT = --disable-gpl --without-tcl
$(eval $(call AUTOTARGETS,package,klish))
|
zzysjtu-klish
|
contrib/buildroot/klish.mk
|
Makefile
|
bsd
| 534
|
#!/bin/sh
# Check for missing binaries
BIN=/usr/bin/konfd
test -x $BIN || exit 5
PID=/var/run/konfd.pid
case "$1" in
start)
echo "Starting konfd daemon..."
test -r $PID && { echo "The service is already running."; exit 1; }
$BIN -p $PID
;;
stop)
echo "Stopping konfd daemon..."
test ! -r $PID && { echo "The service is not running."; exit 1; }
kill $(cat $PID)
;;
*)
echo "Usage: $0 {start|stop}"
exit 1
;;
esac
|
zzysjtu-klish
|
contrib/konfd.init
|
Shell
|
bsd
| 426
|
/*
* callback_log.c
*
* Callback hook to log users's commands
*/
#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <sys/types.h>
#include <pwd.h>
#include "internal.h"
#define SYSLOG_IDENT "klish"
#define SYSLOG_FACILITY LOG_LOCAL0
/*--------------------------------------------------------- */
int clish_log_callback(clish_context_t *context, const char *line,
int retcode)
{
clish_shell_t *this = context->shell;
struct passwd *user = NULL;
char *uname = "unknown";
/* Initialization */
if (!line) {
openlog(SYSLOG_IDENT, LOG_PID, SYSLOG_FACILITY);
return 0;
}
/* Log the given line */
if ((user = clish_shell__get_user(this)))
uname = user->pw_name;
syslog(LOG_INFO, "(%s) %s : %d", uname, line, retcode);
return 0;
}
|
zzysjtu-klish
|
clish/callback_log.c
|
C
|
bsd
| 766
|
#ifndef _clish_var_h
#define _clish_var_h
#include "lub/types.h"
#include "lub/bintree.h"
#include "clish/action.h"
typedef struct clish_var_s clish_var_t;
/*=====================================
* VAR INTERFACE
*===================================== */
/*-----------------
* meta functions
*----------------- */
int clish_var_bt_compare(const void *clientnode, const void *clientkey);
void clish_var_bt_getkey(const void *clientnode, lub_bintree_key_t * key);
size_t clish_var_bt_offset(void);
clish_var_t *clish_var_new(const char *name);
/*-----------------
* methods
*----------------- */
void clish_var_delete(clish_var_t *instance);
void clish_var_dump(const clish_var_t *instance);
/*-----------------
* attributes
*----------------- */
const char *clish_var__get_name(const clish_var_t *instance);
void clish_var__set_dynamic(clish_var_t *instance, bool_t defval);
bool_t clish_var__get_dynamic(const clish_var_t *instance);
void clish_var__set_value(clish_var_t *instance, const char *value);
char *clish_var__get_value(const clish_var_t *instance);
clish_action_t *clish_var__get_action(const clish_var_t *instance);
void clish_var__set_saved(clish_var_t *instance, const char *value);
char *clish_var__get_saved(const clish_var_t *instance);
#endif /* _clish_var_h */
|
zzysjtu-klish
|
clish/var.h
|
C
|
bsd
| 1,291
|
/*
* shell.h
*/
/**
\ingroup clish
\defgroup clish_shell shell
@{
\brief This class represents the top level container for a CLI session.
*/
#ifndef _clish_shell_h
#define _clish_shell_h
#include <stdio.h>
#include <sys/types.h>
#include <pwd.h>
#include "lub/c_decl.h"
#include "lub/types.h"
#include "lub/argv.h"
#include "tinyrl/tinyrl.h"
#include "clish/view.h"
#include "clish/ptype.h"
#include "clish/var.h"
#include "konf/net.h"
#define CLISH_LOCK_PATH "/tmp/clish.lock"
#define CLISH_LOCK_WAIT 20
typedef struct clish_shell_s clish_shell_t;
/* This is used to hold context during callbacks */
struct clish_context_s {
clish_shell_t *shell;
const clish_command_t *cmd;
clish_pargv_t *pargv;
};
typedef struct clish_context_s clish_context_t;
typedef enum {
SHELL_STATE_OK = 0,
SHELL_STATE_UNKNOWN = 1,
SHELL_STATE_IO_ERROR = 2,
SHELL_STATE_SCRIPT_ERROR = 3,/* Script execution error */
SHELL_STATE_SYNTAX_ERROR = 4, /* Illegal line entered */
SHELL_STATE_SYSTEM_ERROR = 5, /* Some internal system error */
SHELL_STATE_INITIALISING = 6,
SHELL_STATE_HELPING = 7,
SHELL_STATE_EOF = 8, /* EOF of input stream */
SHELL_STATE_CLOSING = 9
} clish_shell_state_t;
typedef enum {
SHELL_VAR_NONE, /* Nothing to escape */
SHELL_VAR_ACTION, /* Variable expanding for ACTION script */
SHELL_VAR_REGEX /* Variable expanding for regex usage */
} clish_shell_var_t;
_BEGIN_C_DECL
/*=====================================
* SHELL INTERFACE
*===================================== */
/**
* A hook function used during the spawning of a new shell.
*
* This will be invoked from the context of the spawned shell's thread
* and will be invoked just after the shell instance is created.
*
* This enables the client-specific initialisation of the spawned shell's
* thread
* e.g. to map the I/O streams, authenticate a user.
*
* N.B. It is possible for a client to have this invoked multiple times
* if the user is spawning new shells using a commmand which uses the
* "clish_spawn" builtin function. Hence the client should remember the
* shell which first calls this function, and only assign resource (e.g.
* setting up a script interpreter) for that call.
*
* \return
* - BOOL_TRUE if everything is OK
* - BOOL_FALSE if the shell should be immediately shut down.
*
*/
typedef bool_t clish_shell_init_fn_t(
/**
* The shell instance which invoked this call
*/
const clish_shell_t * shell);
/**
* A hook function used during the shutting down of a spawned shell
*
* This will be invoked from the context of the spawned shell's thread
* and will be invoked just before the shell is destroyed.
*
* This enables the client-specific finalisation to occur.
* e.g. releasing any resource held by the cookie,
* shutting down telnet connections
*
* NB. This function may be called multiple times if a user is spawning
* new commands (via the "clish_spawn" builtin command), hence should use
* the reference to the root shell (remembered by the first call to clish_shell_init_fn_t callback)
* to signal when the cleanup should occur.
*/
typedef void clish_shell_fini_fn_t(
/**
* The shell instance which invoked this call
*/
const clish_shell_t * shell);
/**
* A hook function used to indicate a command line has been executed and the
* shell is about to prompt for the next command.
*
* This will be invoked from the context of the spawned shell's thread
* and will be called once an ACTION has been performed.
*
* A client may use this as a periodic indicator of CLI activity,
* e.g. to manage session timeouts. In addition any required logging of
* commands may be performed.
*/
typedef void clish_shell_cmd_line_fn_t(
/**
* The shell instance which invoked this call
*/
clish_context_t *context,
/**
* The text of the command line entered
*/
const char *cmd_line);
/**
* A hook function used to invoke the script associated with a command
*
* This will be invoked from the context of the spawned shell's thread
* and will be invoked with the ACTION script which is to be performed.
*
* The clish component will only pass down a call when a command has been
* correctly input.
*
* The client may choose to implement invocation of the script in a number of
* ways, which may include forking a sub-process or thread. It is important
* that the call doesn't return until the script has been fully evaluated.
*
* \return
* - Retval (int)
*
* \post
* - If the script executes successfully then any "view" tag associated with the
* command will be honored. i.e. the CLI will switch to the new view
*/
typedef int clish_shell_script_fn_t(
clish_context_t *context,
clish_action_t *action,
const char *script,
char **out);
/**
* A hook function used to control config file write
*
*/
typedef bool_t clish_shell_config_fn_t(
clish_context_t *context);
/**
* A hook function used to control access for the current user.
*
* This will be invoked from the context of the spawned shell's thread
* and will be called during the parsing of the XML files.
*
* The clish component will only insert a command into a view if the access
* call is sucessfull.
*
* The client may choose to implement invocation of the script in a number of
* ways, which may include forking a sub-process or thread. It is important
* that the call doesn't return until the script has been fully evaluated.
*
* \return
* - BOOL_TRUE - if the user of the current CLISH session is permitted access
* - BOOL_FALSE - if the user of the current CLISH session is not permitted access
*
* \post
* - If access is granted then the associated command will be inserted into the
* appropriate view.
*/
typedef bool_t clish_shell_access_fn_t(
/**
* The shell instance which invoked this call
*/
const clish_shell_t * instance,
/**
* A textual string which describes a limitation for a command. This
* string typically may be the name of a user group, of which the
* current user must be a member to grant access to a command.
*/
const char *access);
typedef int clish_shell_log_fn_t(
clish_context_t *context,
const char *line, int retcode);
/**
* A hook function used as a built in command callback
*
* This will be invoked from the context of the spawned shell's thread
* and will be called during the execution of a builting command.
*
* A client may register any number of these callbacks in its
* clish_shell_builtin_cmds_t structure.
*
* \return
* - Retval (int)
*
*/
typedef int clish_shell_builtin_fn_t(
/**
* The shell instance which invoked this call
*/
clish_context_t *context,
/**
* A vector of textual command line arguments.
*/
const lub_argv_t * argv);
/**
* A client of libclish may provide some builtin commands which will be
* interpreted by the framework, instead of the client's script engine.
*/
typedef struct {
const char *name; /**< The textual name to be used in
* the 'builtin' XML attribute"
*/
clish_shell_builtin_fn_t *callback;
/**< The function to be invoked */
} clish_shell_builtin_t;
/**
* A client of libclish will provide hooks for the control of the CLI within
* a particular system.
* They will populate an instance of this structure and pass it into the
*/
typedef struct {
clish_shell_init_fn_t *init_fn; /* Initialisation call */
clish_shell_access_fn_t *access_fn; /* Access control call */
clish_shell_cmd_line_fn_t *cmd_line_fn; /* Command line logging call */
clish_shell_script_fn_t *script_fn; /* script evaluation call */
clish_shell_fini_fn_t *fini_fn; /* Finalisation call */
clish_shell_config_fn_t *config_fn; /* Config call */
clish_shell_log_fn_t *log_fn; /* Logging call */
const clish_shell_builtin_t *cmd_list; /* NULL terminated list */
} clish_shell_hooks_t;
/*-----------------
* meta functions
*----------------- */
clish_shell_t *clish_shell_new(const clish_shell_hooks_t * hooks,
void *cookie,
FILE * istream,
FILE * ostream,
bool_t stop_on_error);
/*-----------------
* methods
*----------------- */
/*
* Called to invoke the startup command for this shell
*/
int clish_shell_startup(clish_shell_t * instance);
void clish_shell_delete(clish_shell_t * instance);
clish_view_t *clish_shell_find_create_view(clish_shell_t * instance,
const char *name,
const char *prompt);
clish_ptype_t *clish_shell_find_create_ptype(clish_shell_t * instance,
const char *name,
const char *text,
const char *pattern,
clish_ptype_method_e method,
clish_ptype_preprocess_e preprocess);
clish_ptype_t *clish_shell_find_ptype(clish_shell_t *instance,
const char *name);
int clish_shell_xml_read(clish_shell_t * instance, const char *filename);
void clish_shell_help(clish_shell_t * instance, const char *line);
int clish_shell_exec_action(clish_action_t *action,
clish_context_t *context, char **out);
int clish_shell_execute(clish_context_t *context, char **out);
int clish_shell_forceline(clish_shell_t *instance, const char *line, char ** out);
int clish_shell_readline(clish_shell_t *instance, char ** out);
void clish_shell_dump(clish_shell_t * instance);
void clish_shell_close(clish_shell_t * instance);
/**
* Push the specified file handle on to the stack of file handles
* for this shell. The specified file will become the source of
* commands, until it is exhausted.
*
* \return
* BOOL_TRUE - the file was successfully associated with the shell.
* BOOL_FALSE - there was insufficient resource to associate this file.
*/
int clish_shell_push_file(clish_shell_t * instance, const char * fname,
bool_t stop_on_error);
int clish_shell_push_fd(clish_shell_t * instance, FILE * file,
bool_t stop_on_error);
void clish_shell_insert_var(clish_shell_t *instance, clish_var_t *var);
clish_var_t *clish_shell_find_var(clish_shell_t *instance, const char *name);
char *clish_shell_expand_var(const char *name, clish_context_t *context);
char *clish_shell_expand(const char *str, clish_shell_var_t vtype, clish_context_t *context);
/*-----------------
* attributes
*----------------- */
clish_view_t *clish_shell__get_view(const clish_shell_t * instance);
unsigned clish_shell__get_depth(const clish_shell_t * instance);
const char *clish_shell__get_viewid(const clish_shell_t * instance);
const char *clish_shell__get_overview(const clish_shell_t * instance);
tinyrl_t *clish_shell__get_tinyrl(const clish_shell_t * instance);
void *clish_shell__get_client_cookie(const clish_shell_t * instance);
void
clish_shell__set_pwd(clish_shell_t *instance, const char * line,
clish_view_t * view, char * viewid, clish_context_t *context);
char *clish_shell__get_pwd_line(const clish_shell_t * instance,
unsigned int index);
char *clish_shell__get_pwd_full(const clish_shell_t * instance, unsigned depth);
clish_view_t *clish_shell__get_pwd_view(const clish_shell_t * instance,
unsigned int index);
konf_client_t *clish_shell__get_client(const clish_shell_t * instance);
FILE *clish_shell__get_istream(const clish_shell_t * instance);
FILE *clish_shell__get_ostream(const clish_shell_t * instance);
void clish_shell__set_lockfile(clish_shell_t * instance, const char * path);
char * clish_shell__get_lockfile(clish_shell_t * instance);
int clish_shell__set_socket(clish_shell_t * instance, const char * path);
void clish_shell_load_scheme(clish_shell_t * instance, const char * xml_path);
int clish_shell_loop(clish_shell_t * instance);
clish_shell_state_t clish_shell__get_state(const clish_shell_t * instance);
void clish_shell__set_state(clish_shell_t * instance,
clish_shell_state_t state);
void clish_shell__set_startup_view(clish_shell_t * instance, const char * viewname);
void clish_shell__set_startup_viewid(clish_shell_t * instance, const char * viewid);
void clish_shell__set_default_shebang(clish_shell_t * instance, const char * shebang);
const char * clish_shell__get_default_shebang(const clish_shell_t * instance);
const char * clish_shell__get_fifo(clish_shell_t * instance);
void clish_shell__set_interactive(clish_shell_t * instance, bool_t interactive);
bool_t clish_shell__get_interactive(const clish_shell_t * instance);
bool_t clish_shell__get_utf8(const clish_shell_t * instance);
void clish_shell__set_utf8(clish_shell_t * instance, bool_t utf8);
void clish_shell__set_timeout(clish_shell_t *instance, int timeout);
char *clish_shell__get_line(clish_context_t *context);
char *clish_shell__get_full_line(clish_context_t *context);
char *clish_shell__get_params(clish_context_t *context);
void clish_shell__set_log(clish_shell_t *instance, bool_t log);
bool_t clish_shell__get_log(const clish_shell_t *instance);
int clish_shell_wdog(clish_shell_t *instance);
void clish_shell__set_wdog_timeout(clish_shell_t *instance,
unsigned int timeout);
unsigned int clish_shell__get_wdog_timeout(const clish_shell_t *instance);
int clish_shell__save_history(const clish_shell_t *instance, const char *fname);
int clish_shell__restore_history(clish_shell_t *instance, const char *fname);
void clish_shell__stifle_history(clish_shell_t *instance, unsigned int stifle);
struct passwd *clish_shell__get_user(clish_shell_t *instance);
_END_C_DECL
#endif /* _clish_shell_h */
/** @} clish_shell */
|
zzysjtu-klish
|
clish/shell.h
|
C
|
bsd
| 13,595
|
/*
* nspace.h
*/
/**
\ingroup clish
\defgroup clish_nspace nspace
@{
\brief This class represents an instance of a namespace type.
Namespace instances are assocated with a view to make view's commands available
within current view.
*/
#ifndef _clish_nspace_h
#define _clish_nspace_h
typedef struct clish_nspace_s clish_nspace_t;
typedef enum {
CLISH_NSPACE_NONE,
CLISH_NSPACE_HELP,
CLISH_NSPACE_COMPLETION,
CLISH_NSPACE_CHELP
} clish_nspace_visibility_t;
#include <regex.h>
#include "clish/view.h"
/*=====================================
* NSPACE INTERFACE
*===================================== */
/*-----------------
* meta functions
*----------------- */
clish_nspace_t *clish_nspace_new(clish_view_t * view);
/*-----------------
* methods
*----------------- */
void clish_nspace_delete(clish_nspace_t * instance);
const clish_command_t *clish_nspace_find_next_completion(clish_nspace_t *
instance, const char *iter_cmd, const char *line,
clish_nspace_visibility_t field);
clish_command_t *clish_nspace_find_command(clish_nspace_t * instance, const char *name);
void clish_nspace_dump(const clish_nspace_t * instance);
clish_command_t * clish_nspace_create_prefix_cmd(clish_nspace_t * instance,
const char * name, const char * help);
void clish_nspace_clean_proxy(clish_nspace_t * instance);
/*-----------------
* attributes
*----------------- */
const char *clish_nspace__get_prefix(const clish_nspace_t * instance);
const regex_t *clish_nspace__get_prefix_regex(const clish_nspace_t * instance);
bool_t clish_nspace__get_help(const clish_nspace_t * instance);
bool_t clish_nspace__get_completion(const clish_nspace_t * instance);
bool_t clish_nspace__get_context_help(const clish_nspace_t * instance);
bool_t clish_nspace__get_inherit(const clish_nspace_t * instance);
bool_t
clish_nspace__get_visibility(const clish_nspace_t * instance,
clish_nspace_visibility_t field);
clish_view_t *clish_nspace__get_view(const clish_nspace_t * instance);
void clish_nspace__set_prefix(clish_nspace_t * instance, const char *prefix);
void clish_nspace__set_help(clish_nspace_t * instance, bool_t help);
void clish_nspace__set_completion(clish_nspace_t * instance, bool_t help);
void clish_nspace__set_context_help(clish_nspace_t * instance, bool_t help);
void clish_nspace__set_inherit(clish_nspace_t * instance, bool_t inherit);
#endif /* _clish_nspace_h */
/** @} clish_nspace */
|
zzysjtu-klish
|
clish/nspace.h
|
C
|
bsd
| 2,411
|
/*
* nspace.c
*
* This file provides the implementation of the "nspace" class
*/
#include "private.h"
#include "lub/string.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <regex.h>
#include <ctype.h>
/*---------------------------------------------------------
* PRIVATE METHODS
*--------------------------------------------------------- */
static void clish_nspace_init(clish_nspace_t * this, clish_view_t * view)
{
this->view = view;
/* set up defaults */
this->prefix = NULL;
this->help = BOOL_FALSE;
this->completion = BOOL_TRUE;
this->context_help = BOOL_FALSE;
this->inherit = BOOL_TRUE;
this->prefix_cmd = NULL;
/* initialise the tree of commands links for this nspace */
lub_bintree_init(&this->tree,
clish_command_bt_offset(),
clish_command_bt_compare, clish_command_bt_getkey);
}
/*--------------------------------------------------------- */
static void clish_nspace_fini(clish_nspace_t * this)
{
clish_command_t *cmd;
/* deallocate the memory for this instance */
if (this->prefix) {
free(this->prefix);
regfree(&this->prefix_regex);
}
/* delete each command link held by this nspace */
while ((cmd = lub_bintree_findfirst(&this->tree))) {
/* remove the command from the tree */
lub_bintree_remove(&this->tree, cmd);
/* release the instance */
clish_command_delete(cmd);
}
/* Delete prefix pseudo-command */
if (this->prefix_cmd) {
clish_command_delete(this->prefix_cmd);
this->prefix_cmd = NULL;
}
}
/*--------------------------------------------------------- */
clish_command_t * clish_nspace_create_prefix_cmd(clish_nspace_t * this,
const char * name, const char * help)
{
if (this->prefix_cmd) {
clish_command_delete(this->prefix_cmd);
this->prefix_cmd = NULL;
}
return (this->prefix_cmd = clish_command_new(name, help));
}
/*--------------------------------------------------------- */
static clish_command_t *clish_nspace_find_create_command(clish_nspace_t * this,
const char *prefix, const clish_command_t * ref)
{
clish_command_t *cmd;
char *name = NULL;
const char *help = NULL;
clish_command_t *tmp = NULL;
const char *str = NULL;
assert(prefix);
if (!ref) {
assert(this->prefix_cmd);
name = lub_string_dup(prefix);
ref = this->prefix_cmd;
help = clish_command__get_text(this->prefix_cmd);
} else {
lub_string_catn(&name, prefix, strlen(prefix));
lub_string_catn(&name, " ", 1);
lub_string_catn(&name, clish_command__get_name(ref),
strlen(clish_command__get_name(ref)));
help = clish_command__get_text(ref);
}
/* The command is cached already */
if ((cmd = lub_bintree_find(&this->tree, name))) {
free(name);
return cmd;
}
cmd = clish_command_new_link(name, help, ref);
free(name);
assert(cmd);
/* The command was created dynamically */
clish_command__set_dynamic(cmd, BOOL_TRUE);
/* Delete proxy commands with another prefixes */
tmp = lub_bintree_findfirst(&this->tree);
if (tmp)
str = clish_command__get_name(tmp);
if (str && (lub_string_nocasestr(str, prefix) != str)) {
do {
lub_bintree_remove(&this->tree, tmp);
clish_command_delete(tmp);
} while ((tmp = lub_bintree_findfirst(&this->tree)));
}
/* Insert command link into the tree */
if (-1 == lub_bintree_insert(&this->tree, cmd)) {
clish_command_delete(cmd);
cmd = NULL;
}
return cmd;
}
/*---------------------------------------------------------
* PUBLIC META FUNCTIONS
*--------------------------------------------------------- */
clish_nspace_t *clish_nspace_new(clish_view_t * view)
{
clish_nspace_t *this = malloc(sizeof(clish_nspace_t));
if (this)
clish_nspace_init(this, view);
return this;
}
/*---------------------------------------------------------
* PUBLIC METHODS
*--------------------------------------------------------- */
void clish_nspace_delete(clish_nspace_t * this)
{
clish_nspace_fini(this);
free(this);
}
/*--------------------------------------------------------- */
static const char *clish_nspace_after_prefix(const regex_t *prefix_regex,
const char *line, char **real_prefix)
{
const char *in_line = NULL;
regmatch_t pmatch[1];
int res;
if (!line)
return NULL;
/* Compile regular expression */
res = regexec(prefix_regex, line, 1, pmatch, 0);
if (res || (0 != pmatch[0].rm_so))
return NULL;
/* Empty match */
if (0 == pmatch[0].rm_eo)
return NULL;
in_line = line + pmatch[0].rm_eo;
lub_string_catn(real_prefix, line, pmatch[0].rm_eo);
return in_line;
}
/*--------------------------------------------------------- */
clish_command_t *clish_nspace_find_command(clish_nspace_t * this, const char *name)
{
clish_command_t *cmd = NULL, *retval = NULL;
clish_view_t *view = clish_nspace__get_view(this);
const char *in_line;
char *real_prefix = NULL;
if (!clish_nspace__get_prefix(this))
return clish_view_find_command(view, name, this->inherit);
if (!(in_line = clish_nspace_after_prefix(
clish_nspace__get_prefix_regex(this), name, &real_prefix)))
return NULL;
/* If prefix is followed by space */
if (in_line[0] == ' ')
in_line++;
if (in_line[0] != '\0') {
cmd = clish_view_find_command(view, in_line, this->inherit);
if (!cmd) {
lub_string_free(real_prefix);
return NULL;
}
}
retval = clish_nspace_find_create_command(this, real_prefix, cmd);
lub_string_free(real_prefix);
return retval;
}
/*--------------------------------------------------------- */
const clish_command_t *clish_nspace_find_next_completion(clish_nspace_t * this,
const char *iter_cmd, const char *line,
clish_nspace_visibility_t field)
{
const clish_command_t *cmd = NULL, *retval = NULL;
clish_view_t *view = clish_nspace__get_view(this);
const char *in_iter = "";
const char *in_line;
char *real_prefix = NULL;
if (!clish_nspace__get_prefix(this))
return clish_view_find_next_completion(view, iter_cmd,
line, field, this->inherit);
if (!(in_line = clish_nspace_after_prefix(
clish_nspace__get_prefix_regex(this), line, &real_prefix)))
return NULL;
if (in_line[0] != '\0') {
/* If prefix is followed by space */
if (!isspace(in_line[0])) {
lub_string_free(real_prefix);
return NULL;
}
in_line++;
if (iter_cmd &&
(lub_string_nocasestr(iter_cmd, real_prefix) == iter_cmd) &&
(lub_string_nocasecmp(iter_cmd, real_prefix)))
in_iter = iter_cmd + strlen(real_prefix) + 1;
cmd = clish_view_find_next_completion(view,
in_iter, in_line, field, this->inherit);
if (!cmd) {
lub_string_free(real_prefix);
return NULL;
}
}
/* If prefix was already returned. */
if (!cmd && iter_cmd && !lub_string_nocasecmp(iter_cmd, real_prefix)) {
lub_string_free(real_prefix);
return NULL;
}
retval = clish_nspace_find_create_command(this, real_prefix, cmd);
lub_string_free(real_prefix);
if (retval && iter_cmd &&
lub_string_nocasecmp(iter_cmd, clish_command__get_name(retval)) > 0)
return NULL;
return retval;
}
/*--------------------------------------------------------- */
void clish_nspace_clean_proxy(clish_nspace_t * this)
{
clish_command_t *cmd = NULL;
/* Recursive proxy clean */
clish_view_clean_proxy(this->view);
/* Delete each command proxy held by this nspace */
while ((cmd = lub_bintree_findfirst(&this->tree))) {
/* remove the command from the tree */
lub_bintree_remove(&this->tree, cmd);
/* release the instance */
clish_command_delete(cmd);
}
}
/*---------------------------------------------------------
* PUBLIC ATTRIBUTES
*--------------------------------------------------------- */
clish_view_t *clish_nspace__get_view(const clish_nspace_t * this)
{
return this->view;
}
/*--------------------------------------------------------- */
void clish_nspace__set_prefix(clish_nspace_t * this, const char *prefix)
{
int res = 0;
assert(!this->prefix);
res = regcomp(&this->prefix_regex, prefix, REG_EXTENDED | REG_ICASE);
assert(!res);
this->prefix = lub_string_dup(prefix);
}
/*--------------------------------------------------------- */
const char *clish_nspace__get_prefix(const clish_nspace_t * this)
{
return this->prefix;
}
/*--------------------------------------------------------- */
const regex_t *clish_nspace__get_prefix_regex(const clish_nspace_t * this)
{
if (!this->prefix)
return NULL;
return &this->prefix_regex;
}
/*--------------------------------------------------------- */
void clish_nspace__set_help(clish_nspace_t * this, bool_t help)
{
this->help = help;
}
/*--------------------------------------------------------- */
bool_t clish_nspace__get_help(const clish_nspace_t * this)
{
return this->help;
}
/*--------------------------------------------------------- */
void clish_nspace__set_completion(clish_nspace_t * this, bool_t completion)
{
this->completion = completion;
}
/*--------------------------------------------------------- */
bool_t clish_nspace__get_completion(const clish_nspace_t * this)
{
return this->completion;
}
/*--------------------------------------------------------- */
void clish_nspace__set_context_help(clish_nspace_t * this, bool_t context_help)
{
this->context_help = context_help;
}
/*--------------------------------------------------------- */
bool_t clish_nspace__get_context_help(const clish_nspace_t * this)
{
return this->context_help;
}
/*--------------------------------------------------------- */
void clish_nspace__set_inherit(clish_nspace_t * this, bool_t inherit)
{
this->inherit = inherit;
}
/*--------------------------------------------------------- */
bool_t clish_nspace__get_inherit(const clish_nspace_t * this)
{
return this->inherit;
}
/*--------------------------------------------------------- */
bool_t clish_nspace__get_visibility(const clish_nspace_t * instance,
clish_nspace_visibility_t field)
{
bool_t result = BOOL_FALSE;
switch (field) {
case CLISH_NSPACE_HELP:
result = clish_nspace__get_help(instance);
break;
case CLISH_NSPACE_COMPLETION:
result = clish_nspace__get_completion(instance);
break;
case CLISH_NSPACE_CHELP:
result = clish_nspace__get_context_help(instance);
break;
default:
break;
}
return result;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
clish/nspace/nspace.c
|
C
|
bsd
| 10,174
|
/*
* nspace.h
*/
#include <regex.h>
#include "clish/nspace.h"
/*---------------------------------------------------------
* PRIVATE TYPES
*--------------------------------------------------------- */
struct clish_nspace_s {
lub_bintree_t tree; /* Tree of command links */
clish_view_t *view; /* The view to import commands from */
char *prefix; /* if non NULL the prefix for imported commands */
regex_t prefix_regex;
bool_t help;
bool_t completion;
bool_t context_help;
bool_t inherit;
clish_command_t * prefix_cmd;
};
|
zzysjtu-klish
|
clish/nspace/private.h
|
C
|
bsd
| 536
|
/*
* nspace_dump.c
*/
#include "private.h"
#include "lub/dump.h"
/*--------------------------------------------------------- */
void clish_nspace_dump(const clish_nspace_t * this)
{
lub_dump_printf("nspace(%p)\n", this);
lub_dump_indent();
lub_dump_printf("view : %s\n",
clish_view__get_name(this->view));
lub_dump_printf("prefix : %s\n",
this->prefix ? this->prefix : "(null)");
lub_dump_printf("help : %s\n", this->help ? "true" : "false");
lub_dump_printf("completion : %s\n",
this->completion ? "true" : "false");
lub_dump_printf("context_help : %s\n",
this->context_help ? "true" : "false");
lub_dump_printf("inherit : %s\n",
this->inherit ? "true" : "false");
lub_dump_undent();
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
clish/nspace/nspace_dump.c
|
C
|
bsd
| 808
|
/*
* param.c
*
* This file provides the implementation of the "param" class
*/
#include "private.h"
#include "lub/string.h"
#include "clish/types.h"
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*---------------------------------------------------------
* PRIVATE METHODS
*--------------------------------------------------------- */
static void clish_param_init(clish_param_t *this, const char *name,
const char *text, clish_ptype_t *ptype)
{
/* initialise the help part */
this->name = lub_string_dup(name);
this->text = lub_string_dup(text);
this->ptype = ptype;
/* set up defaults */
this->defval = NULL;
this->mode = CLISH_PARAM_COMMON;
this->optional = BOOL_FALSE;
this->order = BOOL_FALSE;
this->value = NULL;
this->hidden = BOOL_FALSE;
this->test = NULL;
this->completion = NULL;
this->paramv = clish_paramv_new();
}
/*--------------------------------------------------------- */
static void clish_param_fini(clish_param_t * this)
{
/* deallocate the memory for this instance */
lub_string_free(this->defval);
lub_string_free(this->name);
lub_string_free(this->text);
lub_string_free(this->value);
lub_string_free(this->test);
lub_string_free(this->completion);
clish_paramv_delete(this->paramv);
}
/*---------------------------------------------------------
* PUBLIC META FUNCTIONS
*--------------------------------------------------------- */
clish_param_t *clish_param_new(const char *name, const char *text,
clish_ptype_t *ptype)
{
clish_param_t *this = malloc(sizeof(clish_param_t));
if (this)
clish_param_init(this, name, text, ptype);
return this;
}
/*---------------------------------------------------------
* PUBLIC METHODS
*--------------------------------------------------------- */
void clish_param_delete(clish_param_t * this)
{
clish_param_fini(this);
free(this);
}
/*--------------------------------------------------------- */
void clish_param_insert_param(clish_param_t * this, clish_param_t * param)
{
return clish_paramv_insert(this->paramv, param);
}
/*---------------------------------------------------------
* PUBLIC ATTRIBUTES
*--------------------------------------------------------- */
const char *clish_param__get_name(const clish_param_t * this)
{
if (!this)
return NULL;
return this->name;
}
/*--------------------------------------------------------- */
const char *clish_param__get_text(const clish_param_t * this)
{
return this->text;
}
/*--------------------------------------------------------- */
const char *clish_param__get_range(const clish_param_t * this)
{
return clish_ptype__get_range(this->ptype);
}
/*--------------------------------------------------------- */
clish_ptype_t *clish_param__get_ptype(const clish_param_t * this)
{
return this->ptype;
}
/*--------------------------------------------------------- */
void clish_param__set_default(clish_param_t * this, const char *defval)
{
assert(!this->defval);
this->defval = lub_string_dup(defval);
}
/*--------------------------------------------------------- */
const char *clish_param__get_default(const clish_param_t * this)
{
return this->defval;
}
/*--------------------------------------------------------- */
void clish_param__set_mode(clish_param_t * this, clish_param_mode_e mode)
{
assert(this);
this->mode = mode;
}
/*--------------------------------------------------------- */
clish_param_mode_e clish_param__get_mode(const clish_param_t * this)
{
return this->mode;
}
/*--------------------------------------------------------- */
char *clish_param_validate(const clish_param_t * this, const char *text)
{
if (CLISH_PARAM_SUBCOMMAND == clish_param__get_mode(this)) {
if (lub_string_nocasecmp(clish_param__get_value(this), text))
return NULL;
}
return clish_ptype_translate(this->ptype, text);
}
/*--------------------------------------------------------- */
void clish_param_help(const clish_param_t * this, clish_help_t *help)
{
const char *range = clish_ptype__get_range(this->ptype);
const char *name;
char *str = NULL;
if (CLISH_PARAM_SWITCH == clish_param__get_mode(this)) {
unsigned rec_paramc = clish_param__get_param_count(this);
clish_param_t *cparam;
unsigned i;
for (i = 0; i < rec_paramc; i++) {
cparam = clish_param__get_param(this, i);
if (!cparam)
break;
clish_param_help(cparam, help);
}
return;
}
if (CLISH_PARAM_SUBCOMMAND == clish_param__get_mode(this))
name = clish_param__get_value(this);
else
if (!(name = clish_ptype__get_text(this->ptype)))
name = clish_ptype__get_name(this->ptype);
lub_string_cat(&str, this->text);
if (range) {
lub_string_cat(&str, " (");
lub_string_cat(&str, range);
lub_string_cat(&str, ")");
}
lub_argv_add(help->name, name);
lub_argv_add(help->help, str);
lub_string_free(str);
lub_argv_add(help->detail, NULL);
}
/*--------------------------------------------------------- */
void clish_param_help_arrow(const clish_param_t * this, size_t offset)
{
fprintf(stderr, "%*c\n", (int)offset, '^');
}
/*--------------------------------------------------------- */
clish_param_t *clish_param__get_param(const clish_param_t * this,
unsigned index)
{
return clish_paramv__get_param(this->paramv, index);
}
/*--------------------------------------------------------- */
clish_paramv_t *clish_param__get_paramv(clish_param_t * this)
{
return this->paramv;
}
/*--------------------------------------------------------- */
unsigned int clish_param__get_param_count(const clish_param_t * this)
{
return clish_paramv__get_count(this->paramv);
}
/*--------------------------------------------------------- */
void clish_param__set_optional(clish_param_t * this, bool_t optional)
{
this->optional = optional;
}
/*--------------------------------------------------------- */
bool_t clish_param__get_optional(const clish_param_t * this)
{
return this->optional;
}
/*--------------------------------------------------------- */
void clish_param__set_order(clish_param_t * this, bool_t order)
{
this->order = order;
}
/*--------------------------------------------------------- */
bool_t clish_param__get_order(const clish_param_t * this)
{
return this->order;
}
/*--------------------------------------------------------- */
/* paramv methods */
/*--------------------------------------------------------- */
static void clish_paramv_init(clish_paramv_t * this)
{
this->paramc = 0;
this->paramv = NULL;
}
/*--------------------------------------------------------- */
static void clish_paramv_fini(clish_paramv_t * this)
{
unsigned i;
/* finalize each of the parameter instances */
for (i = 0; i < this->paramc; i++) {
clish_param_delete(this->paramv[i]);
}
/* free the parameter vector */
free(this->paramv);
this->paramc = 0;
}
/*--------------------------------------------------------- */
clish_paramv_t *clish_paramv_new(void)
{
clish_paramv_t *this = malloc(sizeof(clish_paramv_t));
if (this)
clish_paramv_init(this);
return this;
}
/*--------------------------------------------------------- */
void clish_paramv_delete(clish_paramv_t * this)
{
clish_paramv_fini(this);
free(this);
}
/*--------------------------------------------------------- */
void clish_paramv_insert(clish_paramv_t * this, clish_param_t * param)
{
size_t new_size = ((this->paramc + 1) * sizeof(clish_param_t *));
clish_param_t **tmp;
/* resize the parameter vector */
tmp = realloc(this->paramv, new_size);
if (tmp) {
this->paramv = tmp;
/* insert reference to the parameter */
this->paramv[this->paramc++] = param;
}
}
/*--------------------------------------------------------- */
clish_param_t *clish_paramv__get_param(const clish_paramv_t * this,
unsigned index)
{
clish_param_t *result = NULL;
if (index < this->paramc)
result = this->paramv[index];
return result;
}
/*--------------------------------------------------------- */
clish_param_t *clish_paramv_find_param(const clish_paramv_t * this,
const char *name)
{
clish_param_t *res = NULL;
unsigned int i;
for (i = 0; i < this->paramc; i++) {
if (!strcmp(clish_param__get_name(this->paramv[i]), name))
return this->paramv[i];
if ((res = clish_paramv_find_param(
clish_param__get_paramv(this->paramv[i]), name)))
return res;
}
return res;
}
/*--------------------------------------------------------- */
const char *clish_paramv_find_default(const clish_paramv_t * this,
const char *name)
{
clish_param_t *res = clish_paramv_find_param(this, name);
if (res)
return clish_param__get_default(res);
return NULL;
}
/*--------------------------------------------------------- */
unsigned int clish_paramv__get_count(const clish_paramv_t * this)
{
return this->paramc;
}
/*--------------------------------------------------------- */
void clish_param__set_value(clish_param_t * this, const char * value)
{
assert(!this->value);
this->value = lub_string_dup(value);
}
/*--------------------------------------------------------- */
char *clish_param__get_value(const clish_param_t * this)
{
if (this->value)
return this->value;
return this->name;
}
/*--------------------------------------------------------- */
void clish_param__set_hidden(clish_param_t * this, bool_t hidden)
{
this->hidden = hidden;
}
/*--------------------------------------------------------- */
bool_t clish_param__get_hidden(const clish_param_t * this)
{
return this->hidden;
}
/*--------------------------------------------------------- */
void clish_param__set_test(clish_param_t * this, const char *test)
{
assert(!this->test);
this->test = lub_string_dup(test);
}
/*--------------------------------------------------------- */
char *clish_param__get_test(const clish_param_t *this)
{
return this->test;
}
/*--------------------------------------------------------- */
void clish_param__set_completion(clish_param_t *this, const char *completion)
{
assert(!this->completion);
this->completion = lub_string_dup(completion);
}
/*--------------------------------------------------------- */
char *clish_param__get_completion(const clish_param_t *this)
{
return this->completion;
}
|
zzysjtu-klish
|
clish/param/param.c
|
C
|
bsd
| 10,132
|
/*
* param_dump.c
*/
#include "private.h"
#include "lub/dump.h"
/*--------------------------------------------------------- */
void clish_param_dump(const clish_param_t * this)
{
unsigned i;
char *mode;
lub_dump_printf("param(%p)\n", this);
lub_dump_indent();
lub_dump_printf("name : %s\n", this->name);
lub_dump_printf("text : %s\n", this->text);
lub_dump_printf("value : %s\n", this->value);
lub_dump_printf("ptype : %s\n", clish_ptype__get_name(this->ptype));
lub_dump_printf("default : %s\n",
this->defval ? this->defval : "(null)");
switch (this->mode) {
case CLISH_PARAM_COMMON:
mode = "COMMON";
break;
case CLISH_PARAM_SWITCH:
mode = "SWITCH";
break;
case CLISH_PARAM_SUBCOMMAND:
mode = "SUBCOMMAND";
break;
default:
mode = "Unknown";
break;
}
lub_dump_printf("mode : %s\n", mode);
lub_dump_printf("paramc : %d\n", clish_paramv__get_count(this->paramv));
lub_dump_printf("optional : %s\n",
this->optional ? "true" : "false");
lub_dump_printf("hidden : %s\n",
this->hidden ? "true" : "false");
lub_dump_printf("test : %s\n", this->test);
lub_dump_printf("completion : %s\n", this->completion);
/* Get each parameter to dump their details */
for (i = 0; i < clish_paramv__get_count(this->paramv); i++) {
clish_param_dump(clish_param__get_param(this, i));
}
lub_dump_undent();
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
clish/param/param_dump.c
|
C
|
bsd
| 1,449
|
/*
* param.h
*/
#include "clish/param.h"
/*---------------------------------------------------------
* PRIVATE TYPES
*--------------------------------------------------------- */
struct clish_paramv_s {
unsigned paramc;
clish_param_t **paramv;
};
struct clish_param_s {
char *name;
char *text;
char *value;
clish_ptype_t *ptype; /* The type of this parameter */
char *defval; /* default value to use for this parameter */
clish_paramv_t *paramv;
clish_param_mode_e mode;
bool_t optional;
bool_t order;
bool_t hidden;
char *test; /* The condition to enable param */
char *completion; /* Possible completions */
};
|
zzysjtu-klish
|
clish/param/private.h
|
C
|
bsd
| 635
|
/*
* types.h
*/
#ifndef _clish_types_h
#define _clish_types_h
#include "lub/c_decl.h"
#include "lub/argv.h"
struct clish_help_s {
lub_argv_t *name;
lub_argv_t *help;
lub_argv_t *detail;
};
typedef struct clish_help_s clish_help_t;
#endif /* _clish_types_h */
|
zzysjtu-klish
|
clish/types.h
|
C
|
bsd
| 268
|
/*
* clish_config_callback.c
*
*
* Callback hook to execute config operations.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <assert.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <limits.h>
#include <string.h>
#include "internal.h"
#include "konf/net.h"
#include "konf/buf.h"
#include "konf/query.h"
#include "lub/string.h"
static int send_request(konf_client_t * client, char *command);
static unsigned short str2ushort(const char *str)
{
unsigned short num = 0;
if (str && (*str != '\0')) {
long val = 0;
char *endptr;
val = strtol(str, &endptr, 0);
if (endptr == str)
num = 0;
else if (val > 0xffff)
num = 0xffff;
else if (val < 0)
num = 0;
else
num = (unsigned)val;
}
return num;
}
/*--------------------------------------------------------- */
bool_t clish_config_callback(clish_context_t *context)
{
clish_shell_t *this = context->shell;
const clish_command_t *cmd = context->cmd;
clish_config_t *config;
char *command = NULL;
konf_client_t *client;
konf_buf_t *buf = NULL;
char *str = NULL;
char *tstr;
char tmp[PATH_MAX + 100];
clish_config_op_t op;
unsigned int num;
const char *escape_chars = lub_string_esc_quoted;
if (!this)
return BOOL_TRUE;
client = clish_shell__get_client(this);
if (!client)
return BOOL_TRUE;
config = clish_command__get_config(cmd);
op = clish_config__get_op(config);
switch (op) {
case CLISH_CONFIG_NONE:
return BOOL_TRUE;
case CLISH_CONFIG_SET:
/* Add set operation */
lub_string_cat(&command, "-s");
/* Add entered line */
tstr = clish_shell__get_line(context);
str = lub_string_encode(tstr, escape_chars);
lub_string_free(tstr);
lub_string_cat(&command, " -l \"");
lub_string_cat(&command, str);
lub_string_cat(&command, "\"");
lub_string_free(str);
/* Add splitter */
if (!clish_config__get_splitter(config))
lub_string_cat(&command, " -i");
/* Add unique */
if (!clish_config__get_unique(config))
lub_string_cat(&command, " -n");
break;
case CLISH_CONFIG_UNSET:
/* Add unset operation */
lub_string_cat(&command, "-u");
break;
case CLISH_CONFIG_DUMP:
/* Add dump operation */
lub_string_cat(&command, "-d");
/* Add filename */
str = clish_shell_expand(clish_config__get_file(config), SHELL_VAR_ACTION, context);
if (str) {
lub_string_cat(&command, " -f \"");
if (str[0] != '\0')
lub_string_cat(&command, str);
else
lub_string_cat(&command, "/tmp/running-config");
lub_string_cat(&command, "\"");
lub_string_free(str);
}
break;
default:
return BOOL_FALSE;
};
/* Add pattern */
if ((CLISH_CONFIG_SET == op) || (CLISH_CONFIG_UNSET == op)) {
tstr = clish_shell_expand(clish_config__get_pattern(config), SHELL_VAR_REGEX, context);
if (!tstr) {
lub_string_free(command);
return BOOL_FALSE;
}
str = lub_string_encode(tstr, escape_chars);
lub_string_free(tstr);
lub_string_cat(&command, " -r \"");
lub_string_cat(&command, str);
lub_string_cat(&command, "\"");
lub_string_free(str);
}
/* Add priority */
if (clish_config__get_priority(config) != 0) {
snprintf(tmp, sizeof(tmp) - 1, " -p 0x%x",
clish_config__get_priority(config));
tmp[sizeof(tmp) - 1] = '\0';
lub_string_cat(&command, tmp);
}
/* Add sequence */
if (clish_config__get_seq(config)) {
str = clish_shell_expand(clish_config__get_seq(config), SHELL_VAR_ACTION, context);
snprintf(tmp, sizeof(tmp) - 1, " -q %u", str2ushort(str));
tmp[sizeof(tmp) - 1] = '\0';
lub_string_cat(&command, tmp);
lub_string_free(str);
}
/* Add pwd */
if (clish_config__get_depth(config)) {
str = clish_shell_expand(clish_config__get_depth(config), SHELL_VAR_ACTION, context);
num = str2ushort(str);
lub_string_free(str);
} else {
num = clish_command__get_depth(cmd);
}
str = clish_shell__get_pwd_full(this, num);
if (str) {
lub_string_cat(&command, " ");
lub_string_cat(&command, str);
lub_string_free(str);
}
#ifdef DEBUG
fprintf(stderr, "CONFIG request: %s\n", command);
#endif
if (send_request(client, command) < 0) {
fprintf(stderr, "Cannot write to the running-config.\n");
}
if (konf_client_recv_answer(client, &buf) < 0) {
fprintf(stderr, "The error while request to the config daemon.\n");
}
lub_string_free(command);
/* Postprocessing. Get data from daemon etc. */
switch (op) {
case CLISH_CONFIG_DUMP:
if (buf) {
konf_buf_lseek(buf, 0);
while ((str = konf_buf_preparse(buf))) {
if (strlen(str) == 0) {
lub_string_free(str);
break;
}
tinyrl_printf(clish_shell__get_tinyrl(this),
"%s\n", str);
lub_string_free(str);
}
konf_buf_delete(buf);
}
break;
default:
break;
};
return BOOL_TRUE;
}
/*--------------------------------------------------------- */
static int send_request(konf_client_t * client, char *command)
{
if ((konf_client_connect(client) < 0))
return -1;
if (konf_client_send(client, command) < 0) {
if (konf_client_reconnect(client) < 0)
return -1;
if (konf_client_send(client, command) < 0)
return -1;
}
return 0;
}
|
zzysjtu-klish
|
clish/callback_config.c
|
C
|
bsd
| 5,083
|
/*
* view.c
*
* This file provides the implementation of a view class
*/
#include "private.h"
#include "lub/argv.h"
#include "lub/string.h"
#include "lub/ctype.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/*---------------------------------------------------------
* PRIVATE META FUNCTIONS
*--------------------------------------------------------- */
int clish_view_bt_compare(const void *clientnode, const void *clientkey)
{
const clish_view_t *this = clientnode;
const char *key = clientkey;
return strcmp(this->name, key);
}
/*-------------------------------------------------------- */
void clish_view_bt_getkey(const void *clientnode, lub_bintree_key_t * key)
{
const clish_view_t *this = clientnode;
/* fill out the opaque key */
strcpy((char *)key, this->name);
}
/*---------------------------------------------------------
* PRIVATE METHODS
*--------------------------------------------------------- */
static void clish_view_init(clish_view_t * this, const char *name, const char *prompt)
{
/* set up defaults */
this->name = lub_string_dup(name);
this->prompt = NULL;
this->nspacec = 0;
this->nspacev = NULL;
this->depth = 0;
this->restore = CLISH_RESTORE_NONE;
/* Be a good binary tree citizen */
lub_bintree_node_init(&this->bt_node);
/* initialise the tree of commands for this view */
lub_bintree_init(&this->tree,
clish_command_bt_offset(),
clish_command_bt_compare, clish_command_bt_getkey);
/* set up the defaults */
clish_view__set_prompt(this, prompt);
}
/*--------------------------------------------------------- */
static void clish_view_fini(clish_view_t * this)
{
clish_command_t *cmd;
unsigned i;
/* delete each command held by this view */
while ((cmd = lub_bintree_findfirst(&this->tree))) {
/* remove the command from the tree */
lub_bintree_remove(&this->tree, cmd);
/* release the instance */
clish_command_delete(cmd);
}
/* free our memory */
lub_string_free(this->name);
this->name = NULL;
lub_string_free(this->prompt);
this->prompt = NULL;
/* finalize each of the namespace instances */
for (i = 0; i < this->nspacec; i++) {
clish_nspace_delete(this->nspacev[i]);
}
/* free the namespace vector */
free(this->nspacev);
this->nspacec = 0;
this->nspacev = NULL;
}
/*---------------------------------------------------------
* PUBLIC META FUNCTIONS
*--------------------------------------------------------- */
size_t clish_view_bt_offset(void)
{
return offsetof(clish_view_t, bt_node);
}
/*--------------------------------------------------------- */
clish_view_t *clish_view_new(const char *name, const char *prompt)
{
clish_view_t *this = malloc(sizeof(clish_view_t));
if (this)
clish_view_init(this, name, prompt);
return this;
}
/*---------------------------------------------------------
* PUBLIC METHODS
*--------------------------------------------------------- */
void clish_view_delete(clish_view_t * this)
{
clish_view_fini(this);
free(this);
}
/*--------------------------------------------------------- */
clish_command_t *clish_view_new_command(clish_view_t * this,
const char *name, const char *help)
{
/* allocate the memory for a new parameter definition */
clish_command_t *cmd = clish_command_new(name, help);
assert(cmd);
/* if this is a command other than the startup command... */
if (NULL != help) {
/* ...insert it into the binary tree for this view */
if (-1 == lub_bintree_insert(&this->tree, cmd)) {
/* inserting a duplicate command is bad */
clish_command_delete(cmd);
cmd = NULL;
}
}
return cmd;
}
/*--------------------------------------------------------- */
/* This method identifies the command (if any) which provides
* the longest match with the specified line of text.
*
* NB this comparison is case insensitive.
*
* this - the view instance upon which to operate
* line - the command line to analyse
*/
clish_command_t *clish_view_resolve_prefix(clish_view_t * this,
const char *line, bool_t inherit)
{
clish_command_t *result = NULL, *cmd;
char *buffer = NULL;
lub_argv_t *argv;
unsigned i;
/* create a vector of arguments */
argv = lub_argv_new(line, 0);
for (i = 0; i < lub_argv__get_count(argv); i++) {
/* set our buffer to be that of the first "i" arguments */
lub_string_cat(&buffer, lub_argv__get_arg(argv, i));
/* set the result to the longest match */
cmd = clish_view_find_command(this, buffer, inherit);
/* job done */
if (!cmd)
break;
result = cmd;
/* ready for the next word */
lub_string_cat(&buffer, " ");
}
/* free up our dynamic storage */
lub_string_free(buffer);
lub_argv_delete(argv);
return result;
}
/*--------------------------------------------------------- */
clish_command_t *clish_view_resolve_command(clish_view_t *this,
const char *line, bool_t inherit)
{
clish_command_t *result = clish_view_resolve_prefix(this, line, inherit);
if (result) {
clish_action_t *action = clish_command__get_action(result);
clish_config_t *config = clish_command__get_config(result);
if (!clish_action__get_script(action) &&
(!clish_action__get_builtin(action)) &&
(CLISH_CONFIG_NONE == clish_config__get_op(config)) &&
(!clish_command__get_param_count(result)) &&
(!clish_command__get_view(result))) {
/* if this doesn't do anything we've
* not resolved a command
*/
result = NULL;
}
}
return result;
}
/*--------------------------------------------------------- */
clish_command_t *clish_view_find_command(clish_view_t * this,
const char *name, bool_t inherit)
{
clish_command_t *cmd, *result = NULL;
clish_nspace_t *nspace;
unsigned cnt = clish_view__get_nspace_count(this);
int i;
/* Search the current view */
result = lub_bintree_find(&this->tree, name);
/* Make command link from command alias */
result = clish_command_alias_to_link(result);
if (inherit) {
for (i = cnt - 1; i >= 0; i--) {
nspace = clish_view__get_nspace(this, i);
cmd = clish_nspace_find_command(nspace, name);
/* choose the longest match */
result = clish_command_choose_longest(result, cmd);
}
}
return result;
}
/*--------------------------------------------------------- */
static const clish_command_t *find_next_completion(clish_view_t * this,
const char *iter_cmd, const char *line)
{
clish_command_t *cmd;
const char *name = "";
lub_argv_t *largv;
unsigned words;
/* build an argument vector for the line */
largv = lub_argv_new(line, 0);
words = lub_argv__get_count(largv);
/* account for trailing space */
if (!*line || lub_ctype_isspace(line[strlen(line) - 1]))
words++;
if (iter_cmd)
name = iter_cmd;
while ((cmd = lub_bintree_findnext(&this->tree, name))) {
/* Make command link from command alias */
cmd = clish_command_alias_to_link(cmd);
name = clish_command__get_name(cmd);
if (words == lub_argv_wordcount(name)) {
/* only bother with commands of which this line is a prefix */
/* this is a completion */
if (lub_string_nocasestr(name, line) == name)
break;
}
}
/* clean up the dynamic memory */
lub_argv_delete(largv);
return cmd;
}
/*--------------------------------------------------------- */
const clish_command_t *clish_view_find_next_completion(clish_view_t * this,
const char *iter_cmd, const char *line,
clish_nspace_visibility_t field, bool_t inherit)
{
const clish_command_t *result, *cmd;
clish_nspace_t *nspace;
unsigned cnt = clish_view__get_nspace_count(this);
int i;
/* ask local view for next command */
result = find_next_completion(this, iter_cmd, line);
if (!inherit)
return result;
/* ask the imported namespaces for next command */
for (i = cnt - 1; i >= 0; i--) {
nspace = clish_view__get_nspace(this, i);
if (!clish_nspace__get_visibility(nspace, field))
continue;
cmd = clish_nspace_find_next_completion(nspace,
iter_cmd, line, field);
if (clish_command_diff(result, cmd) > 0)
result = cmd;
}
return result;
}
/*--------------------------------------------------------- */
void clish_view_insert_nspace(clish_view_t * this, clish_nspace_t * nspace)
{
size_t new_size = ((this->nspacec + 1) * sizeof(clish_nspace_t *));
clish_nspace_t **tmp;
/* resize the namespace vector */
tmp = realloc(this->nspacev, new_size);
assert(tmp);
this->nspacev = tmp;
/* insert reference to the namespace */
this->nspacev[this->nspacec++] = nspace;
}
/*--------------------------------------------------------- */
void clish_view_clean_proxy(clish_view_t * this)
{
int i;
/* Iterate namespace instances */
for (i = 0; i < this->nspacec; i++) {
clish_nspace_clean_proxy(this->nspacev[i]);
}
}
/*---------------------------------------------------------
* PUBLIC ATTRIBUTES
*--------------------------------------------------------- */
const char *clish_view__get_name(const clish_view_t * this)
{
return this->name;
}
/*--------------------------------------------------------- */
void clish_view__set_prompt(clish_view_t * this, const char *prompt)
{
assert(!this->prompt);
this->prompt = lub_string_dup(prompt);
}
/*--------------------------------------------------------- */
char *clish_view__get_prompt(const clish_view_t *this)
{
return this->prompt;
}
/*--------------------------------------------------------- */
clish_nspace_t *clish_view__get_nspace(const clish_view_t * this,
unsigned index)
{
clish_nspace_t *result = NULL;
if (index < this->nspacec) {
result = this->nspacev[index];
}
return result;
}
/*--------------------------------------------------------- */
unsigned int clish_view__get_nspace_count(const clish_view_t * this)
{
return this->nspacec;
}
/*--------------------------------------------------------- */
void clish_view__set_depth(clish_view_t * this, unsigned depth)
{
this->depth = depth;
}
/*--------------------------------------------------------- */
unsigned clish_view__get_depth(const clish_view_t * this)
{
return this->depth;
}
/*--------------------------------------------------------- */
void clish_view__set_restore(clish_view_t * this,
clish_view_restore_t restore)
{
this->restore = restore;
}
/*--------------------------------------------------------- */
clish_view_restore_t clish_view__get_restore(const clish_view_t * this)
{
return this->restore;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
clish/view/view.c
|
C
|
bsd
| 10,361
|
/*
* view.h
*/
#include "clish/view.h"
#include "lub/bintree.h"
/*---------------------------------------------------------
* PRIVATE TYPES
*--------------------------------------------------------- */
struct clish_view_s {
lub_bintree_t tree;
lub_bintree_node_t bt_node;
char *name;
char *prompt;
unsigned int nspacec;
clish_nspace_t **nspacev;
unsigned int depth;
clish_view_restore_t restore;
};
|
zzysjtu-klish
|
clish/view/private.h
|
C
|
bsd
| 412
|
/*
* view_dump.c
*/
#include "private.h"
#include "lub/dump.h"
/*--------------------------------------------------------- */
void clish_view_dump(clish_view_t * this)
{
clish_command_t *c;
lub_bintree_iterator_t iter;
unsigned i;
lub_dump_printf("view(%p)\n", this);
lub_dump_indent();
lub_dump_printf("name : %s\n", clish_view__get_name(this));
lub_dump_printf("depth : %u\n", clish_view__get_depth(this));
/* Get each namespace to dump their details */
for (i = 0; i < this->nspacec; i++) {
clish_nspace_dump(clish_view__get_nspace(this, i));
}
/* iterate the tree of commands */
c = lub_bintree_findfirst(&this->tree);
for (lub_bintree_iterator_init(&iter, &this->tree, c);
c; c = lub_bintree_iterator_next(&iter)) {
clish_command_dump(c);
}
lub_dump_undent();
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
clish/view/view_dump.c
|
C
|
bsd
| 861
|
/*
* internal.h
*/
#ifndef _clish_internal_h
#define _clish_internal_h
#include "lub/c_decl.h"
#include "clish/shell.h"
_BEGIN_C_DECL
/* storage */
extern struct termios clish_default_tty_termios;
/* Standard clish callback functions */
extern clish_shell_access_fn_t clish_access_callback;
extern clish_shell_script_fn_t clish_script_callback;
extern clish_shell_script_fn_t clish_dryrun_callback;
extern clish_shell_config_fn_t clish_config_callback;
extern clish_shell_log_fn_t clish_log_callback;
_END_C_DECL
#endif /* _clish_internal_h */
|
zzysjtu-klish
|
clish/internal.h
|
C
|
bsd
| 552
|
/*
* shell_word_generator.c
*/
#include <string.h>
#include "private.h"
#include "lub/string.h"
#include "lub/argv.h"
/*-------------------------------------------------------- */
void
clish_shell_iterator_init(clish_shell_iterator_t * iter,
clish_nspace_visibility_t field)
{
iter->last_cmd = NULL;
iter->field = field;
}
/*--------------------------------------------------------- */
const clish_command_t *clish_shell_resolve_command(const clish_shell_t * this,
const char *line)
{
clish_command_t *cmd, *result;
/* Search the current view */
result = clish_view_resolve_command(clish_shell__get_view(this), line, BOOL_TRUE);
/* Search the global view */
cmd = clish_view_resolve_command(this->global, line, BOOL_TRUE);
result = clish_command_choose_longest(result, cmd);
return result;
}
/*--------------------------------------------------------- */
const clish_command_t *clish_shell_resolve_prefix(const clish_shell_t * this,
const char *line)
{
clish_command_t *cmd, *result;
/* Search the current view */
result = clish_view_resolve_prefix(clish_shell__get_view(this), line, BOOL_TRUE);
/* Search the global view */
cmd = clish_view_resolve_prefix(this->global, line, BOOL_TRUE);
result = clish_command_choose_longest(result, cmd);
return result;
}
/*-------------------------------------------------------- */
const clish_command_t *clish_shell_find_next_completion(const clish_shell_t *
this, const char *line, clish_shell_iterator_t * iter)
{
const clish_command_t *result, *cmd;
/* ask the local view for next command */
result = clish_view_find_next_completion(clish_shell__get_view(this),
iter->last_cmd, line, iter->field, BOOL_TRUE);
/* ask the global view for next command */
cmd = clish_view_find_next_completion(this->global,
iter->last_cmd, line, iter->field, BOOL_TRUE);
if (clish_command_diff(result, cmd) > 0)
result = cmd;
if (!result)
iter->last_cmd = NULL;
else
iter->last_cmd = clish_command__get_name(result);
return result;
}
/*--------------------------------------------------------- */
void clish_shell_param_generator(clish_shell_t *this, lub_argv_t *matches,
const clish_command_t *cmd, const char *line, unsigned offset)
{
const char *name = clish_command__get_name(cmd);
char *text = lub_string_dup(&line[offset]);
clish_ptype_t *ptype;
unsigned idx = lub_argv_wordcount(name);
/* get the index of the current parameter */
unsigned index = lub_argv_wordcount(line) - idx;
clish_context_t context;
if ((0 != index) || (offset && line[offset - 1] == ' ')) {
lub_argv_t *argv = lub_argv_new(line, 0);
clish_pargv_t *pargv = clish_pargv_new();
clish_pargv_t *completion = clish_pargv_new();
unsigned completion_index = 0;
const clish_param_t *param = NULL;
/* if there is some text for the parameter then adjust the index */
if ((0 != index) && (text[0] != '\0'))
index--;
/* Parse command line to get completion pargv's */
context.shell = this;
context.cmd = cmd;
context.pargv = pargv;
clish_shell_parse_pargv(pargv, cmd, &context,
clish_command__get_paramv(cmd),
argv, &idx, completion, index + idx);
lub_argv_delete(argv);
while ((param = clish_pargv__get_param(completion,
completion_index++))) {
char *result;
/* The param is args so it has no completion */
if (param == clish_command__get_args(cmd))
continue;
/* The switch has no completion string */
if (CLISH_PARAM_SWITCH == clish_param__get_mode(param))
continue;
/* The subcommand is identified by it's value */
if (CLISH_PARAM_SUBCOMMAND ==
clish_param__get_mode(param)) {
result = clish_param__get_value(param);
if (result)
lub_argv_add(matches, result);
}
/* The 'completion' field of PARAM */
if (clish_param__get_completion(param)) {
char *str, *q;
char *saveptr;
str = clish_shell_expand(
clish_param__get_completion(param), SHELL_VAR_ACTION, &context);
if (str) {
for (q = strtok_r(str, " \n", &saveptr);
q; q = strtok_r(NULL, " \n", &saveptr)) {
if (q == strstr(q, text))
lub_argv_add(matches, q);
}
lub_string_free(str);
}
}
/* The common PARAM. Let ptype do the work */
if ((ptype = clish_param__get_ptype(param)))
clish_ptype_word_generator(ptype, matches, text);
}
clish_pargv_delete(completion);
clish_pargv_delete(pargv);
}
lub_string_free(text);
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
clish/shell/shell_command.c
|
C
|
bsd
| 4,468
|
/*
* shell_new.c
*/
#include "private.h"
#include "lub/string.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
/*-------------------------------------------------------- */
int clish_shell_loop(clish_shell_t *this)
{
int running = 0;
int retval = SHELL_STATE_OK;
assert(this);
if (!tinyrl__get_istream(this->tinyrl))
return SHELL_STATE_IO_ERROR;
/* Check the shell isn't closing down */
if (this && (SHELL_STATE_CLOSING == this->state))
return retval;
/* Loop reading and executing lines until the user quits */
while (!running) {
retval = SHELL_STATE_OK;
/* Get input from the stream */
running = clish_shell_readline(this, NULL);
if (running) {
switch (this->state) {
case SHELL_STATE_SCRIPT_ERROR:
case SHELL_STATE_SYNTAX_ERROR:
/* Interactive session doesn't exit on error */
if (tinyrl__get_isatty(this->tinyrl) ||
(this->current_file &&
!this->current_file->stop_on_error))
running = 0;
retval = this->state;
default:
break;
}
}
if (SHELL_STATE_CLOSING == this->state)
running = -1;
if (running)
running = clish_shell_pop_file(this);
}
return retval;
}
/*-------------------------------------------------------- */
|
zzysjtu-klish
|
clish/shell/shell_spawn.c
|
C
|
bsd
| 1,262
|
/*
* shell_find_create_view.c
*/
#include <assert.h>
#include "private.h"
/*--------------------------------------------------------- */
clish_view_t *clish_shell_find_create_view(clish_shell_t * this,
const char *name, const char *prompt)
{
clish_view_t *view = lub_bintree_find(&this->view_tree, name);
if (!view) {
/* create a view */
view = clish_view_new(name, prompt);
assert(view);
clish_shell_insert_view(this, view);
} else {
/* set the prompt */
if (prompt)
clish_view__set_prompt(view, prompt);
}
return view;
}
/*--------------------------------------------------------- */
clish_view_t *clish_shell_find_view(clish_shell_t * this, const char *name)
{
return lub_bintree_find(&this->view_tree, name);
}
/*--------------------------------------------------------- */
void clish_shell_insert_view(clish_shell_t * this, clish_view_t * view)
{
(void)lub_bintree_insert(&this->view_tree, view);
}
/*--------------------------------------------------------- */
clish_view_t *clish_shell__get_view(const clish_shell_t * this)
{
assert(this);
if (this->depth < 0)
return NULL;
return this->pwdv[this->depth]->view;
}
/*--------------------------------------------------------- */
unsigned clish_shell__get_depth(const clish_shell_t * this)
{
assert(this);
return this->depth;
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
clish/shell/shell_view.c
|
C
|
bsd
| 1,386
|
/*
* shell_find_create_ptype.c
*/
#include <assert.h>
#include "private.h"
/*--------------------------------------------------------- */
clish_ptype_t *clish_shell_find_ptype(clish_shell_t *this,
const char *name)
{
return lub_bintree_find(&this->ptype_tree, name);
}
/*--------------------------------------------------------- */
clish_ptype_t *clish_shell_find_create_ptype(clish_shell_t * this,
const char *name, const char *text, const char *pattern,
clish_ptype_method_e method, clish_ptype_preprocess_e preprocess)
{
clish_ptype_t *ptype = lub_bintree_find(&this->ptype_tree, name);
if (!ptype) {
/* create a ptype */
ptype = clish_ptype_new(name, text, pattern,
method, preprocess);
assert(ptype);
clish_shell_insert_ptype(this, ptype);
} else {
if (pattern) {
/* set the pattern */
clish_ptype__set_pattern(ptype, pattern, method);
/* set the preprocess */
clish_ptype__set_preprocess(ptype, preprocess);
}
/* set the help text */
if (text)
clish_ptype__set_text(ptype, text);
}
return ptype;
}
/*--------------------------------------------------------- */
void clish_shell_insert_ptype(clish_shell_t * this, clish_ptype_t * ptype)
{
(void)lub_bintree_insert(&this->ptype_tree, ptype);
}
/*--------------------------------------------------------- */
|
zzysjtu-klish
|
clish/shell/shell_ptype.c
|
C
|
bsd
| 1,315
|
/*
* ------------------------------------------------------
* shell_roxml.c
*
* This file implements the means to read an XML encoded file
* and populate the CLI tree based on the contents. It implements
* the clish_xml API using roxml
* ------------------------------------------------------
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if defined(HAVE_LIB_LIBXML2)
#include <errno.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include "xmlapi.h"
/* dummy stuff ; really a xmlDoc */
struct clish_xmldoc_s {
int dummy;
};
/* dummy stuff ; really a xmlNode */
struct clish_xmlnode_s {
int dummy;
};
static inline xmlDoc *xmldoc_to_doc(clish_xmldoc_t *doc)
{
return (xmlDoc*)doc;
}
static inline xmlNode *xmlnode_to_node(clish_xmlnode_t *node)
{
return (xmlNode*)node;
}
static inline clish_xmldoc_t *doc_to_xmldoc(xmlDoc *node)
{
return (clish_xmldoc_t*)node;
}
static inline clish_xmlnode_t *node_to_xmlnode(xmlNode *node)
{
return (clish_xmlnode_t*)node;
}
/*
* public interface
*/
clish_xmldoc_t *clish_xmldoc_read(const char *filename)
{
xmlDoc *doc = xmlReadFile(filename, NULL, 0);
return doc_to_xmldoc(doc);
}
void clish_xmldoc_release(clish_xmldoc_t *doc)
{
if (doc) {
xmlFreeDoc(xmldoc_to_doc(doc));
xmlCleanupParser();
}
}
int clish_xmldoc_is_valid(clish_xmldoc_t *doc)
{
return doc != NULL;
}
int clish_xmldoc_error_caps(clish_xmldoc_t *doc)
{
return CLISH_XMLERR_NOCAPS;
}
int clish_xmldoc_get_err_line(clish_xmldoc_t *doc)
{
return -1;
}
int clish_xmldoc_get_err_col(clish_xmldoc_t *doc)
{
return -1;
}
const char *clish_xmldoc_get_err_msg(clish_xmldoc_t *doc)
{
return "";
}
int clish_xmlnode_get_type(clish_xmlnode_t *node)
{
if (node) {
xmlNode *n = xmlnode_to_node(node);
switch (n->type) {
case XML_ELEMENT_NODE:
return CLISH_XMLNODE_ELM;
case XML_TEXT_NODE:
return CLISH_XMLNODE_TEXT;
case XML_COMMENT_NODE:
return CLISH_XMLNODE_COMMENT;
case XML_PI_NODE:
return CLISH_XMLNODE_PI;
case XML_ATTRIBUTE_NODE:
return CLISH_XMLNODE_ATTR;
default:
break;
}
}
return CLISH_XMLNODE_UNKNOWN;
}
clish_xmlnode_t *clish_xmldoc_get_root(clish_xmldoc_t *doc)
{
if (doc) {
xmlNode *root = xmlDocGetRootElement(xmldoc_to_doc(doc));
return node_to_xmlnode(root);
}
return NULL;
}
clish_xmlnode_t *clish_xmlnode_parent(clish_xmlnode_t *node)
{
if (node) {
xmlNode *n = xmlnode_to_node(node);
xmlNode *root = xmlDocGetRootElement(n->doc);
if (n != root)
return node_to_xmlnode(n->parent);
}
return NULL;
}
clish_xmlnode_t *clish_xmlnode_next_child(clish_xmlnode_t *parent,
clish_xmlnode_t *curchild)
{
xmlNode *child;
if (!parent)
return NULL;
if (curchild) {
child = xmlnode_to_node(curchild)->next;
} else {
child = xmlnode_to_node(parent)->children;
}
return node_to_xmlnode(child);
}
char *clish_xmlnode_fetch_attr(clish_xmlnode_t *node,
const char *attrname)
{
xmlNode *n;
if (!node || !attrname)
return NULL;
n = xmlnode_to_node(node);
if (n->type == XML_ELEMENT_NODE) {
xmlAttr *a = n->properties;
while (a) {
if (strcmp((char*)a->name, attrname) == 0) {
if (a->children && a->children->content)
return (char *)a->children->content;
else
return NULL;
}
a = a->next;
}
}
return NULL;
}
int clish_xmlnode_get_content(clish_xmlnode_t *node, char *content,
unsigned int *contentlen)
{
xmlNode *n;
xmlNode *c;
int rlen = 0;
if (content && contentlen && *contentlen)
*content = 0;
if (!node || !content || !contentlen)
return -EINVAL;
if (*contentlen <= 1)
return -EINVAL;
*content = 0;
n = xmlnode_to_node(node);
/* first, get the content length */
c = n->children;
while (c) {
if (c->type == XML_TEXT_NODE && !xmlIsBlankNode(c)) {
rlen += strlen((char*)c->content);
}
c = c->next;
}
++rlen;
if (rlen <= *contentlen) {
c = n->children;
while (c) {
if (c->type == XML_TEXT_NODE && !xmlIsBlankNode(c)) {
strcat(content, (char*)c->content);
}
c = c->next;
}
return 0;
} else {
*contentlen = rlen;
return -E2BIG;
}
}
int clish_xmlnode_get_name(clish_xmlnode_t *node, char *name,
unsigned int *namelen)
{
int rlen;
xmlNode *n;
if (name && namelen && *namelen)
*name = 0;
if (!node || !name || !namelen)
return -EINVAL;
if (*namelen <= 1)
return -EINVAL;
*name = 0;
n = xmlnode_to_node(node);
rlen = strlen((char*)n->name) + 1;
if (rlen <= *namelen) {
sprintf(name, "%s", (char*)n->name);
return 0;
} else {
*namelen = rlen;
return -E2BIG;
}
}
void clish_xmlnode_print(clish_xmlnode_t *node, FILE *out)
{
xmlNode *n;
xmlAttr *a;
n = xmlnode_to_node(node);
if (n && n->name) {
fprintf(out, "<%s", (char*)n->name);
a = n->properties;
while (a) {
char *av = "";
if (a->children && a->children->content)
av = (char*)a->children->content;
fprintf(out, " %s='%s'", (char*)a->name, av);
a = a->next;
}
fprintf(out, ">");
}
}
void clish_xml_release(void *p)
{
/* do we allocate memory? not yet. */
}
#endif /* HAVE_LIB_LIBXML2 */
|
zzysjtu-klish
|
clish/shell/shell_libxml2.c
|
C
|
bsd
| 5,095
|
/*
* shell_startup.c
*/
#include "private.h"
#include <assert.h>
#include "lub/string.h"
/*----------------------------------------------------------- */
int clish_shell_startup(clish_shell_t *this)
{
const char *banner;
clish_context_t context;
int res = 0;
assert(this->startup);
banner = clish_command__get_detail(this->startup);
if (banner)
tinyrl_printf(this->tinyrl, "%s\n", banner);
context.shell = this;
context.cmd = this->startup;
context.pargv = NULL;
/* Call log initialize */
if (clish_shell__get_log(this) && this->client_hooks->log_fn)
this->client_hooks->log_fn(&context, NULL, 0);
/* Call startup script */
res = clish_shell_execute(&context, NULL);
return res;
}
/*----------------------------------------------------------- */
void clish_shell__set_startup_view(clish_shell_t * this, const char * viewname)
{
clish_view_t *view;
assert(this);
assert(this->startup);
/* Search for the view */
view = clish_shell_find_create_view(this, viewname, NULL);
clish_command__force_view(this->startup, view);
}
/*----------------------------------------------------------- */
void clish_shell__set_startup_viewid(clish_shell_t * this, const char * viewid)
{
assert(this);
assert(this->startup);
clish_command__force_viewid(this->startup, viewid);
}
/*----------------------------------------------------------- */
void clish_shell__set_default_shebang(clish_shell_t * this, const char * shebang)
{
assert(this);
lub_string_free(this->default_shebang);
this->default_shebang = lub_string_dup(shebang);
}
/*----------------------------------------------------------- */
const char * clish_shell__get_default_shebang(const clish_shell_t * this)
{
assert(this);
return this->default_shebang;
}
/*----------------------------------------------------------- */
|
zzysjtu-klish
|
clish/shell/shell_startup.c
|
C
|
bsd
| 1,809
|
/*
* shell_execute.c
*/
#include "private.h"
#include "lub/string.h"
#include "lub/argv.h"
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <signal.h>
#include <fcntl.h>
/*
* These are the internal commands for this framework.
*/
static clish_shell_builtin_fn_t
clish_close,
clish_overview,
clish_source,
clish_source_nostop,
clish_history,
clish_nested_up,
clish_nop,
clish_wdog;
static clish_shell_builtin_t clish_cmd_list[] = {
{"clish_close", clish_close},
{"clish_overview", clish_overview},
{"clish_source", clish_source},
{"clish_source_nostop", clish_source_nostop},
{"clish_history", clish_history},
{"clish_nested_up", clish_nested_up},
{"clish_nop", clish_nop},
{"clish_wdog", clish_wdog},
{NULL, NULL}
};
/*----------------------------------------------------------- */
/* Terminate the current shell session */
static int clish_close(clish_context_t *context, const lub_argv_t * argv)
{
/* the exception proves the rule... */
clish_shell_t *this = (clish_shell_t *)context->shell;
argv = argv; /* not used */
this->state = SHELL_STATE_CLOSING;
return 0;
}
/*----------------------------------------------------------- */
/*
Open a file and interpret it as a script in the context of a new
thread. Whether the script continues after command, but not script,
errors depends on the value of the stop_on_error flag.
*/
static int clish_source_internal(clish_context_t *context,
const lub_argv_t * argv, bool_t stop_on_error)
{
int result = -1;
const char *filename = lub_argv__get_arg(argv, 0);
struct stat fileStat;
/* the exception proves the rule... */
clish_shell_t *this = (clish_shell_t *)context->shell;
/*
* Check file specified is not a directory
*/
if ((0 == stat((char *)filename, &fileStat)) &&
(!S_ISDIR(fileStat.st_mode))) {
/*
* push this file onto the file stack associated with this
* session. This will be closed by clish_shell_pop_file()
* when it is finished with.
*/
result = clish_shell_push_file(this, filename,
stop_on_error);
}
return result ? -1 : 0;
}
/*----------------------------------------------------------- */
/*
Open a file and interpret it as a script in the context of a new
thread. Invoking a script in this way will cause the script to
stop on the first error
*/
static int clish_source(clish_context_t *context, const lub_argv_t * argv)
{
return (clish_source_internal(context, argv, BOOL_TRUE));
}
/*----------------------------------------------------------- */
/*
Open a file and interpret it as a script in the context of a new
thread. Invoking a script in this way will cause the script to
continue after command, but not script, errors.
*/
static int clish_source_nostop(clish_context_t *context, const lub_argv_t * argv)
{
return (clish_source_internal(context, argv, BOOL_FALSE));
}
/*----------------------------------------------------------- */
/*
Show the shell overview
*/
static int clish_overview(clish_context_t *context, const lub_argv_t * argv)
{
clish_shell_t *this = context->shell;
argv = argv; /* not used */
tinyrl_printf(this->tinyrl, "%s\n", context->shell->overview);
return 0;
}
/*----------------------------------------------------------- */
static int clish_history(clish_context_t *context, const lub_argv_t * argv)
{
clish_shell_t *this = context->shell;
tinyrl_history_t *history = tinyrl__get_history(this->tinyrl);
tinyrl_history_iterator_t iter;
const tinyrl_history_entry_t *entry;
unsigned limit = 0;
const char *arg = lub_argv__get_arg(argv, 0);
if (arg && ('\0' != *arg)) {
limit = (unsigned)atoi(arg);
if (0 == limit) {
/* unlimit the history list */
(void)tinyrl_history_unstifle(history);
} else {
/* limit the scope of the history list */
tinyrl_history_stifle(history, limit);
}
}
for (entry = tinyrl_history_getfirst(history, &iter);
entry; entry = tinyrl_history_getnext(&iter)) {
/* dump the details of this entry */
tinyrl_printf(this->tinyrl,
"%5d %s\n",
tinyrl_history_entry__get_index(entry),
tinyrl_history_entry__get_line(entry));
}
return 0;
}
/*----------------------------------------------------------- */
/*
* Searches for a builtin command to execute
*/
static clish_shell_builtin_fn_t *find_builtin_callback(const
clish_shell_builtin_t * cmd_list, const char *name)
{
const clish_shell_builtin_t *result;
/* search a list of commands */
for (result = cmd_list; result && result->name; result++) {
if (0 == strcmp(name, result->name))
break;
}
return (result && result->name) ? result->callback : NULL;
}
/*----------------------------------------------------------- */
void clish_shell_cleanup_script(void *script)
{
/* simply release the memory */
lub_string_free(script);
}
/*-------------------------------------------------------- */
static int clish_shell_lock(const char *lock_path)
{
int i;
int res;
int lock_fd = -1;
struct flock lock;
if (!lock_path)
return -1;
lock_fd = open(lock_path, O_WRONLY | O_CREAT, 00644);
if (-1 == lock_fd) {
fprintf(stderr, "Can't open lockfile %s.\n", lock_path);
return -1;
}
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
for (i = 0; i < CLISH_LOCK_WAIT; i++) {
res = fcntl(lock_fd, F_SETLK, &lock);
if (res != -1)
break;
if (EINTR == errno)
continue;
if ((EAGAIN == errno) || (EACCES == errno)) {
if (0 == i)
fprintf(stderr,
"Try to get lock. Please wait...\n");
sleep(1);
continue;
}
break;
}
if (res == -1) {
fprintf(stderr, "Can't get lock.\n");
close(lock_fd);
return -1;
}
return lock_fd;
}
/*-------------------------------------------------------- */
static void clish_shell_unlock(int lock_fd)
{
struct flock lock;
if (lock_fd == -1)
return;
lock.l_type = F_UNLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
fcntl(lock_fd, F_SETLK, &lock);
close(lock_fd);
}
/*----------------------------------------------------------- */
int clish_shell_execute(clish_context_t *context, char **out)
{
clish_shell_t *this = context->shell;
const clish_command_t *cmd = context->cmd;
clish_action_t *action;
int result = 0;
char *lock_path = clish_shell__get_lockfile(this);
int lock_fd = -1;
sigset_t old_sigs;
struct sigaction old_sigint, old_sigquit, old_sighup;
clish_view_t *cur_view = clish_shell__get_view(this);
unsigned int saved_wdog_timeout = this->wdog_timeout;
assert(cmd);
action = clish_command__get_action(cmd);
/* Pre-change view if the command is from another depth/view */
{
clish_view_restore_t restore = clish_command__get_restore(cmd);
if ((CLISH_RESTORE_VIEW == restore) &&
(clish_command__get_pview(cmd) != cur_view)) {
clish_view_t *view = clish_command__get_pview(cmd);
clish_shell__set_pwd(this, NULL, view, NULL, context);
} else if ((CLISH_RESTORE_DEPTH == restore) &&
(clish_command__get_depth(cmd) < this->depth)) {
this->depth = clish_command__get_depth(cmd);
}
}
/* Lock the lockfile */
if (lock_path && clish_command__get_lock(cmd)) {
lock_fd = clish_shell_lock(lock_path);
if (-1 == lock_fd) {
result = -1;
goto error; /* Can't set lock */
}
}
/* Ignore and block SIGINT, SIGQUIT, SIGHUP */
if (!clish_command__get_interrupt(cmd)) {
struct sigaction sa;
sigset_t sigs;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
sigaction(SIGINT, &sa, &old_sigint);
sigaction(SIGQUIT, &sa, &old_sigquit);
sigaction(SIGHUP, &sa, &old_sighup);
sigemptyset(&sigs);
sigaddset(&sigs, SIGINT);
sigaddset(&sigs, SIGQUIT);
sigaddset(&sigs, SIGHUP);
sigprocmask(SIG_BLOCK, &sigs, &old_sigs);
}
/* Execute ACTION */
result = clish_shell_exec_action(action, context, out);
/* Restore SIGINT, SIGQUIT, SIGHUP */
if (!clish_command__get_interrupt(cmd)) {
sigprocmask(SIG_SETMASK, &old_sigs, NULL);
/* Is the signals delivery guaranteed here (before
sigaction restore) for previously blocked and
pending signals? The simple test is working well.
I don't want to use sigtimedwait() function bacause
it needs a realtime extensions. The sigpending() with
the sleep() is not nice too. Report bug if clish will
get the SIGINT after non-interruptable action.
*/
sigaction(SIGINT, &old_sigint, NULL);
sigaction(SIGQUIT, &old_sigquit, NULL);
sigaction(SIGHUP, &old_sighup, NULL);
}
/* Call config callback */
if (!result && this->client_hooks->config_fn)
this->client_hooks->config_fn(context);
/* Call logging callback */
if (clish_shell__get_log(this) && this->client_hooks->log_fn) {
char *full_line = clish_shell__get_full_line(context);
this->client_hooks->log_fn(context, full_line, result);
lub_string_free(full_line);
}
/* Unlock the lockfile */
if (lock_fd != -1)
clish_shell_unlock(lock_fd);
/* Move into the new view */
if (!result) {
clish_view_t *view = clish_command__get_view(cmd);
/* Save the PWD */
if (view) {
char *line = clish_shell__get_line(context);
clish_shell__set_pwd(this, line, view,
clish_command__get_viewid(cmd), context);
lub_string_free(line);
}
}
/* Set appropriate timeout. Workaround: Don't turn on watchdog
on the "set watchdog <timeout>" command itself. */
if (this->wdog_timeout && saved_wdog_timeout) {
tinyrl__set_timeout(this->tinyrl, this->wdog_timeout);
this->wdog_active = BOOL_TRUE;
fprintf(stderr, "Warning: The watchdog is active. Timeout is %u "
"seconds.\nWarning: Press any key to stop watchdog.\n",
this->wdog_timeout);
} else
tinyrl__set_timeout(this->tinyrl, this->idle_timeout);
error:
return result;
}
/*----------------------------------------------------------- */
int clish_shell_exec_action(clish_action_t *action,
clish_context_t *context, char **out)
{
clish_shell_t *this = context->shell;
int result = 0;
const char *builtin;
char *script;
builtin = clish_action__get_builtin(action);
script = clish_shell_expand(clish_action__get_script(action), SHELL_VAR_ACTION, context);
if (builtin) {
clish_shell_builtin_fn_t *callback;
lub_argv_t *argv = script ? lub_argv_new(script, 0) : NULL;
result = -1;
/* search for an internal command */
callback = find_builtin_callback(clish_cmd_list, builtin);
if (!callback) {
/* search for a client command */
callback = find_builtin_callback(
this->client_hooks->cmd_list, builtin);
}
/* invoke the builtin callback */
if (callback)
result = callback(context, argv);
if (argv)
lub_argv_delete(argv);
} else if (script) {
/* now get the client to interpret the resulting script */
result = this->client_hooks->script_fn(context, action, script, out);
}
lub_string_free(script);
return result;
}
/*----------------------------------------------------------- */
/*
* Find out the previous view in the stack and go to it
*/
static int clish_nested_up(clish_context_t *context, const lub_argv_t *argv)
{
clish_shell_t *this = context->shell;
if (!this)
return -1;
argv = argv; /* not used */
/* If depth=0 than exit */
if (0 == this->depth) {
this->state = SHELL_STATE_CLOSING;
return 0;
}
this->depth--;
return 0;
}
/*----------------------------------------------------------- */
/*
* Builtin: NOP function
*/
static int clish_nop(clish_context_t *context, const lub_argv_t *argv)
{
return 0;
}
/*----------------------------------------------------------- */
/*
* Builtin: Set watchdog timeout. The "0" to turn watchdog off.
*/
static int clish_wdog(clish_context_t *context, const lub_argv_t *argv)
{
const char *arg = lub_argv__get_arg(argv, 0);
clish_shell_t *this = context->shell;
/* Turn off watchdog if no args */
if (!arg || ('\0' == *arg)) {
this->wdog_timeout = 0;
return 0;
}
this->wdog_timeout = (unsigned int)atoi(arg);
return 0;
}
/*----------------------------------------------------------- */
const char *clish_shell__get_fifo(clish_shell_t * this)
{
char *name;
int res;
if (this->fifo_name) {
if (0 == access(this->fifo_name, R_OK | W_OK))
return this->fifo_name;
unlink(this->fifo_name);
lub_string_free(this->fifo_name);
this->fifo_name = NULL;
}
do {
char template[] = "/tmp/klish.fifo.XXXXXX";
name = mktemp(template);
if (name[0] == '\0')
return NULL;
res = mkfifo(name, 0600);
if (res == 0)
this->fifo_name = lub_string_dup(name);
} while ((res < 0) && (EEXIST == errno));
return this->fifo_name;
}
/*--------------------------------------------------------- */
void *clish_shell__get_client_cookie(const clish_shell_t * this)
{
return this->client_cookie;
}
/*-------------------------------------------------------- */
void clish_shell__set_log(clish_shell_t *this, bool_t log)
{
assert(this);
this->log = log;
}
/*-------------------------------------------------------- */
bool_t clish_shell__get_log(const clish_shell_t *this)
{
assert(this);
return this->log;
}
/*----------------------------------------------------------- */
|
zzysjtu-klish
|
clish/shell/shell_execute.c
|
C
|
bsd
| 13,133
|