From 458b2a58d18f7e548cfed653dc6f18c318790232 Mon Sep 17 00:00:00 2001 From: Riza Sulistyo Date: Thu, 14 Mar 2013 07:18:13 +0000 Subject: Re #1643: add initial support for CLI git-svn-id: http://svn.pjsip.org/repos/pjproject/trunk@4440 74dad513-b988-da41-8d7b-12977e46ad98 --- pjlib-util/build/Makefile | 7 +- pjlib-util/build/pjlib_util.vcproj | 9644 ++++++++++++++------------- pjlib-util/include/pjlib-util/cli.h | 529 ++ pjlib-util/include/pjlib-util/cli_console.h | 117 + pjlib-util/include/pjlib-util/cli_imp.h | 208 + pjlib-util/include/pjlib-util/cli_telnet.h | 120 + pjlib-util/include/pjlib-util/config.h | 100 + pjlib-util/include/pjlib-util/errno.h | 54 + pjlib-util/src/pjlib-util/cli.c | 1206 ++++ pjlib-util/src/pjlib-util/cli_console.c | 540 ++ pjlib-util/src/pjlib-util/cli_telnet.c | 1786 +++++ pjlib-util/src/pjlib-util/errno.c | 10 + 12 files changed, 9510 insertions(+), 4811 deletions(-) create mode 100644 pjlib-util/include/pjlib-util/cli.h create mode 100644 pjlib-util/include/pjlib-util/cli_console.h create mode 100644 pjlib-util/include/pjlib-util/cli_imp.h create mode 100644 pjlib-util/include/pjlib-util/cli_telnet.h create mode 100644 pjlib-util/src/pjlib-util/cli.c create mode 100644 pjlib-util/src/pjlib-util/cli_console.c create mode 100644 pjlib-util/src/pjlib-util/cli_telnet.c (limited to 'pjlib-util') diff --git a/pjlib-util/build/Makefile b/pjlib-util/build/Makefile index d2ad65a8..ca57e7e4 100644 --- a/pjlib-util/build/Makefile +++ b/pjlib-util/build/Makefile @@ -28,9 +28,10 @@ export _LDFLAGS := $(subst /,$(HOST_PSEP),$(PJLIB_UTIL_LIB)) \ # export PJLIB_UTIL_SRCDIR = ../src/pjlib-util export PJLIB_UTIL_OBJS += $(OS_OBJS) $(M_OBJS) $(CC_OBJS) $(HOST_OBJS) \ - base64.o crc32.o errno.o dns.o dns_dump.o dns_server.o \ - getopt.o hmac_md5.o hmac_sha1.o http_client.o md5.o pcap.o resolver.o \ - scanner.o sha1.o srv_resolver.o string.o stun_simple.o \ + base64.o cli.o cli_console.o cli_telnet.o crc32.o errno.o dns.o \ + dns_dump.o dns_server.o getopt.o hmac_md5.o hmac_sha1.o \ + http_client.o md5.o pcap.o resolver.o scanner.o sha1.o \ + srv_resolver.o string.o stun_simple.o \ stun_simple_client.o xml.o export PJLIB_UTIL_CFLAGS += $(_CFLAGS) diff --git a/pjlib-util/build/pjlib_util.vcproj b/pjlib-util/build/pjlib_util.vcproj index 4eb8cadf..11827c2f 100644 --- a/pjlib-util/build/pjlib_util.vcproj +++ b/pjlib-util/build/pjlib_util.vcproj @@ -1,4808 +1,4836 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pjlib-util/include/pjlib-util/cli.h b/pjlib-util/include/pjlib-util/cli.h new file mode 100644 index 00000000..1244c605 --- /dev/null +++ b/pjlib-util/include/pjlib-util/cli.h @@ -0,0 +1,529 @@ +/* $Id$ */ +/* + * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#ifndef __PJLIB_UTIL_CLI_H__ +#define __PJLIB_UTIL_CLI_H__ + +/** + * @file cli.h + * @brief Command Line Interface + */ + +#include +#include + + +PJ_BEGIN_DECL + +/** + * @defgroup PJLIB_UTIL_CLI Command Line Interface Framework + * @{ + * A CLI framework features an interface for defining command specification, + * parsing, and executing a command. + * It also features an interface to communicate with various front-ends, + * such as console, telnet. + * Application normally needs only one CLI instance to be created. + * On special cases, application could also create multiple CLI + * instances, with each instance has specific command structure. + * +\verbatim +| vid help Show this help screen | +| vid enable|disable Enable or disable video in next offer/answer | +| vid call add Add video stream for current call | +| vid call cap N ID Set capture dev ID for stream #N in current call | +| disable_codec g711|g722 Show this help screen | + + + + + + + + + + + + + + + + + + +\endverbatim + */ + +/** + * This opaque structure represents a CLI application. A CLI application is + * the root placeholder of other CLI objects. In an application, one (and + * normally only one) CLI application instance needs to be created. + */ +typedef struct pj_cli_t pj_cli_t; + +/** + * Type of command id. + */ +typedef int pj_cli_cmd_id; + +/** + * This describes the parameters to be specified when creating a CLI + * application with pj_cli_create(). Application MUST initialize this + * structure by calling pj_cli_cfg_default() before using it. + */ +typedef struct pj_cli_cfg +{ + /** + * The application name, which will be used in places such as logs. + * This field is mandatory. + */ + pj_str_t name; + + /** + * Optional application title, which will be used in places such as + * window title. If not specified, the application name will be used + * as the title. + */ + pj_str_t title; + + /** + * The pool factory where all memory allocations will be taken from. + * This field is mandatory. + */ + pj_pool_factory *pf; + +} pj_cli_cfg; + +/** + * Type of argument id. + */ +typedef int pj_cli_arg_id; + +/** + * Forward declaration of pj_cli_cmd_spec structure. + */ +typedef struct pj_cli_cmd_spec pj_cli_cmd_spec; + +/** + * Forward declaration for pj_cli_sess, which will be declared in cli_imp.h. + */ +typedef struct pj_cli_sess pj_cli_sess; + +/** + * Forward declaration for CLI front-end. + */ +typedef struct pj_cli_front_end pj_cli_front_end; + +/** + * Forward declaration for CLI argument spec structure. + */ +typedef struct pj_cli_arg_spec pj_cli_arg_spec; + +/** + * This structure contains the command to be executed by command handler. + */ +typedef struct pj_cli_cmd_val +{ + /** The session on which the command was executed on. */ + pj_cli_sess *sess; + + /** The command specification being executed. */ + const pj_cli_cmd_spec *cmd; + + /** Number of argvs. */ + int argc; + + /** Array of args, with argv[0] specifies the name of the cmd. */ + pj_str_t argv[PJ_CLI_MAX_ARGS]; + +} pj_cli_cmd_val; + +/** + * This structure contains the hints information for the end user. + * This structure could contain either command or argument information. + * The front-end will format the information and present it to the user. + */ +typedef struct pj_cli_hint_info +{ + /** + * The hint value. + */ + pj_str_t name; + + /** + * The hint type. + */ + pj_str_t type; + + /** + * Helpful description of the hint value. + */ + pj_str_t desc; + +} pj_cli_hint_info; + +/** + * This structure contains extra information returned by pj_cli_sess_exec()/ + * pj_cli_sess_parse(). + * Upon return from the function, various other fields in this structure will + * be set by the function. + */ +typedef struct pj_cli_exec_info +{ + /** + * If command parsing failed, on return this will point to the location + * where the failure occurs, otherwise the value will be set to -1. + */ + int err_pos; + + /** + * If a command matching the command in the cmdline was found, on return + * this will be set to the command id of the command, otherwise it will be + * set to PJ_CLI_INVALID_CMD_ID. + */ + pj_cli_cmd_id cmd_id; + + /** + * If a command was executed, on return this will be set to the return + * value of the command, otherwise it will contain PJ_SUCCESS. + */ + pj_status_t cmd_ret; + + /** + * The number of hint elements + **/ + unsigned hint_cnt; + + /** + * If pj_cli_sess_parse() fails because of a missing argument or ambigous + * command/argument, the function returned PJ_CLI_EMISSINGARG or + * PJ_CLI_EAMBIGUOUS error. + * This field will contain the hint information. This is useful to give + * helpful information to the end_user. + */ + pj_cli_hint_info hint[PJ_CLI_MAX_HINTS]; + +} pj_cli_exec_info; + +/** + * This structure contains the information returned from the dynamic + * argument callback. + */ +typedef struct pj_cli_arg_choice_val +{ + /** + * The argument choice value + */ + pj_str_t value; + + /** + * Helpful description of the choice value. This text will be used when + * displaying the help texts for the choice value + */ + pj_str_t desc; + +} pj_cli_arg_choice_val; + +/** + * This structure contains the parameters for pj_cli_get_dyn_choice + */ +typedef struct pj_cli_dyn_choice_param +{ + /** + * The session on which the command was executed on. + */ + pj_cli_sess *sess; + + /** + * The command being processed. + */ + pj_cli_cmd_spec *cmd; + + /** + * The argument id. + */ + pj_cli_arg_id arg_id; + + /** + * The maximum number of values that the choice can hold. + */ + unsigned max_cnt; + + /** + * The pool to allocate memory from. + */ + pj_pool_t *pool; + + /** + * The choice values count. + */ + unsigned cnt; + + /** + * Array containing the valid choice values. + */ + pj_cli_arg_choice_val choice[PJ_CLI_MAX_CHOICE_VAL]; +} pj_cli_dyn_choice_param; + +/** + * This specifies the callback type for argument handlers, which will be + * called to get the valid values of the choice type arguments. + */ +typedef void (*pj_cli_get_dyn_choice) (pj_cli_dyn_choice_param *param); + +/** + * This specifies the callback type for command handlers, which will be + * executed when the specified command is invoked. + * + * @param cmd_val The command that is specified by the user. + * + * @return Return the status of the command execution. + */ +typedef pj_status_t (*pj_cli_cmd_handler)(pj_cli_cmd_val *cval); + +/** + * Write a log message to the CLI application. The CLI application + * will send the log message to all the registered front-ends. + * + * @param cli The CLI application instance. + * @param level Verbosity level of this message message. + * @param buffer The message itself. + * @param len Length of this message. + */ +PJ_DECL(void) pj_cli_write_log(pj_cli_t *cli, + int level, + const char *buffer, + int len); + +/** + * Create a new CLI application instance. + * + * @param cfg CLI application creation parameters. + * @param p_cli Pointer to receive the returned instance. + * + * @return PJ_SUCCESS on success, or the appropriate error code. + */ +PJ_DECL(pj_status_t) pj_cli_create(pj_cli_cfg *cfg, + pj_cli_t **p_cli); + +/** + * This specifies the function to get the id of the specified command + * + * @param cmd The specified command. + * + * @return The command id + */ +PJ_DECL(pj_cli_cmd_id) pj_cli_get_cmd_id(const pj_cli_cmd_spec *cmd); + +/** + * Get the internal parameter of the CLI instance. + * + * @param cli The CLI application instance. + * + * @return CLI parameter instance. + */ +PJ_DECL(pj_cli_cfg*) pj_cli_get_param(pj_cli_t *cli); + +/** + * Call this to signal application shutdown. Typically application would + * call this from it's "Quit" menu or similar command to quit the + * application. + * + * See also pj_cli_sess_end_session() to end a session instead of quitting the + * whole application. + * + * @param cli The CLI application instance. + * @param req The session on which the shutdown request is + * received. + * @param restart Indicate whether application restart is wanted. + */ +PJ_DECL(void) pj_cli_quit(pj_cli_t *cli, pj_cli_sess *req, + pj_bool_t restart); +/** + * Check if application shutdown or restart has been requested. + * + * @param cli The CLI application instance. + * + * @return PJ_TRUE if pj_cli_quit() has been called. + */ +PJ_DECL(pj_bool_t) pj_cli_is_quitting(pj_cli_t *cli); + +/** + * Check if application restart has been requested. + * + * @param cli The CLI application instance. + * + * @return PJ_TRUE if pj_cli_quit() has been called with + * restart parameter set. + */ +PJ_DECL(pj_bool_t) pj_cli_is_restarting(pj_cli_t *cli); + +/** + * Destroy a CLI application instance. This would also close all sessions + * currently running for this CLI application. + * + * @param cli The CLI application. + */ +PJ_DECL(void) pj_cli_destroy(pj_cli_t *cli); + +/** + * Initialize a pj_cli_cfg with its default values. + * + * @param param The instance to be initialized. + */ +PJ_DECL(void) pj_cli_cfg_default(pj_cli_cfg *param); + +/** + * Register a front end to the CLI application. + * + * @param CLI The CLI application. + * @param fe The CLI front end to be registered. + */ +PJ_DECL(void) pj_cli_register_front_end(pj_cli_t *cli, + pj_cli_front_end *fe); + +/** + * Create a new complete command specification from an XML node text and + * register it to the CLI application. + * + * @param cli The CLI application. + * @param group Optional group to which this command will be added + * to, or specify NULL if this command is a root + * command. + * @param xml Input string containing XML node text for the + * command. + * @param handler Function handler for the command. This must be NULL + * if the command specifies a command group. + * @param p_cmd Optional pointer to store the newly created + * specification. + * @param get_choice Function handler for the argument. Specify this for + * dynamic choice type arguments. + * + * @return PJ_SUCCESS on success, or the appropriate error code. + */ +PJ_DECL(pj_status_t) pj_cli_add_cmd_from_xml(pj_cli_t *cli, + pj_cli_cmd_spec *group, + const pj_str_t *xml, + pj_cli_cmd_handler handler, + pj_cli_cmd_spec **p_cmd, + pj_cli_get_dyn_choice get_choice); +/** + * Initialize pj_cli_exec_info with its default values. + * + * @param param The param to be initialized. + */ +PJ_DECL(void) pj_cli_exec_info_default(pj_cli_exec_info *param); + +/** + * Write a log message to the specific CLI session. + * + * @param sess The CLI active session. + * @param buffer The message itself. + * @param len Length of this message. + */ +PJ_DECL(void) pj_cli_sess_write_msg(pj_cli_sess *sess, + const char *buffer, + int len); + +/** + * Parse an input cmdline string. The first word of the command line is the + * command itself, which will be matched against command specifications + * registered in the CLI application. + * + * Zero or more arguments follow the command name. Arguments are separated by + * one or more whitespaces. Argument may be placed inside a pair of quotes, + * double quotes, '{' and '}', or '[' and ']' pairs. This is useful when the + * argument itself contains whitespaces or other restricted characters. If + * the quote character itself is to appear in the argument, the argument then + * must be quoted with different quote characters. There is no character + * escaping facility provided by this function (such as the use of backslash + * '\' character). + * + * The cmdline may be followed by an extra newline (LF or CR-LF characters), + * which will be removed by the function. However any more characters + * following this newline will cause an error to be returned. + * + * @param sess The CLI session. + * @param cmdline The command line string to be parsed. + * @param val Structure to store the parsing result. + * @param pool The pool to allocate memory from. + * @param info Additional info to be returned regarding the parsing. + * + * @return This function returns the status of the parsing, + * which can be one of the following : + * - PJ_SUCCESS: a command was executed successfully. + * - PJ_EINVAL: invalid parameter to this function. + * - PJ_ENOTFOUND: command is not found. + * - PJ_CLI_EAMBIGUOUS: command/argument is ambiguous. + * - PJ_CLI_EMISSINGARG: missing argument. + * - PJ_CLI_EINVARG: invalid command argument. + * - PJ_CLI_EEXIT: "exit" has been called to end + * the current session. This is a signal for the + * application to end it's main loop. + */ +PJ_DECL(pj_status_t) pj_cli_sess_parse(pj_cli_sess *sess, + char *cmdline, + pj_cli_cmd_val *val, + pj_pool_t *pool, + pj_cli_exec_info *info); + +/** + * End the specified session, and destroy it to release all resources used + * by the session. + * + * See also pj_cli_sess and pj_cli_front_end for more info regarding the + * creation process. + * See also pj_cli_quit() to quit the whole application instead. + * + * @param sess The CLI session to be destroyed. + */ +PJ_DECL(void) pj_cli_sess_end_session(pj_cli_sess *sess); + +/** + * Execute a command line. This function will parse the input string to find + * the appropriate command and verify whether the string matches the command + * specifications. If matches, the command will be executed, and the return + * value of the command will be set in the \a cmd_ret field of the \a info + * argument, if specified. + * + * See also pj_cli_sess_parse() for more info regarding the cmdline format. + * + * @param sess The CLI session. + * @param cmdline The command line string to be executed. + * @param pool The pool to allocate memory from. + * @param info Optional pointer to receive additional information + * related to the execution of the command (such as + * the command return value). + * + * @return This function returns the status of the command + * parsing and execution (note that the return value + * of the handler itself will be returned in \a info + * argument, if specified). Please see the return value + * of pj_cli_sess_parse() for possible return values. + */ +PJ_DECL(pj_status_t) pj_cli_sess_exec(pj_cli_sess *sess, + char *cmdline, + pj_pool_t *pool, + pj_cli_exec_info *info); + +/** + * @} + */ + +PJ_END_DECL + +#endif /* __PJLIB_UTIL_CLI_H__ */ diff --git a/pjlib-util/include/pjlib-util/cli_console.h b/pjlib-util/include/pjlib-util/cli_console.h new file mode 100644 index 00000000..5b68ead8 --- /dev/null +++ b/pjlib-util/include/pjlib-util/cli_console.h @@ -0,0 +1,117 @@ +/* $Id$ */ +/* + * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#ifndef __PJLIB_UTIL_CLI_CONSOLE_H__ +#define __PJLIB_UTIL_CLI_CONSOLE_H__ + +/** + * @file cli_console.h + * @brief Command Line Interface Console Front End API + */ + +#include + + +PJ_BEGIN_DECL + +/** + * @ingroup PJLIB_UTIL_CLI_IMP + * @{ + * + */ + + +/** + * This structure contains various options for CLI console front-end. + * Application must call pj_cli_console_cfg_default() to initialize + * this structure with its default values. + */ +typedef struct pj_cli_console_cfg +{ + /** + * Default log verbosity level for the session. + * + * Default value: PJ_CLI_CONSOLE_LOG_LEVEL + */ + int log_level; + + /** + * Specify text message as a prompt string to user. + * + * Default: empty + */ + pj_str_t prompt_str; + + /** + * Specify the command to quit the application. + * + * Default: empty + */ + pj_str_t quit_command; + +} pj_cli_console_cfg; + + +/** + * Initialize pj_cli_console_cfg with its default values. + * + * @param param The structure to be initialized. + */ +PJ_DECL(void) pj_cli_console_cfg_default(pj_cli_console_cfg *param); + + +/** + * Create a console front-end for the specified CLI application, and return + * the only session instance for the console front end. On Windows operating + * system, this may open a new console window. + * + * @param cli The CLI application instance. + * @param param Optional console CLI parameters. If this value is + * NULL, default parameters will be used. + * @param p_sess Pointer to receive the session instance for the + * console front end. + * @param p_fe Optional pointer to receive the front-end instance + * of the console front-end just created. + * + * @return PJ_SUCCESS on success, or the appropriate error code. + */ +PJ_DECL(pj_status_t) pj_cli_console_create(pj_cli_t *cli, + const pj_cli_console_cfg *param, + pj_cli_sess **p_sess, + pj_cli_front_end **p_fe); + +/** + * Retrieve a cmdline from console stdin and process the input accordingly. + * + * @param sess The CLI session. + * @param buf Pointer to receive the buffer. + * @param maxlen Maximum length to read. + * + * @return PJ_SUCCESS if an input was read + */ +PJ_DECL(pj_status_t) pj_cli_console_process(pj_cli_sess *sess, + char *buf, + unsigned maxlen); + +/** + * @} + */ + +PJ_END_DECL + +#endif /* __PJLIB_UTIL_CLI_CONSOLE_H__ */ diff --git a/pjlib-util/include/pjlib-util/cli_imp.h b/pjlib-util/include/pjlib-util/cli_imp.h new file mode 100644 index 00000000..c79a8d3f --- /dev/null +++ b/pjlib-util/include/pjlib-util/cli_imp.h @@ -0,0 +1,208 @@ +/* $Id$ */ +/* + * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#ifndef __PJLIB_UTIL_CLI_IMP_H__ +#define __PJLIB_UTIL_CLI_IMP_H__ + +/** + * @file cli_imp.h + * @brief Command Line Interface Implementor's API + */ + +#include + + +PJ_BEGIN_DECL + +/** + * @defgroup PJLIB_UTIL_CLI_IMP Command Line Interface Implementor's API + * @ingroup PJLIB_UTIL_CLI + * @{ + * + */ + +/** + * Default log level for console sessions. + */ +#ifndef PJ_CLI_CONSOLE_LOG_LEVEL +# define PJ_CLI_CONSOLE_LOG_LEVEL PJ_LOG_MAX_LEVEL +#endif + +/** + * Default log level for telnet sessions. + */ +#ifndef PJ_CLI_TELNET_LOG_LEVEL +# define PJ_CLI_TELNET_LOG_LEVEL 3 +#endif + +/** + * Default port number for telnet daemon. + */ +#ifndef PJ_CLI_TELNET_PORT +# define PJ_CLI_TELNET_PORT 0 +#endif + +/** + * This enumeration specifies front end types. + */ +typedef enum pj_cli_front_end_type +{ + PJ_CLI_CONSOLE_FRONT_END, /**< Console front end. */ + PJ_CLI_TELNET_FRONT_END, /**< Telnet front end. */ + PJ_CLI_HTTP_FRONT_END, /**< HTTP front end. */ + PJ_CLI_GUI_FRONT_END /**< GUI front end. */ +} pj_cli_front_end_type; + + +/** + * Front end operations. Only the CLI should call these functions + * directly. + */ +typedef struct pj_cli_front_end_op +{ + /** + * Callback to write a log message to the appropriate sessions belonging + * to this front end. The front end would only send the log message to + * the session if the session's log verbosity level is greater than the + * level of this log message. + * + * @param fe The front end. + * @param level Verbosity level of this message message. + * @param data The message itself. + * @param len Length of this message. + */ + void (*on_write_log)(pj_cli_front_end *fe, int level, + const char *data, int len); + + /** + * Callback to be called when the application is quitting, to signal the + * front-end to end its main loop or any currently blocking functions, + * if any. + * + * @param fe The front end. + * @param req The session which requested the application quit. + */ + void (*on_quit)(pj_cli_front_end *fe, pj_cli_sess *req); + + /** + * Callback to be called to close and self destroy the front-end. This + * must also close any active sessions created by this front-ends. + * + * @param fe The front end. + */ + void (*on_destroy)(pj_cli_front_end *fe); + +} pj_cli_front_end_op; + + +/** + * This structure describes common properties of CLI front-ends. A front- + * end is a mean to interact with end user, for example the CLI application + * may interact with console, telnet, web, or even a GUI. + * + * Each end user's interaction will create an instance of pj_cli_sess. + * + * Application instantiates the front end by calling the appropriate + * function to instantiate them. + */ +struct pj_cli_front_end +{ + /** + * Linked list members + */ + PJ_DECL_LIST_MEMBER(struct pj_cli_front_end); + + /** + * Front end type. + */ + pj_cli_front_end_type type; + + /** + * The CLI application. + */ + pj_cli_t *cli; + + /** + * Front end operations. + */ + pj_cli_front_end_op *op; +}; + + +/** + * Session operations. + */ +typedef struct pj_cli_sess_op +{ + /** + * Callback to be called to close and self destroy the session. + * + * @param sess The session to destroy. + */ + void (*destroy)(pj_cli_sess *sess); + +} pj_cli_sess_op; + + +/** + * This structure describes common properties of a CLI session. A CLI session + * is the interaction of an end user to the CLI application via a specific + * renderer, where the renderer can be console, telnet, web, or a GUI app for + * mobile. A session is created by its renderer, and it's creation procedures + * vary among renderer (for example, a telnet session is created when the + * end user connects to the application, while a console session is always + * instantiated once the program is run). + */ +struct pj_cli_sess +{ + /** + * Linked list members + */ + PJ_DECL_LIST_MEMBER(struct pj_cli_sess); + + /** + * Pointer to the front-end instance which created this session. + */ + pj_cli_front_end *fe; + + /** + * Session operations. + */ + pj_cli_sess_op *op; + + /** + * Text containing session info, which is filled by the renderer when + * the session is created. + */ + pj_str_t info; + + /** + * Log verbosity of this session. + */ + int log_level; + +}; + +/** + * @} + */ + + +PJ_END_DECL + +#endif /* __PJLIB_UTIL_CLI_IMP_H__ */ diff --git a/pjlib-util/include/pjlib-util/cli_telnet.h b/pjlib-util/include/pjlib-util/cli_telnet.h new file mode 100644 index 00000000..bf8dafbc --- /dev/null +++ b/pjlib-util/include/pjlib-util/cli_telnet.h @@ -0,0 +1,120 @@ +/* $Id$ */ +/* + * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#ifndef __PJLIB_UTIL_CLI_TELNET_H__ +#define __PJLIB_UTIL_CLI_TELNET_H__ + +/** + * @file cli_telnet.h + * @brief Command Line Interface Telnet Front End API + */ + +#include + +PJ_BEGIN_DECL + +/** + * @ingroup PJLIB_UTIL_CLI_IMP + * @{ + * + */ + + +/** + * This structure contains various options to instantiate the telnet daemon. + * Application must call pj_cli_telnet_cfg_default() to initialize + * this structure with its default values. + */ +typedef struct pj_cli_telnet_cfg +{ + /** + * Listening port number. The value may be 0 to let the system choose + * the first available port. + * + * Default value: PJ_CLI_TELNET_PORT + */ + pj_uint16_t port; + + /** + * Ioqueue instance to be used. If this field is NULL, an internal + * ioqueue and worker thread will be created. + */ + pj_ioqueue_t *ioqueue; + + /** + * Default log verbosity level for the session. + * + * Default value: PJ_CLI_TELNET_LOG_LEVEL + */ + int log_level; + + /** + * Specify a password to be asked to the end user to access the + * application. + * + * Default: empty (no password) + */ + pj_str_t passwd; + + /** + * Specify text message to be displayed to newly connected users. + * + * Default: empty + */ + pj_str_t welcome_msg; + + /** + * Specify text message as a prompt string to user. + * + * Default: empty + */ + pj_str_t prompt_str; + +} pj_cli_telnet_cfg; + + +/** + * Initialize pj_cli_telnet_cfg with its default values. + * + * @param param The structure to be initialized. + */ +PJ_DECL(void) pj_cli_telnet_cfg_default(pj_cli_telnet_cfg *param); + + +/** + * Create, initialize, and start a telnet daemon for the application. + * + * @param cli The CLI application instance. + * @param param Optional parameters for creating the telnet daemon. + * If this value is NULL, default parameters will be used. + * @param p_fe Optional pointer to receive the front-end instance + * of the telnet front-end just created. + * + * @return PJ_SUCCESS on success, or the appropriate error code. + */ +PJ_DECL(pj_status_t) pj_cli_telnet_create(pj_cli_t *cli, + pj_cli_telnet_cfg *param, + pj_cli_front_end **p_fe); + +/** + * @} + */ + +PJ_END_DECL + +#endif /* __PJLIB_UTIL_CLI_TELNET_H__ */ diff --git a/pjlib-util/include/pjlib-util/config.h b/pjlib-util/include/pjlib-util/config.h index ff3c4e6d..19821c0b 100644 --- a/pjlib-util/include/pjlib-util/config.h +++ b/pjlib-util/include/pjlib-util/config.h @@ -266,6 +266,106 @@ # define PJ_HTTP_DEFAULT_TIMEOUT (60000) #endif +/* ************************************************************************** + * CLI configuration + */ + +/** + * Initial pool size for CLI. + * Default: 1024 bytes + */ +#ifndef PJ_CLI_POOL_SIZE +# define PJ_CLI_POOL_SIZE 1024 +#endif + +/** + * Pool increment size for CLI. + * Default: 512 bytes + */ +#ifndef PJ_CLI_POOL_INC +# define PJ_CLI_POOL_INC 512 +#endif + +/** + * Maximum length of command buffer. + * Default: 120 + */ +#ifndef PJ_CLI_MAX_CMDBUF +# define PJ_CLI_MAX_CMDBUF 120 +#endif + +/** + * Maximum command arguments. + * Default: 8 + */ +#ifndef PJ_CLI_MAX_ARGS +# define PJ_CLI_MAX_ARGS 8 +#endif + +/** + * Maximum number of hints. + * Default: 32 + */ +#ifndef PJ_CLI_MAX_HINTS +# define PJ_CLI_MAX_HINTS 32 +#endif + +/** + * Maximum short name version (shortcuts) for a command. + * Default: 4 + */ +#ifndef PJ_CLI_MAX_SHORTCUTS +# define PJ_CLI_MAX_SHORTCUTS 4 +#endif + +/** + * Initial pool size for console CLI. + * Default: 256 bytes + */ +#ifndef PJ_CLI_CONSOLE_POOL_SIZE +# define PJ_CLI_CONSOLE_POOL_SIZE 256 +#endif + +/** + * Pool increment size for console CLI. + * Default: 256 bytes + */ +#ifndef PJ_CLI_CONSOLE_POOL_INC +# define PJ_CLI_CONSOLE_POOL_INC 256 +#endif + +/** + * Initial pool size for telnet CLI. + * Default: 1024 bytes + */ +#ifndef PJ_CLI_TELNET_POOL_SIZE +# define PJ_CLI_TELNET_POOL_SIZE 1024 +#endif + +/** + * Pool increment size for telnet CLI. + * Default: 512 bytes + */ +#ifndef PJ_CLI_TELNET_POOL_INC +# define PJ_CLI_TELNET_POOL_INC 512 +#endif + +/** + * Maximum number of argument values of choice type. + * Default: 16 + */ +#ifndef PJ_CLI_MAX_CHOICE_VAL +# define PJ_CLI_MAX_CHOICE_VAL 16 +#endif + +/** + * Maximum number of command history. + * Default: 16 + */ +#ifndef PJ_CLI_MAX_CMD_HISTORY +# define PJ_CLI_MAX_CMD_HISTORY 16 +#endif + /** * @} */ diff --git a/pjlib-util/include/pjlib-util/errno.h b/pjlib-util/include/pjlib-util/errno.h index 5e42653f..e224c6a9 100644 --- a/pjlib-util/include/pjlib-util/errno.h +++ b/pjlib-util/include/pjlib-util/errno.h @@ -386,6 +386,60 @@ */ #define PJLIB_UTIL_EHTTPLOST (PJLIB_UTIL_ERRNO_START+155)/* 320155 */ +/************************************************************ + * CLI ERROR + ***********************************************************/ + +/** + * @hideinitializer + * End the current session. This is a special error code returned by + * pj_cli_sess_exec() to indicate that "exit" or equivalent command has been + * called to end the current session. + */ +#define PJ_CLI_EEXIT (PJLIB_UTIL_ERRNO_START+201)/* 320201 */ +/** + * @hideinitializer + * A required CLI argument is not specified. + */ +#define PJ_CLI_EMISSINGARG (PJLIB_UTIL_ERRNO_START+202)/* 320202 */ + /** + * @hideinitializer + * Too many CLI arguments. + */ +#define PJ_CLI_ETOOMANYARGS (PJLIB_UTIL_ERRNO_START+203)/* 320203 */ +/** + * @hideinitializer + * Invalid CLI argument. Typically this is caused by extra characters + * specified in the command line which does not match any arguments. + */ +#define PJ_CLI_EINVARG (PJLIB_UTIL_ERRNO_START+204)/* 320204 */ +/** + * @hideinitializer + * CLI command with the specified name already exist. + */ +#define PJ_CLI_EBADNAME (PJLIB_UTIL_ERRNO_START+205)/* 320205 */ +/** + * @hideinitializer + * CLI command with the specified id already exist. + */ +#define PJ_CLI_EBADID (PJLIB_UTIL_ERRNO_START+206)/* 320206 */ +/** + * @hideinitializer + * Invalid XML format for CLI command specification. + */ +#define PJ_CLI_EBADXML (PJLIB_UTIL_ERRNO_START+207)/* 320207 */ +/** + * @hideinitializer + * CLI command entered by user match with more than one command/argument + * specification. + */ +#define PJ_CLI_EAMBIGUOUS (PJLIB_UTIL_ERRNO_START+208)/* 320208 */ +/** + * @hideinitializer + * Telnet connection lost. + */ +#define PJ_CLI_ETELNETLOST (PJLIB_UTIL_ERRNO_START+211)/* 320211 */ + /** * @} */ diff --git a/pjlib-util/src/pjlib-util/cli.c b/pjlib-util/src/pjlib-util/cli.c new file mode 100644 index 00000000..68cd6f04 --- /dev/null +++ b/pjlib-util/src/pjlib-util/cli.c @@ -0,0 +1,1206 @@ +/* $Id$ */ +/* + * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CMD_HASH_TABLE_SIZE 63 /* Hash table size */ + +#define CLI_CMD_CHANGE_LOG 30000 +#define CLI_CMD_EXIT 30001 + +#if 1 + /* Enable some tracing */ + #define THIS_FILE "cli.c" + #define TRACE_(arg) PJ_LOG(3,arg) +#else + #define TRACE_(arg) +#endif + +/** + * This structure describes the full specification of a CLI command. A CLI + * command mainly consists of the name of the command, zero or more arguments, + * and a callback function to be called to execute the command. + * + * Application can create this specification by forming an XML document and + * calling pj_cli_add_cmd_from_xml() to instantiate the spec. A sample XML + * document containing a command spec is as follows: + * + \verbatim + + + + + + \endverbatim + */ +struct pj_cli_cmd_spec +{ + /** + * To make list of child cmds. + */ + PJ_DECL_LIST_MEMBER(struct pj_cli_cmd_spec); + + /** + * Command ID assigned to this command by the application during command + * creation. If this value is PJ_CLI_CMD_ID_GROUP (-2), then this is + * a command group and it can't be executed. + */ + pj_cli_cmd_id id; + + /** + * The command name. + */ + pj_str_t name; + + /** + * The full description of the command. + */ + pj_str_t desc; + + /** + * Number of optional shortcuts + */ + unsigned sc_cnt; + + /** + * Optional array of shortcuts, if any. Shortcut is a short name version + * of the command. If the command doesn't have any shortcuts, this + * will be initialized to NULL. + */ + pj_str_t *sc; + + /** + * The command handler, to be executed when a command matching this command + * specification is invoked by the end user. The value may be NULL if this + * is a command group. + */ + pj_cli_cmd_handler handler; + + /** + * Number of arguments. + */ + unsigned arg_cnt; + + /** + * Array of arguments. + */ + pj_cli_arg_spec *arg; + + /** + * Child commands, if any. A command will only have subcommands if it is + * a group. If the command doesn't have subcommands, this field will be + * initialized with NULL. + */ + pj_cli_cmd_spec *sub_cmd; +}; + +struct pj_cli_t +{ + pj_pool_t *pool; /* Pool to allocate memory from */ + pj_cli_cfg cfg; /* CLI configuration */ + pj_cli_cmd_spec root; /* Root of command tree structure */ + pj_cli_front_end fe_head; /* List of front-ends */ + pj_hash_table_t *cmd_name_hash; /* Command name hash table */ + pj_hash_table_t *cmd_id_hash; /* Command id hash table */ + + pj_bool_t is_quitting; + pj_bool_t is_restarting; +}; + +/** + * Reserved command id constants. + */ +typedef enum pj_cli_std_cmd_id +{ + /** + * Constant to indicate an invalid command id. + */ + PJ_CLI_INVALID_CMD_ID = -1, + + /** + * A special command id to indicate that a command id denotes + * a command group. + */ + PJ_CLI_CMD_ID_GROUP = -2 + +} pj_cli_std_cmd_id; + +/** + * This describes the type of an argument (pj_cli_arg_spec). + */ +typedef enum pj_cli_arg_type +{ + /** + * Unformatted string. + */ + PJ_CLI_ARG_TEXT, + + /** + * An integral number. + */ + PJ_CLI_ARG_INT, + + /** + * Choice type + */ + PJ_CLI_ARG_CHOICE + +} pj_cli_arg_type; + +struct arg_type +{ + const pj_str_t msg; +} arg_type[3] = +{ + {{"Text", 4}}, + {{"Int", 3}}, + {{"Choice", 6}} +}; + +/** + * This structure describe the specification of a command argument. + */ +struct pj_cli_arg_spec +{ + /** + * Argument id + */ + pj_cli_arg_id id; + + /** + * Argument name. + */ + pj_str_t name; + + /** + * Helpful description of the argument. This text will be used when + * displaying help texts for the command/argument. + */ + pj_str_t desc; + + /** + * Argument type, which will be used for rendering the argument and + * to perform basic validation against an input value. + */ + pj_cli_arg_type type; + + /** + * Argument status + */ + pj_bool_t optional; + + /** + * Validate choice values + */ + pj_bool_t validate; + + /** + * Static Choice Values count + */ + unsigned stat_choice_cnt; + + /** + * Static Choice Values + */ + pj_cli_arg_choice_val *stat_choice_val; + + /** + * Argument callback to get the valid values + */ + pj_cli_get_dyn_choice get_dyn_choice; + +}; + +/** + * This describe the parse mode of the command line + */ +typedef enum pj_cli_parse_mode { + PARSE_NONE, + PARSE_COMPLETION, /* Complete the command line */ + PARSE_NEXT_AVAIL, /* Find the next available command line */ + PARSE_EXEC /* Exec the command line */ +} pj_cli_parse_mode; + +/** + * This is used to get the matched command/argument from the + * command/argument structure. + * + * @param sess The session on which the command is execute on. + * @param cmd The active command. + * @param cmd_val The command value to match. + * @param argc The number of argument that the + * current active command have. + * @param pool The memory pool to allocate memory. + * @param get_cmd Set true to search matching command from sub command. + * @param parse_mode The parse mode. + * @param p_cmd The command that mathes the command value. + * @param info The output information containing any hints for + * matching command/arg. + * @return This function return the status of the + * matching process.Please see the return value + * of pj_cli_sess_parse() for possible return values. + */ +static pj_status_t get_available_cmds(pj_cli_sess *sess, + pj_cli_cmd_spec *cmd, + pj_str_t *cmd_val, + unsigned argc, + pj_pool_t *pool, + pj_bool_t get_cmd, + pj_cli_parse_mode parse_mode, + pj_cli_cmd_spec **p_cmd, + pj_cli_exec_info *info); + +PJ_DEF(pj_cli_cmd_id) pj_cli_get_cmd_id(const pj_cli_cmd_spec *cmd) +{ + return cmd->id; +} + +PJ_DEF(void) pj_cli_cfg_default(pj_cli_cfg *param) +{ + pj_assert(param); + pj_bzero(param, sizeof(*param)); + pj_strset2(¶m->name, ""); +} + +PJ_DEF(void) pj_cli_exec_info_default(pj_cli_exec_info *param) +{ + pj_assert(param); + pj_bzero(param, sizeof(*param)); + param->err_pos = -1; + param->cmd_id = PJ_CLI_INVALID_CMD_ID; + param->cmd_ret = PJ_SUCCESS; +} + +PJ_DEF(void) pj_cli_write_log(pj_cli_t *cli, + int level, + const char *buffer, + int len) +{ + struct pj_cli_front_end *fe; + + pj_assert(cli); + + fe = cli->fe_head.next; + while (fe != &cli->fe_head) { + if (fe->op && fe->op->on_write_log) + (*fe->op->on_write_log)(fe, level, buffer, len); + fe = fe->next; + } +} + +PJ_DECL(void) pj_cli_sess_write_msg(pj_cli_sess *sess, + const char *buffer, + int len) +{ + struct pj_cli_front_end *fe; + + pj_assert(sess); + + fe = sess->fe; + if (fe->op && fe->op->on_write_log) + (*fe->op->on_write_log)(fe, 0, buffer, len); +} + +/* Command handler */ +static pj_status_t cmd_handler(pj_cli_cmd_val *cval) +{ + unsigned level; + + switch(cval->cmd->id) { + case CLI_CMD_CHANGE_LOG: + level = pj_strtoul(&cval->argv[1]); + if (!level && cval->argv[1].slen > 0 && (cval->argv[1].ptr[0] < '0' || + cval->argv[1].ptr[0] > '9')) + { + return PJ_CLI_EINVARG; + } + cval->sess->log_level = level; + return PJ_SUCCESS; + case CLI_CMD_EXIT: + pj_cli_sess_end_session(cval->sess); + return PJ_CLI_EEXIT; + default: + return PJ_SUCCESS; + } +} + +PJ_DEF(pj_status_t) pj_cli_create(pj_cli_cfg *cfg, + pj_cli_t **p_cli) +{ + pj_pool_t *pool; + pj_cli_t *cli; + unsigned i; + + /* This is an example of the command structure */ + char* cmd_xmls[] = { + "" + " " + "", + "" + "", + }; + + PJ_ASSERT_RETURN(cfg && cfg->pf && p_cli, PJ_EINVAL); + + pool = pj_pool_create(cfg->pf, "cli", PJ_CLI_POOL_SIZE, + PJ_CLI_POOL_INC, NULL); + if (!pool) + return PJ_ENOMEM; + cli = PJ_POOL_ZALLOC_T(pool, struct pj_cli_t); + + pj_memcpy(&cli->cfg, cfg, sizeof(*cfg)); + cli->pool = pool; + pj_list_init(&cli->fe_head); + + cli->cmd_name_hash = pj_hash_create(pool, CMD_HASH_TABLE_SIZE); + cli->cmd_id_hash = pj_hash_create(pool, CMD_HASH_TABLE_SIZE); + + cli->root.sub_cmd = PJ_POOL_ZALLOC_T(pool, pj_cli_cmd_spec); + pj_list_init(cli->root.sub_cmd); + + /* Register some standard commands. */ + for (i = 0; i < sizeof(cmd_xmls)/sizeof(cmd_xmls[0]); i++) { + pj_str_t xml = pj_str(cmd_xmls[i]); + + if (pj_cli_add_cmd_from_xml(cli, NULL, &xml, + &cmd_handler, NULL, NULL) != PJ_SUCCESS) + { + TRACE_((THIS_FILE, "Failed to add command #%d", i)); + } + } + + *p_cli = cli; + + return PJ_SUCCESS; +} + +PJ_DEF(pj_cli_cfg*) pj_cli_get_param(pj_cli_t *cli) +{ + PJ_ASSERT_RETURN(cli, NULL); + + return &cli->cfg; +} + +PJ_DEF(void) pj_cli_register_front_end(pj_cli_t *cli, + pj_cli_front_end *fe) +{ + pj_list_push_back(&cli->fe_head, fe); +} + +PJ_DEF(void) pj_cli_quit(pj_cli_t *cli, pj_cli_sess *req, + pj_bool_t restart) +{ + pj_cli_front_end *fe; + + pj_assert(cli); + if (cli->is_quitting) + return; + + cli->is_quitting = PJ_TRUE; + cli->is_restarting = restart; + + fe = cli->fe_head.next; + while (fe != &cli->fe_head) { + if (fe->op && fe->op->on_quit) + (*fe->op->on_quit)(fe, req); + fe = fe->next; + } +} + +PJ_DEF(pj_bool_t) pj_cli_is_quitting(pj_cli_t *cli) +{ + PJ_ASSERT_RETURN(cli, PJ_FALSE); + + return cli->is_quitting; +} + +PJ_DEF(pj_bool_t) pj_cli_is_restarting(pj_cli_t *cli) +{ + PJ_ASSERT_RETURN(cli, PJ_FALSE); + + return cli->is_restarting; +} + +PJ_DEF(void) pj_cli_destroy(pj_cli_t *cli) +{ + pj_cli_front_end *fe; + + if (!cli) + return; + + if (!pj_cli_is_quitting(cli)) + pj_cli_quit(cli, NULL, PJ_FALSE); + + fe = cli->fe_head.next; + while (fe != &cli->fe_head) { + pj_list_erase(fe); + if (fe->op && fe->op->on_destroy) + (*fe->op->on_destroy)(fe); + + fe = cli->fe_head.next; + } + cli->is_quitting = PJ_FALSE; + pj_pool_release(cli->pool); +} + +PJ_DEF(void) pj_cli_sess_end_session(pj_cli_sess *sess) +{ + pj_assert(sess); + + if (sess->op && sess->op->destroy) + (*sess->op->destroy)(sess); +} + +/* Syntax error handler for parser. */ +static void on_syntax_error(pj_scanner *scanner) +{ + PJ_UNUSED_ARG(scanner); + PJ_THROW(PJ_EINVAL); +} + +/* Check if command already added to command hash */ +static pj_bool_t cmd_name_exists(pj_cli_t *cli, pj_cli_cmd_spec *group, + pj_str_t *cmd) +{ + pj_str_t cmd_val; + char cmd_ptr[64]; + + cmd_val.ptr = &cmd_ptr[0]; + cmd_val.slen = 0; + + if (group) { + char cmd_str[16]; + pj_ansi_sprintf(&cmd_str[0], "%d", group->id); + pj_strcat2(&cmd_val, &cmd_str[0]); + } + pj_strcat(&cmd_val, cmd); + return (pj_hash_get(cli->cmd_name_hash, + cmd_val.ptr, cmd_val.slen, NULL) != 0); +} + +/* Add command to the command hash */ +static void add_cmd_name(pj_cli_t *cli, pj_cli_cmd_spec *group, + pj_cli_cmd_spec *cmd, pj_str_t *cmd_name) +{ + pj_str_t cmd_val; + pj_str_t add_cmd; + char cmd_ptr[64]; + + cmd_val.ptr = &cmd_ptr[0]; + cmd_val.slen = 0; + + if (group) { + pj_strcat(&cmd_val, &group->name); + } + pj_strcat(&cmd_val, cmd_name); + pj_strdup(cli->pool, &add_cmd, &cmd_val); + + pj_hash_set(cli->pool, cli->cmd_name_hash, + cmd_val.ptr, cmd_val.slen, 0, cmd); +} + +/** + * This method is to parse and add the choice type + * argument values to command structure. + **/ +static pj_status_t add_choice_node(pj_cli_t *cli, + pj_xml_node *xml_node, + pj_cli_arg_spec *arg, + pj_cli_get_dyn_choice get_choice) +{ + pj_xml_node *choice_node; + pj_xml_node *sub_node; + pj_cli_arg_choice_val choice_values[PJ_CLI_MAX_CHOICE_VAL]; + pj_status_t status = PJ_SUCCESS; + + sub_node = xml_node; + arg->type = PJ_CLI_ARG_CHOICE; + arg->get_dyn_choice = get_choice; + + choice_node = sub_node->node_head.next; + while (choice_node != (pj_xml_node*)&sub_node->node_head) { + pj_xml_attr *choice_attr; + unsigned *stat_cnt = &arg->stat_choice_cnt; + pj_cli_arg_choice_val *choice_val = &choice_values[*stat_cnt]; + pj_bzero(choice_val, sizeof(*choice_val)); + + choice_attr = choice_node->attr_head.next; + while (choice_attr != &choice_node->attr_head) { + if (!pj_stricmp2(&choice_attr->name, "value")) { + pj_strassign(&choice_val->value, &choice_attr->value); + } else if (!pj_stricmp2(&choice_attr->name, "desc")) { + pj_strassign(&choice_val->desc, &choice_attr->value); + } + choice_attr = choice_attr->next; + } + if (++(*stat_cnt) >= PJ_CLI_MAX_CHOICE_VAL) + break; + choice_node = choice_node->next; + } + if (arg->stat_choice_cnt > 0) { + unsigned i; + + arg->stat_choice_val = (pj_cli_arg_choice_val *) + pj_pool_zalloc(cli->pool, + arg->stat_choice_cnt * + sizeof(pj_cli_arg_choice_val)); + + for (i = 0; i < arg->stat_choice_cnt; i++) { + pj_strdup(cli->pool, &arg->stat_choice_val[i].value, + &choice_values[i].value); + pj_strdup(cli->pool, &arg->stat_choice_val[i].desc, + &choice_values[i].desc); + } + } + return status; +} + +/** + * This method is to parse and add the argument attribute to command structure. + **/ +static pj_status_t add_arg_node(pj_cli_t *cli, + pj_xml_node *xml_node, + pj_cli_cmd_spec *cmd, + pj_cli_arg_spec *arg, + pj_cli_get_dyn_choice get_choice) +{ + pj_xml_attr *attr; + pj_status_t status = PJ_SUCCESS; + pj_xml_node *sub_node = xml_node; + + if (cmd->arg_cnt >= PJ_CLI_MAX_ARGS) + return PJ_CLI_ETOOMANYARGS; + + pj_bzero(arg, sizeof(*arg)); + attr = sub_node->attr_head.next; + arg->optional = PJ_FALSE; + arg->validate = PJ_TRUE; + while (attr != &sub_node->attr_head) { + if (!pj_stricmp2(&attr->name, "name")) { + pj_strassign(&arg->name, &attr->value); + } else if (!pj_stricmp2(&attr->name, "id")) { + arg->id = pj_strtol(&attr->value); + } else if (!pj_stricmp2(&attr->name, "type")) { + if (!pj_stricmp2(&attr->value, "text")) { + arg->type = PJ_CLI_ARG_TEXT; + } else if (!pj_stricmp2(&attr->value, "int")) { + arg->type = PJ_CLI_ARG_INT; + } else if (!pj_stricmp2(&attr->value, "choice")) { + /* Get choice value */ + add_choice_node(cli, xml_node, arg, get_choice); + } + } else if (!pj_stricmp2(&attr->name, "desc")) { + pj_strassign(&arg->desc, &attr->value); + } else if (!pj_stricmp2(&attr->name, "optional")) { + if (!pj_strcmp2(&attr->value, "1")) { + arg->optional = PJ_TRUE; + } + } else if (!pj_stricmp2(&attr->name, "validate")) { + if (!pj_strcmp2(&attr->value, "1")) { + arg->validate = PJ_TRUE; + } else { + arg->validate = PJ_FALSE; + } + } + attr = attr->next; + } + cmd->arg_cnt++; + return status; +} + +/** + * This method is to parse and add the command attribute to command structure. + **/ +static pj_status_t add_cmd_node(pj_cli_t *cli, + pj_cli_cmd_spec *group, + pj_xml_node *xml_node, + pj_cli_cmd_handler handler, + pj_cli_cmd_spec **p_cmd, + pj_cli_get_dyn_choice get_choice) +{ + pj_xml_node *root = xml_node; + pj_xml_attr *attr; + pj_xml_node *sub_node; + pj_cli_cmd_spec *cmd; + pj_cli_arg_spec args[PJ_CLI_MAX_ARGS]; + pj_str_t sc[PJ_CLI_MAX_SHORTCUTS]; + pj_status_t status = PJ_SUCCESS; + + if (pj_stricmp2(&root->name, "CMD")) + return PJ_EINVAL; + + /* Initialize the command spec */ + cmd = PJ_POOL_ZALLOC_T(cli->pool, struct pj_cli_cmd_spec); + + /* Get the command attributes */ + attr = root->attr_head.next; + while (attr != &root->attr_head) { + if (!pj_stricmp2(&attr->name, "name")) { + pj_strltrim(&attr->value); + if (!attr->value.slen || + cmd_name_exists(cli, group, &attr->value)) + { + return PJ_CLI_EBADNAME; + } + pj_strdup(cli->pool, &cmd->name, &attr->value); + } else if (!pj_stricmp2(&attr->name, "id")) { + pj_bool_t is_valid = PJ_FALSE; + if (attr->value.slen) { + pj_cli_cmd_id cmd_id = pj_strtol(&attr->value); + if (!pj_hash_get(cli->cmd_id_hash, &cmd_id, + sizeof(pj_cli_cmd_id), NULL)) + is_valid = PJ_TRUE; + } + if (!is_valid) + return PJ_CLI_EBADID; + cmd->id = (pj_cli_cmd_id)pj_strtol(&attr->value); + } else if (!pj_stricmp2(&attr->name, "sc")) { + pj_scanner scanner; + pj_str_t str; + + PJ_USE_EXCEPTION; + + pj_scan_init(&scanner, attr->value.ptr, attr->value.slen, + PJ_SCAN_AUTOSKIP_WS, &on_syntax_error); + + PJ_TRY { + while (!pj_scan_is_eof(&scanner)) { + pj_scan_get_until_ch(&scanner, ',', &str); + pj_strrtrim(&str); + if (!pj_scan_is_eof(&scanner)) + pj_scan_advance_n(&scanner, 1, PJ_TRUE); + if (!str.slen) + continue; + + if (cmd->sc_cnt >= PJ_CLI_MAX_SHORTCUTS) { + PJ_THROW(PJ_CLI_ETOOMANYARGS); + } + /* Check whether the shortcuts are already used */ + if (cmd_name_exists(cli, group, &str)) { + PJ_THROW(PJ_CLI_EBADNAME); + } + + pj_strassign(&sc[cmd->sc_cnt++], &str); + } + } + PJ_CATCH_ANY { + pj_scan_fini(&scanner); + return (PJ_GET_EXCEPTION()); + } + PJ_END; + + } else if (!pj_stricmp2(&attr->name, "desc")) { + pj_strdup(cli->pool, &cmd->desc, &attr->value); + } + attr = attr->next; + } + + /* Get the command childs/arguments */ + sub_node = root->node_head.next; + while (sub_node != (pj_xml_node*)&root->node_head) { + if (!pj_stricmp2(&sub_node->name, "CMD")) { + status = add_cmd_node(cli, cmd, sub_node, handler, NULL, + get_choice); + if (status != PJ_SUCCESS) + return status; + } else if (!pj_stricmp2(&sub_node->name, "ARG")) { + /* Get argument attribute */ + status = add_arg_node(cli, sub_node, + cmd, &args[cmd->arg_cnt], + get_choice); + + if (status != PJ_SUCCESS) + return status; + } + sub_node = sub_node->next; + } + + if (!cmd->name.slen) + return PJ_CLI_EBADNAME; + + if (!cmd->id) + return PJ_CLI_EBADID; + + if (cmd->arg_cnt) { + unsigned i; + + cmd->arg = (pj_cli_arg_spec *)pj_pool_zalloc(cli->pool, cmd->arg_cnt * + sizeof(pj_cli_arg_spec)); + + for (i = 0; i < cmd->arg_cnt; i++) { + pj_strdup(cli->pool, &cmd->arg[i].name, &args[i].name); + pj_strdup(cli->pool, &cmd->arg[i].desc, &args[i].desc); + cmd->arg[i].id = args[i].id; + cmd->arg[i].type = args[i].type; + cmd->arg[i].optional = args[i].optional; + cmd->arg[i].validate = args[i].validate; + cmd->arg[i].get_dyn_choice = args[i].get_dyn_choice; + cmd->arg[i].stat_choice_cnt = args[i].stat_choice_cnt; + cmd->arg[i].stat_choice_val = args[i].stat_choice_val; + } + } + + if (cmd->sc_cnt) { + unsigned i; + + cmd->sc = (pj_str_t *)pj_pool_zalloc(cli->pool, cmd->sc_cnt * + sizeof(pj_str_t)); + for (i = 0; i < cmd->sc_cnt; i++) { + pj_strdup(cli->pool, &cmd->sc[i], &sc[i]); + add_cmd_name(cli, group, cmd, &sc[i]); + } + } + + add_cmd_name(cli, group, cmd, &cmd->name); + pj_hash_set(cli->pool, cli->cmd_id_hash, + &cmd->id, sizeof(pj_cli_cmd_id), 0, cmd); + + cmd->handler = handler; + + if (group) { + if (!group->sub_cmd) { + group->sub_cmd = PJ_POOL_ALLOC_T(cli->pool, struct pj_cli_cmd_spec); + pj_list_init(group->sub_cmd); + } + pj_list_push_back(group->sub_cmd, cmd); + } else { + pj_list_push_back(cli->root.sub_cmd, cmd); + } + + if (p_cmd) + *p_cmd = cmd; + + return status; +} + +PJ_DEF(pj_status_t) pj_cli_add_cmd_from_xml(pj_cli_t *cli, + pj_cli_cmd_spec *group, + const pj_str_t *xml, + pj_cli_cmd_handler handler, + pj_cli_cmd_spec **p_cmd, + pj_cli_get_dyn_choice get_choice) +{ + pj_pool_t *pool; + pj_xml_node *root; + pj_status_t status = PJ_SUCCESS; + + PJ_ASSERT_RETURN(cli && xml, PJ_EINVAL); + + /* Parse the xml */ + pool = pj_pool_create(cli->cfg.pf, "xml", 1024, 1024, NULL); + if (!pool) + return PJ_ENOMEM; + + root = pj_xml_parse(pool, xml->ptr, xml->slen); + if (!root) { + TRACE_((THIS_FILE, "Error: unable to parse XML")); + pj_pool_release(pool); + return PJ_CLI_EBADXML; + } + status = add_cmd_node(cli, group, root, handler, p_cmd, get_choice); + pj_pool_release(pool); + return status; +} + +PJ_DEF(pj_status_t) pj_cli_sess_parse(pj_cli_sess *sess, + char *cmdline, + pj_cli_cmd_val *val, + pj_pool_t *pool, + pj_cli_exec_info *info) +{ + pj_scanner scanner; + pj_str_t str; + int len; + pj_cli_cmd_spec *cmd; + pj_cli_cmd_spec *next_cmd; + pj_status_t status = PJ_SUCCESS; + pj_cli_parse_mode parse_mode = PARSE_NONE; + + PJ_USE_EXCEPTION; + + PJ_ASSERT_RETURN(sess && cmdline && val, PJ_EINVAL); + + PJ_UNUSED_ARG(pool); + + str.slen = 0; + pj_cli_exec_info_default(info); + + /* Set the parse mode based on the latest char. */ + len = pj_ansi_strlen(cmdline); + if (len > 0 && ((cmdline[len - 1] == '\r')||(cmdline[len - 1] == '\n'))) { + cmdline[--len] = 0; + parse_mode = PARSE_EXEC; + } else if (len > 0 && + (cmdline[len - 1] == '\t' || cmdline[len - 1] == '?')) + { + cmdline[--len] = 0; + if (len == 0) { + parse_mode = PARSE_NEXT_AVAIL; + } else { + if (cmdline[len - 1] == ' ') + parse_mode = PARSE_NEXT_AVAIL; + else + parse_mode = PARSE_COMPLETION; + } + } + val->argc = 0; + info->err_pos = 0; + cmd = &sess->fe->cli->root; + if (len > 0) { + pj_scan_init(&scanner, cmdline, len, PJ_SCAN_AUTOSKIP_WS, + &on_syntax_error); + PJ_TRY { + val->argc = 0; + while (!pj_scan_is_eof(&scanner)) { + info->err_pos = scanner.curptr - scanner.begin; + if (*scanner.curptr == '\'' || *scanner.curptr == '"' || + *scanner.curptr == '[' || *scanner.curptr == '{') + { + pj_scan_get_quotes(&scanner, "'\"[{", "'\"]}", 4, &str); + /* Remove the quotes */ + str.ptr++; + str.slen -= 2; + } else { + pj_scan_get_until_chr(&scanner, " \t\r\n", &str); + } + ++val->argc; + if (val->argc == PJ_CLI_MAX_ARGS) + PJ_THROW(PJ_CLI_ETOOMANYARGS); + + status = get_available_cmds(sess, cmd, &str, val->argc-1, + pool, PJ_TRUE, parse_mode, + &next_cmd, info); + + if (status != PJ_SUCCESS) + PJ_THROW(status); + + if (cmd != next_cmd) { + /* Found new command, set it as the active command */ + cmd = next_cmd; + val->argc = 1; + val->cmd = cmd; + } + if (parse_mode == PARSE_EXEC) + pj_strassign(&val->argv[val->argc-1], &info->hint->name); + else + pj_strassign(&val->argv[val->argc-1], &str); + + } + if (!pj_scan_is_eof(&scanner)) + PJ_THROW(PJ_CLI_EINVARG); + + } + PJ_CATCH_ANY { + pj_scan_fini(&scanner); + return PJ_GET_EXCEPTION(); + } + PJ_END; + } + + if ((parse_mode == PARSE_NEXT_AVAIL) || (parse_mode == PARSE_EXEC)) { + /* If exec mode, just get the matching argument */ + status = get_available_cmds(sess, cmd, NULL, val->argc, pool, + (parse_mode==PARSE_NEXT_AVAIL), + parse_mode, + NULL, info); + if ((status != PJ_SUCCESS) && (status != PJ_CLI_EINVARG)) { + pj_str_t data = pj_str(cmdline); + pj_strrtrim(&data); + data.ptr[data.slen] = ' '; + data.ptr[data.slen+1] = 0; + + info->err_pos = pj_ansi_strlen(cmdline); + } + } + + val->sess = sess; + return status; +} + +PJ_DECL(pj_status_t) pj_cli_sess_exec(pj_cli_sess *sess, + char *cmdline, + pj_pool_t *pool, + pj_cli_exec_info *info) +{ + pj_cli_cmd_val val; + pj_status_t status; + pj_cli_exec_info einfo; + pj_str_t cmd; + + PJ_ASSERT_RETURN(sess && cmdline, PJ_EINVAL); + + PJ_UNUSED_ARG(pool); + + cmd.ptr = cmdline; + cmd.slen = pj_ansi_strlen(cmdline); + + if (pj_strtrim(&cmd)->slen == 0) + return PJ_SUCCESS; + + if (!info) + info = &einfo; + + status = pj_cli_sess_parse(sess, cmdline, &val, pool, info); + if (status != PJ_SUCCESS) + return status; + + if ((val.argc > 0) && (val.cmd->handler)) { + info->cmd_ret = (*val.cmd->handler)(&val); + if (info->cmd_ret == PJ_CLI_EINVARG || + info->cmd_ret == PJ_CLI_EEXIT) + { + return info->cmd_ret; + } + } + + return PJ_SUCCESS; +} + +static pj_status_t insert_new_hint(pj_pool_t *pool, + const pj_str_t *name, + const pj_str_t *desc, + const pj_str_t *type, + pj_cli_exec_info *info) +{ + pj_cli_hint_info *hint; + PJ_ASSERT_RETURN(pool && info, PJ_EINVAL); + PJ_ASSERT_RETURN((info->hint_cnt < PJ_CLI_MAX_HINTS), PJ_EINVAL); + hint = &info->hint[info->hint_cnt]; + + pj_strdup(pool, &hint->name, name); + + if (desc && (desc->slen > 0)) { + pj_strdup(pool, &hint->desc, desc); + } else { + hint->desc.slen = 0; + } + + if (type && (type->slen > 0)) { + pj_strdup(pool, &hint->type, type); + } else { + hint->type.slen = 0; + } + + ++info->hint_cnt; + return PJ_SUCCESS; +} + +static pj_status_t get_match_cmds(pj_cli_cmd_spec *cmd, + const pj_str_t *cmd_val, + pj_pool_t *pool, + pj_cli_cmd_spec **p_cmd, + pj_cli_exec_info *info) +{ + pj_status_t status = PJ_SUCCESS; + PJ_ASSERT_RETURN(cmd && pool && info && cmd_val, PJ_EINVAL); + + if (p_cmd) + *p_cmd = cmd; + + /* Get matching command */ + if (cmd->sub_cmd) { + pj_cli_cmd_spec *child_cmd = cmd->sub_cmd->next; + while (child_cmd != cmd->sub_cmd) { + unsigned i; + pj_bool_t found = PJ_FALSE; + if (!pj_strncmp(&child_cmd->name, cmd_val, cmd_val->slen)) { + status = insert_new_hint(pool, &child_cmd->name, + &child_cmd->desc, NULL, info); + if (status != PJ_SUCCESS) + return status; + + found = PJ_TRUE; + } + for (i=0; i < child_cmd->sc_cnt; ++i) { + static const pj_str_t SHORTCUT = {"SC", 2}; + pj_str_t *sc = &child_cmd->sc[i]; + PJ_ASSERT_RETURN(sc, PJ_EINVAL); + + if (!pj_strncmp(sc, cmd_val, cmd_val->slen)) { + status = insert_new_hint(pool, sc, &child_cmd->desc, + &SHORTCUT, info); + if (status != PJ_SUCCESS) + return status; + + found = PJ_TRUE; + } + } + if (found && p_cmd) + *p_cmd = child_cmd; + + child_cmd = child_cmd->next; + } + } + return status; +} + +static pj_status_t get_match_args(pj_cli_sess *sess, + pj_cli_cmd_spec *cmd, + const pj_str_t *cmd_val, + unsigned argc, + pj_pool_t *pool, + pj_cli_parse_mode parse_mode, + pj_cli_exec_info *info) +{ + pj_cli_arg_spec *arg; + pj_status_t status = PJ_SUCCESS; + + PJ_ASSERT_RETURN(cmd && pool && cmd_val && info, PJ_EINVAL); + + if ((argc > cmd->arg_cnt) && (!cmd->sub_cmd)) { + if (cmd_val->slen > 0) + return PJ_CLI_ETOOMANYARGS; + else + return PJ_SUCCESS; + } + + if (cmd->arg_cnt > 0) { + arg = &cmd->arg[argc-1]; + PJ_ASSERT_RETURN(arg, PJ_EINVAL); + if (arg->type == PJ_CLI_ARG_CHOICE) { + unsigned j; + + if ((parse_mode == PARSE_EXEC) && (!arg->validate)) { + /* If no validation needed, then insert the values */ + status = insert_new_hint(pool, + cmd_val, + NULL, + NULL, + info); + return status; + } + + for (j=0; j < arg->stat_choice_cnt; ++j) { + pj_cli_arg_choice_val *choice_val = &arg->stat_choice_val[j]; + + PJ_ASSERT_RETURN(choice_val, PJ_EINVAL); + + if (!pj_strncmp(&choice_val->value, cmd_val, cmd_val->slen)) { + status = insert_new_hint(pool, + &choice_val->value, + &choice_val->desc, + &arg_type[PJ_CLI_ARG_CHOICE].msg, + info); + if (status != PJ_SUCCESS) + return status; + } + } + if (arg->get_dyn_choice) { + pj_cli_dyn_choice_param dyn_choice_param; + static pj_str_t choice_str = {"choice", 6}; + + /* Get the dynamic choice values */ + dyn_choice_param.sess = sess; + dyn_choice_param.cmd = cmd; + dyn_choice_param.arg_id = arg->id; + dyn_choice_param.max_cnt = PJ_CLI_MAX_CHOICE_VAL; + dyn_choice_param.pool = pool; + dyn_choice_param.cnt = 0; + + (*arg->get_dyn_choice)(&dyn_choice_param); + for (j=0; j < dyn_choice_param.cnt; ++j) { + pj_cli_arg_choice_val *choice = &dyn_choice_param.choice[j]; + if (!pj_strncmp(&choice->value, cmd_val, cmd_val->slen)) { + pj_strassign(&info->hint[info->hint_cnt].name, + &choice->value); + pj_strassign(&info->hint[info->hint_cnt].type, + &choice_str); + pj_strassign(&info->hint[info->hint_cnt].desc, + &choice->desc); + if ((++info->hint_cnt) >= PJ_CLI_MAX_HINTS) + break; + } + } + if ((info->hint_cnt == 0) && (!arg->optional)) + return PJ_CLI_EMISSINGARG; + } + } else { + if (cmd_val->slen == 0) { + if (info->hint_cnt == 0) { + if (!((parse_mode == PARSE_EXEC) && (arg->optional))) { + /* For exec mode,no need to insert hint if optional */ + status = insert_new_hint(pool, + &arg->name, + &arg->desc, + &arg_type[arg->type].msg, + info); + if (status != PJ_SUCCESS) + return status; + } + if (!arg->optional) + return PJ_CLI_EMISSINGARG; + } + } else { + return insert_new_hint(pool, cmd_val, NULL, NULL, info); + } + } + } + return status; +} + +static pj_status_t get_available_cmds(pj_cli_sess *sess, + pj_cli_cmd_spec *cmd, + pj_str_t *cmd_val, + unsigned argc, + pj_pool_t *pool, + pj_bool_t get_cmd, + pj_cli_parse_mode parse_mode, + pj_cli_cmd_spec **p_cmd, + pj_cli_exec_info *info) +{ + pj_status_t status = PJ_SUCCESS; + pj_str_t *prefix; + pj_str_t EMPTY_STR = {NULL, 0}; + + prefix = cmd_val?(pj_strtrim(cmd_val)):(&EMPTY_STR); + + info->hint_cnt = 0; + + if (get_cmd) + status = get_match_cmds(cmd, prefix, pool, p_cmd, info); + if (argc > 0) + status = get_match_args(sess, cmd, prefix, argc, + pool, parse_mode, info); + + if (status == PJ_SUCCESS) { + if (prefix->slen > 0) { + if (info->hint_cnt == 0) { + status = PJ_CLI_EINVARG; + } else if (info->hint_cnt > 1) { + status = PJ_CLI_EAMBIGUOUS; + } + } else { + if (info->hint_cnt > 0) + status = PJ_CLI_EAMBIGUOUS; + } + } + + return status; +} + diff --git a/pjlib-util/src/pjlib-util/cli_console.c b/pjlib-util/src/pjlib-util/cli_console.c new file mode 100644 index 00000000..76dedb35 --- /dev/null +++ b/pjlib-util/src/pjlib-util/cli_console.c @@ -0,0 +1,540 @@ +/* $Id$ */ +/* + * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * This specify the state of output character parsing. + */ +typedef enum out_parse_state +{ + OP_NORMAL, + OP_TYPE, + OP_SHORTCUT, + OP_CHOICE +} out_parse_state; + +struct cli_console_fe +{ + pj_cli_front_end base; + pj_pool_t *pool; + pj_cli_sess *sess; + pj_thread_t *input_thread; + pj_bool_t thread_quit; + pj_sem_t *thread_sem; + pj_cli_console_cfg cfg; + + struct async_input_t + { + char *buf; + unsigned maxlen; + pj_sem_t *sem; + } input; +}; + +static void console_write_log(pj_cli_front_end *fe, int level, + const char *data, int len) +{ + struct cli_console_fe * cfe = (struct cli_console_fe *)fe; + + if (cfe->sess->log_level > level) + printf("%.*s", len, data); +} + +static void console_quit(pj_cli_front_end *fe, pj_cli_sess *req) +{ + struct cli_console_fe * cfe = (struct cli_console_fe *)fe; + + PJ_UNUSED_ARG(req); + + pj_assert(cfe); + if (cfe->input_thread) { + cfe->thread_quit = PJ_TRUE; + pj_sem_post(cfe->input.sem); + pj_sem_post(cfe->thread_sem); + } +} + +static void console_destroy(pj_cli_front_end *fe) +{ + struct cli_console_fe * cfe = (struct cli_console_fe *)fe; + + pj_assert(cfe); + console_quit(fe, NULL); + + if (cfe->input_thread) + pj_thread_join(cfe->input_thread); + + if (cfe->input_thread) { + pj_thread_destroy(cfe->input_thread); + cfe->input_thread = NULL; + } + + pj_sem_destroy(cfe->thread_sem); + pj_sem_destroy(cfe->input.sem); + pj_pool_release(cfe->pool); +} + +PJ_DEF(void) pj_cli_console_cfg_default(pj_cli_console_cfg *param) +{ + pj_assert(param); + + param->log_level = PJ_CLI_CONSOLE_LOG_LEVEL; + param->prompt_str.slen = 0; + param->quit_command.slen = 0; +} + +PJ_DEF(pj_status_t) pj_cli_console_create(pj_cli_t *cli, + const pj_cli_console_cfg *param, + pj_cli_sess **p_sess, + pj_cli_front_end **p_fe) +{ + pj_cli_sess *sess; + struct cli_console_fe *fe; + pj_cli_console_cfg cfg; + pj_pool_t *pool; + pj_status_t status; + + PJ_ASSERT_RETURN(cli && p_sess, PJ_EINVAL); + + pool = pj_pool_create(pj_cli_get_param(cli)->pf, "console_fe", + PJ_CLI_CONSOLE_POOL_SIZE, PJ_CLI_CONSOLE_POOL_INC, + NULL); + if (!pool) + return PJ_ENOMEM; + + sess = PJ_POOL_ZALLOC_T(pool, pj_cli_sess); + fe = PJ_POOL_ZALLOC_T(pool, struct cli_console_fe); + + if (!param) { + pj_cli_console_cfg_default(&cfg); + param = &cfg; + } + sess->fe = &fe->base; + sess->log_level = param->log_level; + sess->op = PJ_POOL_ZALLOC_T(pool, struct pj_cli_sess_op); + fe->base.op = PJ_POOL_ZALLOC_T(pool, struct pj_cli_front_end_op); + fe->base.cli = cli; + fe->base.type = PJ_CLI_CONSOLE_FRONT_END; + fe->base.op->on_write_log = &console_write_log; + fe->base.op->on_quit = &console_quit; + fe->base.op->on_destroy = &console_destroy; + fe->pool = pool; + fe->sess = sess; + status = pj_sem_create(pool, "console_fe", 0, 1, &fe->thread_sem); + if (status != PJ_SUCCESS) + return status; + + status = pj_sem_create(pool, "console_fe", 0, 1, &fe->input.sem); + if (status != PJ_SUCCESS) + return status; + + pj_cli_register_front_end(cli, &fe->base); + if (param->prompt_str.slen == 0) { + pj_str_t prompt_sign = pj_str(">>> "); + fe->cfg.prompt_str.ptr = pj_pool_alloc(fe->pool, prompt_sign.slen+1); + pj_strcpy(&fe->cfg.prompt_str, &prompt_sign); + } else { + fe->cfg.prompt_str.ptr = pj_pool_alloc(fe->pool, + param->prompt_str.slen+1); + pj_strcpy(&fe->cfg.prompt_str, ¶m->prompt_str); + } + fe->cfg.prompt_str.ptr[fe->cfg.prompt_str.slen] = 0; + + if (param->quit_command.slen) + pj_strdup(fe->pool, &fe->cfg.quit_command, ¶m->quit_command); + + *p_sess = sess; + if (p_fe) + *p_fe = &fe->base; + + return PJ_SUCCESS; +} + +static void send_prompt_str(pj_cli_sess *sess) +{ + pj_str_t send_data; + char data_str[128]; + struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe; + + send_data.ptr = &data_str[0]; + send_data.slen = 0; + + pj_strcat(&send_data, &fe->cfg.prompt_str); + send_data.ptr[send_data.slen] = 0; + + printf("%s", send_data.ptr); +} + +static void send_err_arg(pj_cli_sess *sess, + const pj_cli_exec_info *info, + const pj_str_t *msg, + pj_bool_t with_return) +{ + pj_str_t send_data; + char data_str[256]; + unsigned len; + unsigned i; + struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe; + + send_data.ptr = &data_str[0]; + send_data.slen = 0; + + if (with_return) + pj_strcat2(&send_data, "\r\n"); + + len = fe->cfg.prompt_str.slen + info->err_pos; + + for (i=0;icfg.prompt_str); + + send_data.ptr[send_data.slen] = 0; + printf("%s", send_data.ptr); +} + +static void send_inv_arg(pj_cli_sess *sess, + const pj_cli_exec_info *info, + pj_bool_t with_return) +{ + static const pj_str_t ERR_MSG = {"%Error : Invalid Arguments\r\n", 28}; + send_err_arg(sess, info, &ERR_MSG, with_return); +} + +static void send_too_many_arg(pj_cli_sess *sess, + const pj_cli_exec_info *info, + pj_bool_t with_return) +{ + static const pj_str_t ERR_MSG = {"%Error : Too Many Arguments\r\n", 29}; + send_err_arg(sess, info, &ERR_MSG, with_return); +} + +static void send_hint_arg(pj_str_t *send_data, + const pj_str_t *desc, + pj_ssize_t cmd_len, + pj_ssize_t max_len) +{ + if ((desc) && (desc->slen > 0)) { + int j; + + for (j=0;j<(max_len-cmd_len);++j) { + pj_strcat2(send_data, " "); + } + pj_strcat2(send_data, " "); + pj_strcat(send_data, desc); + send_data->ptr[send_data->slen] = 0; + printf("%s", send_data->ptr); + send_data->slen = 0; + } +} + +static void send_ambi_arg(pj_cli_sess *sess, + const pj_cli_exec_info *info, + pj_bool_t with_return) +{ + unsigned i; + unsigned len; + pj_str_t send_data; + char data[1028]; + struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe; + const pj_cli_hint_info *hint = info->hint; + out_parse_state parse_state = OP_NORMAL; + pj_ssize_t max_length = 0; + pj_ssize_t cmd_length = 0; + const pj_str_t *cmd_desc = 0; + static const pj_str_t sc_type = {"sc", 2}; + static const pj_str_t choice_type = {"choice", 6}; + send_data.ptr = &data[0]; + send_data.slen = 0; + + if (with_return) + pj_strcat2(&send_data, "\r\n"); + + len = fe->cfg.prompt_str.slen + info->err_pos; + + for (i=0;ihint_cnt;++i) { + if ((&hint[i].type) && (hint[i].type.slen > 0)) { + if (pj_stricmp(&hint[i].type, &sc_type) == 0) { + //Additional delimiter " | " + cmd_length += (hint[i].name.slen + 3); + } else { + cmd_length = hint[i].name.slen; + } + } else { + cmd_length = hint[i].name.slen; + } + + if (cmd_length > max_length) { + max_length = cmd_length; + } + } + + cmd_length = 0; + for (i=0;ihint_cnt;++i) { + if ((&hint[i].type) && (hint[i].type.slen > 0)) { + if (pj_stricmp(&hint[i].type, &sc_type) == 0) { + parse_state = OP_SHORTCUT; + } else if (pj_stricmp(&hint[i].type, &choice_type) == 0) { + parse_state = OP_CHOICE; + } else { + parse_state = OP_TYPE; + } + } else { + parse_state = OP_NORMAL; + } + + if ((parse_state != OP_SHORTCUT)) { + if (cmd_desc) { + /* Print data if previous hint is shortcut */ + send_hint_arg(&send_data, cmd_desc, cmd_length, max_length); + cmd_desc = 0; + } + pj_strcat2(&send_data, "\r\n "); + cmd_length = hint[i].name.slen; + } + + switch (parse_state) { + case OP_CHOICE: + pj_strcat2(&send_data, "["); + pj_strcat(&send_data, &hint[i].name); + pj_strcat2(&send_data, "]"); + break; + case OP_TYPE: + pj_strcat2(&send_data, "<"); + pj_strcat(&send_data, &hint[i].type); + pj_strcat2(&send_data, ">"); + break; + case OP_SHORTCUT: + pj_strcat2(&send_data, " | "); + pj_strcat(&send_data, &hint[i].name); + cmd_length += (hint[i].name.slen + 3); + break; + default: + pj_strcat(&send_data, &hint[i].name); + cmd_desc = &hint[i].desc; + break; + } + + if ((parse_state == OP_TYPE) || (parse_state == OP_CHOICE) || + ((i+1) >= info->hint_cnt)) + { + /* Add description info */ + send_hint_arg(&send_data, &hint[i].desc, cmd_length, max_length); + } + } + pj_strcat2(&send_data, "\r\n"); + pj_strcat(&send_data, &fe->cfg.prompt_str); + send_data.ptr[send_data.slen] = 0; + printf("%s", send_data.ptr); +} + +static pj_bool_t handle_hint(pj_cli_sess *sess) +{ + pj_status_t status; + pj_bool_t retval = PJ_TRUE; + + pj_pool_t *pool; + pj_cli_cmd_val *cmd_val; + pj_cli_exec_info info; + struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe; + char *recv_buf = fe->input.buf; + pj_cli_t *cli = sess->fe->cli; + + pool = pj_pool_create(pj_cli_get_param(cli)->pf, "handle_hint", + PJ_CLI_CONSOLE_POOL_SIZE, PJ_CLI_CONSOLE_POOL_INC, + NULL); + + cmd_val = PJ_POOL_ZALLOC_T(pool, pj_cli_cmd_val); + + status = pj_cli_sess_parse(sess, recv_buf, cmd_val, + pool, &info); + + switch (status) { + case PJ_CLI_EINVARG: + send_inv_arg(sess, &info, PJ_TRUE); + break; + case PJ_CLI_ETOOMANYARGS: + send_too_many_arg(sess, &info, PJ_TRUE); + break; + case PJ_CLI_EMISSINGARG: + case PJ_CLI_EAMBIGUOUS: + send_ambi_arg(sess, &info, PJ_TRUE); + break; + case PJ_SUCCESS: + if (info.hint_cnt > 0) { + /* Compelete command */ + send_ambi_arg(sess, &info, PJ_TRUE); + } else { + retval = PJ_FALSE; + } + break; + } + + pj_pool_release(pool); + return retval; +} + +static pj_bool_t handle_exec(pj_cli_sess *sess) +{ + pj_status_t status; + pj_bool_t retval = PJ_TRUE; + + pj_pool_t *pool; + pj_cli_exec_info info; + pj_cli_t *cli = sess->fe->cli; + struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe; + char *recv_buf = fe->input.buf; + + printf("\r\n"); + + pool = pj_pool_create(pj_cli_get_param(cli)->pf, "handle_exec", + PJ_CLI_CONSOLE_POOL_SIZE, PJ_CLI_CONSOLE_POOL_INC, + NULL); + + status = pj_cli_sess_exec(sess, recv_buf, + pool, &info); + + switch (status) { + case PJ_CLI_EINVARG: + send_inv_arg(sess, &info, PJ_FALSE); + break; + case PJ_CLI_ETOOMANYARGS: + send_too_many_arg(sess, &info, PJ_FALSE); + break; + case PJ_CLI_EAMBIGUOUS: + case PJ_CLI_EMISSINGARG: + send_ambi_arg(sess, &info, PJ_FALSE); + break; + case PJ_CLI_EEXIT: + retval = PJ_FALSE; + break; + case PJ_SUCCESS: + send_prompt_str(sess); + break; + } + + pj_pool_release(pool); + return retval; +} + +static int readline_thread(void * p) +{ + struct cli_console_fe * fe = (struct cli_console_fe *)p; + + printf("%s", fe->cfg.prompt_str.ptr); + + while (!fe->thread_quit) { + unsigned input_len = 0; + pj_str_t input_str; + char *recv_buf = fe->input.buf; + pj_bool_t is_valid = PJ_TRUE; + + if (fgets(recv_buf, fe->input.maxlen, stdin) == NULL) { + /* + * Be friendly to users who redirect commands into + * program, when file ends, resume with kbd. + * If exit is desired end script with q for quit + */ + /* Reopen stdin/stdout/stderr to /dev/console */ +#if defined(PJ_WIN32) && PJ_WIN32!=0 + if (freopen ("CONIN$", "r", stdin) == NULL) { +#else + if (1) { +#endif + puts("Cannot switch back to console from file redirection"); + if (fe->cfg.quit_command.slen) { + pj_memcpy(recv_buf, fe->cfg.quit_command.ptr, + fe->input.maxlen); + } + recv_buf[fe->cfg.quit_command.slen] = '\0'; + } else { + puts("Switched back to console from file redirection"); + continue; + } + } + + input_str.ptr = recv_buf; + input_str.slen = pj_ansi_strlen(recv_buf); + pj_strrtrim(&input_str); + recv_buf[input_str.slen] = '\n'; + recv_buf[input_str.slen+1] = 0; + if (fe->thread_quit) { + break; + } + input_len = pj_ansi_strlen(fe->input.buf); + if ((input_len > 1) && (fe->input.buf[input_len-2] == '?')) { + fe->input.buf[input_len-1] = 0; + is_valid = handle_hint(fe->sess); + if (!is_valid) + printf("%s", fe->cfg.prompt_str.ptr); + } else { + is_valid = handle_exec(fe->sess); + } + + pj_sem_post(fe->input.sem); + pj_sem_wait(fe->thread_sem); + } + + return 0; +} + +PJ_DEF(pj_status_t) pj_cli_console_process(pj_cli_sess *sess, + char *buf, + unsigned maxlen) +{ + struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe; + + PJ_ASSERT_RETURN(sess, PJ_EINVAL); + + fe->input.buf = buf; + fe->input.maxlen = maxlen; + + if (!fe->input_thread) { + pj_status_t status; + + status = pj_thread_create(fe->pool, NULL, &readline_thread, fe, + 0, 0, &fe->input_thread); + if (status != PJ_SUCCESS) + return status; + } else { + /* Wake up readline thread */ + pj_sem_post(fe->thread_sem); + } + + pj_sem_wait(fe->input.sem); + + return (pj_cli_is_quitting(fe->base.cli)? PJ_CLI_EEXIT : PJ_SUCCESS); +} diff --git a/pjlib-util/src/pjlib-util/cli_telnet.c b/pjlib-util/src/pjlib-util/cli_telnet.c new file mode 100644 index 00000000..c6a8cf16 --- /dev/null +++ b/pjlib-util/src/pjlib-util/cli_telnet.c @@ -0,0 +1,1786 @@ +/* $Id$ */ +/* + * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CLI_TELNET_BUF_SIZE 256 + +#define CUT_MSG "<..data truncated..>\r\n" +#define MAX_CUT_MSG_LEN 25 + +#if 1 + /* Enable some tracing */ + #define THIS_FILE "cli_telnet.c" + #define TRACE_(arg) PJ_LOG(3,arg) +#else + #define TRACE_(arg) +#endif + +#define MAX_CLI_TELNET_OPTIONS 256 + +/** + * This specify the state for the telnet option negotiation. + */ +enum cli_telnet_option_states +{ + OPT_DISABLE, /* Option disable */ + OPT_ENABLE, /* Option enable */ + OPT_EXPECT_DISABLE, /* Already send disable req, expecting resp */ + OPT_EXPECT_ENABLE, /* Already send enable req, expecting resp */ + OPT_EXPECT_DISABLE_REV, /* Already send disable req, expecting resp, + * need to send enable req */ + OPT_EXPECT_ENABLE_REV /* Already send enable req, expecting resp, + * need to send disable req */ +}; + +/** + * This structure contains information for telnet session option negotiation. + * It contains the local/peer option config and the option negotiation state. + */ +typedef struct cli_telnet_sess_option +{ + /** + * Local setting for the option. + * Default: FALSE; + */ + pj_bool_t local_is_enable; + + /** + * Remote setting for the option. + * Default: FALSE; + */ + pj_bool_t peer_is_enable; + + /** + * Local state of the option negotiation. + */ + enum cli_telnet_option_states local_state; + + /** + * Remote state of the option negotiation. + */ + enum cli_telnet_option_states peer_state; +} cli_telnet_sess_option; + +/** + * This specify the state of input character parsing. + */ +typedef enum cmd_parse_state +{ + ST_NORMAL, + ST_CR, + ST_ESC, + ST_VT100, + ST_IAC, + ST_DO, + ST_DONT, + ST_WILL, + ST_WONT +} cmd_parse_state; + +typedef enum cli_telnet_command +{ + SUBNEGO_END = 240, /* End of subnegotiation parameters. */ + NOP = 241, /* No operation. */ + DATA_MARK = 242, /* Marker for NVT cleaning. */ + BREAK = 243, /* Indicates that the "break" key was hit. */ + INT_PROCESS = 244, /* Suspend, interrupt or abort the process. */ + ABORT_OUTPUT = 245, /* Abort output, abort output stream. */ + ARE_YOU_THERE = 246, /* Are you there. */ + ERASE_CHAR = 247, /* Erase character, erase the current char. */ + ERASE_LINE = 248, /* Erase line, erase the current line. */ + GO_AHEAD = 249, /* Go ahead, other end can transmit. */ + SUBNEGO_BEGIN = 250, /* Subnegotiation begin. */ + WILL = 251, /* Accept the use of option. */ + WONT = 252, /* Refuse the use of option. */ + DO = 253, /* Request to use option. */ + DONT = 254, /* Request to not use option. */ + IAC = 255 /* Interpret as command */ +} cli_telnet_command; + +enum cli_telnet_options +{ + TRANSMIT_BINARY = 0, /* Transmit Binary. */ + ECHO = 1, /* Echo. */ + RECONNECT = 2, /* Reconnection. */ + SUPPRESS_GA = 3, /* Suppress Go Aheah. */ + MESSAGE_SIZE_NEGO = 4, /* Approx Message Size Negotiation. */ + STATUS = 5, /* Status. */ + TIMING_MARK = 6, /* Timing Mark. */ + RTCE_OPTION = 7, /* Remote Controlled Trans and Echo. */ + OUTPUT_LINE_WIDTH = 8, /* Output Line Width. */ + OUTPUT_PAGE_SIZE = 9, /* Output Page Size. */ + CR_DISPOSITION = 10, /* Carriage-Return Disposition. */ + HORI_TABSTOPS = 11, /* Horizontal Tabstops. */ + HORI_TAB_DISPO = 12, /* Horizontal Tab Disposition. */ + FF_DISP0 = 13, /* Formfeed Disposition. */ + VERT_TABSTOPS = 14, /* Vertical Tabstops. */ + VERT_TAB_DISPO = 15, /* Vertical Tab Disposition. */ + LF_DISP0 = 16, /* Linefeed Disposition. */ + EXT_ASCII = 17, /* Extended ASCII. */ + LOGOUT = 18, /* Logout. */ + BYTE_MACRO = 19, /* Byte Macro. */ + DE_TERMINAL = 20, /* Data Entry Terminal. */ + SUPDUP_PROTO = 21, /* SUPDUP Protocol. */ + SUPDUP_OUTPUT = 22, /* SUPDUP Output. */ + SEND_LOC = 23, /* Send Location. */ + TERM_TYPE = 24, /* Terminal Type. */ + EOR = 25, /* End of Record. */ + TACACS_UID = 26, /* TACACS User Identification. */ + OUTPUT_MARKING = 27, /* Output Marking. */ + TTYLOC = 28, /* Terminal Location Number. */ + USE_3270_REGIME = 29, /* Telnet 3270 Regime. */ + USE_X3_PAD = 30, /* X.3 PAD. */ + WINDOW_SIZE = 31, /* Window Size. */ + TERM_SPEED = 32, /* Terminal Speed. */ + REM_FLOW_CONTROL = 33, /* Remote Flow Control. */ + LINE_MODE = 34, /* Linemode. */ + X_DISP_LOC = 35, /* X Display Location. */ + ENVIRONMENT = 36, /* Environment. */ + AUTH = 37, /* Authentication. */ + ENCRYPTION = 38, /* Encryption Option. */ + NEW_ENVIRONMENT = 39, /* New Environment. */ + TN_3270E = 40, /* TN3270E. */ + XAUTH = 41, /* XAUTH. */ + CHARSET = 42, /* CHARSET. */ + REM_SERIAL_PORT = 43, /* Telnet Remote Serial Port. */ + COM_PORT_CONTROL = 44, /* Com Port Control. */ + SUPP_LOCAL_ECHO = 45, /* Telnet Suppress Local Echo. */ + START_TLS = 46, /* Telnet Start TLS. */ + KERMIT = 47, /* KERMIT. */ + SEND_URL = 48, /* SEND-URL. */ + FWD_X = 49, /* FORWARD_X. */ + EXT_OPTIONS = 255 /* Extended-Options-List */ +}; + +enum terminal_cmd +{ + TC_ESC = 27, + TC_UP = 65, + TC_DOWN = 66, + TC_RIGHT = 67, + TC_LEFT = 68, + TC_END = 70, + TC_HOME = 72, + TC_CTRL_C = 3, + TC_CR = 13, + TC_BS = 8, + TC_TAB = 9, + TC_QM = 63, + TC_BELL = 7, + TC_DEL = 127 +}; + +/** + * This specify the state of output character parsing. + */ +typedef enum out_parse_state +{ + OP_NORMAL, + OP_TYPE, + OP_SHORTCUT, + OP_CHOICE +} out_parse_state; + +/** + * This structure contains the command line shown to the user. + * The telnet also needs to maintain and manage command cursor position. + * Due to that reason, the insert/delete character process from buffer will + * consider its current cursor position. + */ +typedef struct telnet_recv_buf { + /** + * Buffer containing the characters, NULL terminated. + */ + unsigned char rbuf[PJ_CLI_MAX_CMDBUF]; + + /** + * Current length of the command line. + */ + unsigned len; + + /** + * Current cursor position. + */ + unsigned cur_pos; +} telnet_recv_buf; + +/** + * This structure contains the command history executed by user. + * Besides storing the command history, it is necessary to be able + * to browse it. + */ +typedef struct cmd_history +{ + PJ_DECL_LIST_MEMBER(struct cmd_history); + pj_str_t command; +} cmd_history; + +typedef struct cli_telnet_sess +{ + pj_cli_sess base; + pj_pool_t *pool; + pj_activesock_t *asock; + pj_bool_t authorized; + pj_ioqueue_op_key_t op_key; + pj_mutex_t *smutex; + cmd_parse_state parse_state; + cli_telnet_sess_option telnet_option[MAX_CLI_TELNET_OPTIONS]; + cmd_history *history; + cmd_history *active_history; + + telnet_recv_buf *rcmd; + unsigned char buf[CLI_TELNET_BUF_SIZE + MAX_CUT_MSG_LEN]; + unsigned buf_len; +} cli_telnet_sess; + +struct cli_telnet_fe +{ + pj_cli_front_end base; + pj_pool_t *pool; + pj_cli_telnet_cfg cfg; + pj_bool_t own_ioqueue; + pj_cli_sess sess_head; + + pj_activesock_t *asock; + pj_thread_t *worker_thread; + pj_bool_t is_quitting; + pj_mutex_t *mutex; +}; + +/* Forward Declaration */ +static pj_status_t telnet_sess_send2(cli_telnet_sess *sess, + const unsigned char *str, int len); + +static pj_status_t telnet_sess_send(cli_telnet_sess *sess, + const pj_str_t *str); + +/** + * Return the number of characters between the current cursor position + * to the end of line. + */ +static unsigned recv_buf_right_len(telnet_recv_buf *recv_buf) +{ + return (recv_buf->len - recv_buf->cur_pos); +} + +/** + * Insert character to the receive buffer. + */ +static pj_bool_t recv_buf_insert(telnet_recv_buf *recv_buf, + unsigned char *data) +{ + if (recv_buf->len+1 >= PJ_CLI_MAX_CMDBUF) { + return PJ_FALSE; + } else { + if (*data == '\t' || *data == '?' || *data == '\r') { + /* Always insert to the end of line */ + recv_buf->rbuf[recv_buf->len] = *data; + } else { + /* Insert based on the current cursor pos */ + unsigned cur_pos = recv_buf->cur_pos; + unsigned rlen = recv_buf_right_len(recv_buf); + if (rlen > 0) { + /* Shift right characters */ + pj_memmove(&recv_buf->rbuf[cur_pos+1], + &recv_buf->rbuf[cur_pos], + rlen+1); + } + recv_buf->rbuf[cur_pos] = *data; + } + ++recv_buf->cur_pos; + ++recv_buf->len; + recv_buf->rbuf[recv_buf->len] = 0; + } + return PJ_TRUE; +} + +/** + * Delete character on the previous cursor position of the receive buffer. + */ +static pj_bool_t recv_buf_backspace(telnet_recv_buf *recv_buf) +{ + if ((recv_buf->cur_pos == 0) || (recv_buf->len == 0)) { + return PJ_FALSE; + } else { + unsigned rlen = recv_buf_right_len(recv_buf); + if (rlen) { + unsigned cur_pos = recv_buf->cur_pos; + /* Shift left characters */ + pj_memmove(&recv_buf->rbuf[cur_pos-1], &recv_buf->rbuf[cur_pos], + rlen); + } + --recv_buf->cur_pos; + --recv_buf->len; + recv_buf->rbuf[recv_buf->len] = 0; + } + return PJ_TRUE; +} + +static int compare_str(void *value, const pj_list_type *nd) +{ + cmd_history *node = (cmd_history*)nd; + return (pj_strcmp((pj_str_t *)value, &node->command)); +} + +/** + * Insert the command to history. If the entered command is not on the list, + * a new entry will be created. All entered command will be moved to + * the first entry of the history. + */ +static pj_status_t insert_history(cli_telnet_sess *sess, + char *cmd_val) +{ + cmd_history *in_history; + pj_str_t cmd; + cmd.ptr = cmd_val; + cmd.slen = pj_ansi_strlen(cmd_val)-1; + + if (cmd.slen == 0) + return PJ_SUCCESS; + + PJ_ASSERT_RETURN(sess, PJ_EINVAL); + + /* Find matching history */ + in_history = pj_list_search(sess->history, (void*)&cmd, compare_str); + if (!in_history) { + if (pj_list_size(sess->history) < PJ_CLI_MAX_CMD_HISTORY) { + char *data_history; + in_history = PJ_POOL_ZALLOC_T(sess->pool, cmd_history); + pj_list_init(in_history); + data_history = (char *)pj_pool_calloc(sess->pool, + sizeof(char), PJ_CLI_MAX_CMDBUF); + in_history->command.ptr = data_history; + in_history->command.slen = 0; + } else { + /* Get the oldest history */ + in_history = sess->history->prev; + } + } else { + pj_list_insert_nodes_after(in_history->prev, in_history->next); + } + pj_strcpy(&in_history->command, pj_strtrim(&cmd)); + pj_list_push_front(sess->history, in_history); + sess->active_history = sess->history; + + return PJ_SUCCESS; +} + +/** + * Get the next or previous history of the shown/active history. + */ +static pj_str_t* get_prev_history(cli_telnet_sess *sess, pj_bool_t is_forward) +{ + pj_str_t *retval; + pj_size_t history_size; + cmd_history *node; + cmd_history *root; + + PJ_ASSERT_RETURN(sess, NULL); + + node = sess->active_history; + root = sess->history; + history_size = pj_list_size(sess->history); + + if (history_size == 0) { + return NULL; + } else { + if (is_forward) { + node = (node->next==root)?node->next->next:node->next; + } else { + node = (node->prev==root)?node->prev->prev:node->prev; + } + retval = &node->command; + sess->active_history = node; + } + return retval; +} + +/* + * This method is used to send option negotiation command. + * The commands dealing with option negotiation are + * three byte sequences, the third byte being the code for the option + * referenced - (RFC-854). + */ +static pj_bool_t send_telnet_cmd(cli_telnet_sess *sess, + cli_telnet_command cmd, + unsigned char option) +{ + unsigned char buf[3]; + PJ_ASSERT_RETURN(sess, PJ_FALSE); + + buf[0] = IAC; + buf[1] = cmd; + buf[2] = option; + telnet_sess_send2(sess, buf, 3); + + return PJ_TRUE; +} + +/** + * This method will handle sending telnet's ENABLE option negotiation. + * For local option: send WILL. + * For remote option: send DO. + * This method also handle the state transition of the ENABLE + * negotiation process. + */ +static pj_bool_t send_enable_option(cli_telnet_sess *sess, + pj_bool_t is_local, + unsigned char option) +{ + cli_telnet_sess_option *sess_option; + enum cli_telnet_option_states *state; + PJ_ASSERT_RETURN(sess, PJ_FALSE); + + sess_option = &sess->telnet_option[option]; + state = is_local?(&sess_option->local_state):(&sess_option->peer_state); + switch (*state) { + case OPT_ENABLE: + /* Ignore if already enabled */ + break; + case OPT_DISABLE: + *state = OPT_EXPECT_ENABLE; + send_telnet_cmd(sess, (is_local?WILL:DO), option); + break; + case OPT_EXPECT_ENABLE: + *state = OPT_DISABLE; + break; + case OPT_EXPECT_DISABLE: + *state = OPT_EXPECT_DISABLE_REV; + break; + case OPT_EXPECT_ENABLE_REV: + *state = OPT_EXPECT_ENABLE; + break; + case OPT_EXPECT_DISABLE_REV: + *state = OPT_DISABLE; + break; + default: + return PJ_FALSE; + } + return PJ_TRUE; +} + +static pj_bool_t send_cmd_do(cli_telnet_sess *sess, + unsigned char option) +{ + return send_enable_option(sess, PJ_FALSE, option); +} + +static pj_bool_t send_cmd_will(cli_telnet_sess *sess, + unsigned char option) +{ + return send_enable_option(sess, PJ_TRUE, option); +} + +/** + * This method will handle receiving telnet's ENABLE option negotiation. + * This method also handle the state transition of the ENABLE + * negotiation process. + */ +static pj_bool_t receive_enable_option(cli_telnet_sess *sess, + pj_bool_t is_local, + unsigned char option) +{ + cli_telnet_sess_option *sess_opt; + enum cli_telnet_option_states *state; + pj_bool_t opt_ena; + PJ_ASSERT_RETURN(sess, PJ_FALSE); + + sess_opt = &sess->telnet_option[option]; + state = is_local?(&sess_opt->local_state):(&sess_opt->peer_state); + opt_ena = is_local?sess_opt->local_is_enable:sess_opt->peer_is_enable; + switch (*state) { + case OPT_ENABLE: + /* Ignore if already enabled */ + break; + case OPT_DISABLE: + if (opt_ena) { + *state = OPT_ENABLE; + send_telnet_cmd(sess, is_local?WILL:DO, option); + } else { + send_telnet_cmd(sess, is_local?WONT:DONT, option); + } + break; + case OPT_EXPECT_ENABLE: + *state = OPT_ENABLE; + break; + case OPT_EXPECT_DISABLE: + *state = OPT_DISABLE; + break; + case OPT_EXPECT_ENABLE_REV: + *state = OPT_EXPECT_DISABLE; + send_telnet_cmd(sess, is_local?WONT:DONT, option); + break; + case OPT_EXPECT_DISABLE_REV: + *state = OPT_EXPECT_DISABLE; + break; + default: + return PJ_FALSE; + } + return PJ_TRUE; +} + +/** + * This method will handle receiving telnet's DISABLE option negotiation. + * This method also handle the state transition of the DISABLE + * negotiation process. + */ +static pj_bool_t receive_disable_option(cli_telnet_sess *sess, + pj_bool_t is_local, + unsigned char option) +{ + cli_telnet_sess_option *sess_opt; + enum cli_telnet_option_states *state; + + PJ_ASSERT_RETURN(sess, PJ_FALSE); + + sess_opt = &sess->telnet_option[option]; + state = is_local?(&sess_opt->local_state):(&sess_opt->peer_state); + + switch (*state) { + case OPT_ENABLE: + /* Disabling option always need to be accepted */ + *state = OPT_DISABLE; + send_telnet_cmd(sess, is_local?WONT:DONT, option); + break; + case OPT_DISABLE: + /* Ignore if already enabled */ + break; + case OPT_EXPECT_ENABLE: + case OPT_EXPECT_DISABLE: + *state = OPT_DISABLE; + break; + case OPT_EXPECT_ENABLE_REV: + *state = OPT_DISABLE; + send_telnet_cmd(sess, is_local?WONT:DONT, option); + break; + case OPT_EXPECT_DISABLE_REV: + *state = OPT_EXPECT_ENABLE; + send_telnet_cmd(sess, is_local?WILL:DO, option); + break; + default: + return PJ_FALSE; + } + return PJ_TRUE; +} + +static pj_bool_t receive_do(cli_telnet_sess *sess, unsigned char option) +{ + return receive_enable_option(sess, PJ_TRUE, option); +} + +static pj_bool_t receive_dont(cli_telnet_sess *sess, unsigned char option) +{ + return receive_disable_option(sess, PJ_TRUE, option); +} + +static pj_bool_t receive_will(cli_telnet_sess *sess, unsigned char option) +{ + return receive_enable_option(sess, PJ_FALSE, option); +} + +static pj_bool_t receive_wont(cli_telnet_sess *sess, unsigned char option) +{ + return receive_disable_option(sess, PJ_FALSE, option); +} + +static void set_local_option(cli_telnet_sess *sess, + unsigned char option, + pj_bool_t enable) +{ + sess->telnet_option[option].local_is_enable = enable; +} + +static void set_peer_option(cli_telnet_sess *sess, + unsigned char option, + pj_bool_t enable) +{ + sess->telnet_option[option].peer_is_enable = enable; +} + +static pj_bool_t is_local_option_state_ena(cli_telnet_sess *sess, + unsigned char option) +{ + return (sess->telnet_option[option].local_state == OPT_ENABLE); +} + +static void send_return_key(cli_telnet_sess *sess) +{ + telnet_sess_send2(sess, (unsigned char*)"\r\n", 2); +} + +static void send_bell(cli_telnet_sess *sess) { + static const unsigned char bell = 0x07; + telnet_sess_send2(sess, &bell, 1); +} + +static void send_prompt_str(cli_telnet_sess *sess) +{ + pj_str_t send_data; + char data_str[128]; + struct cli_telnet_fe *fe = (struct cli_telnet_fe *)sess->base.fe; + + send_data.ptr = &data_str[0]; + send_data.slen = 0; + + pj_strcat(&send_data, &fe->cfg.prompt_str); + + telnet_sess_send(sess, &send_data); +} + +/* + * This method is used to send error message to client, including + * the error position of the source command. + */ +static void send_err_arg(cli_telnet_sess *sess, + const pj_cli_exec_info *info, + const pj_str_t *msg, + pj_bool_t with_return, + pj_bool_t with_last_cmd) +{ + pj_str_t send_data; + char data_str[256]; + unsigned len; + unsigned i; + struct cli_telnet_fe *fe = (struct cli_telnet_fe *)sess->base.fe; + + send_data.ptr = &data_str[0]; + send_data.slen = 0; + + if (with_return) + pj_strcat2(&send_data, "\r\n"); + + len = fe->cfg.prompt_str.slen + info->err_pos; + + /* Set the error pointer mark */ + for (i=0;icfg.prompt_str); + if (with_last_cmd) + pj_strcat2(&send_data, (char *)&sess->rcmd->rbuf[0]); + + telnet_sess_send(sess, &send_data); +} + +static void send_inv_arg(cli_telnet_sess *sess, + const pj_cli_exec_info *info, + pj_bool_t with_return, + pj_bool_t with_last_cmd) +{ + static const pj_str_t ERR_MSG = {"%Error : Invalid Arguments\r\n", 28}; + send_err_arg(sess, info, &ERR_MSG, with_return, with_last_cmd); +} + +static void send_too_many_arg(cli_telnet_sess *sess, + const pj_cli_exec_info *info, + pj_bool_t with_return, + pj_bool_t with_last_cmd) +{ + static const pj_str_t ERR_MSG = {"%Error : Too Many Arguments\r\n", 29}; + send_err_arg(sess, info, &ERR_MSG, with_return, with_last_cmd); +} + +static void send_hint_arg(cli_telnet_sess *sess, + pj_str_t *send_data, + const pj_str_t *desc, + pj_ssize_t cmd_len, + pj_ssize_t max_len) +{ + if ((desc) && (desc->slen > 0)) { + int j; + + for (j=0;j<(max_len-cmd_len);++j) { + pj_strcat2(send_data, " "); + } + pj_strcat2(send_data, " "); + pj_strcat(send_data, desc); + telnet_sess_send(sess, send_data); + send_data->slen = 0; + } +} + +/* + * This method is used to notify to the client that the entered command + * is ambiguous. It will show the matching command as the hint information. + */ +static void send_ambi_arg(cli_telnet_sess *sess, + const pj_cli_exec_info *info, + pj_bool_t with_return, + pj_bool_t with_last_cmd) +{ + unsigned i; + unsigned len; + pj_str_t send_data; + char data[1028]; + struct cli_telnet_fe *fe = (struct cli_telnet_fe *)sess->base.fe; + const pj_cli_hint_info *hint = info->hint; + out_parse_state parse_state = OP_NORMAL; + pj_ssize_t max_length = 0; + pj_ssize_t cmd_length = 0; + const pj_str_t *cmd_desc = 0; + static const pj_str_t sc_type = {"sc", 2}; + static const pj_str_t choice_type = {"choice", 6}; + send_data.ptr = &data[0]; + send_data.slen = 0; + + if (with_return) + pj_strcat2(&send_data, "\r\n"); + + len = fe->cfg.prompt_str.slen + info->err_pos; + + for (i=0;ihint_cnt;++i) { + if ((&hint[i].type) && (hint[i].type.slen > 0)) { + if (pj_stricmp(&hint[i].type, &sc_type) == 0) { + //Additional delimiter " | " + cmd_length += (hint[i].name.slen + 3); + } else { + cmd_length = hint[i].name.slen; + } + } else { + cmd_length = hint[i].name.slen; + } + + if (cmd_length > max_length) { + max_length = cmd_length; + } + } + + cmd_length = 0; + /* Build hint information */ + for (i=0;ihint_cnt;++i) { + if ((&hint[i].type) && (hint[i].type.slen > 0)) { + if (pj_stricmp(&hint[i].type, &sc_type) == 0) { + parse_state = OP_SHORTCUT; + } else if (pj_stricmp(&hint[i].type, &choice_type) == 0) { + parse_state = OP_CHOICE; + } else { + parse_state = OP_TYPE; + } + } else { + parse_state = OP_NORMAL; + } + + if ((parse_state != OP_SHORTCUT)) { + if (cmd_desc) { + /* Print data if previous hint is shortcut */ + send_hint_arg(sess, &send_data, + cmd_desc, cmd_length, + max_length); + cmd_desc = 0; + } + pj_strcat2(&send_data, "\r\n "); + cmd_length = hint[i].name.slen; + } + + switch (parse_state) { + case OP_CHOICE: + /* Format : "[Choice Value] description" */ + pj_strcat2(&send_data, "["); + pj_strcat(&send_data, &hint[i].name); + pj_strcat2(&send_data, "]"); + break; + case OP_TYPE: + /* Format : " description" */ + pj_strcat2(&send_data, "<"); + pj_strcat(&send_data, &hint[i].name); + pj_strcat2(&send_data, ">"); + break; + case OP_SHORTCUT: + /* Format : "Command | sc | description" */ + pj_strcat2(&send_data, " | "); + pj_strcat(&send_data, &hint[i].name); + cmd_length += (hint[i].name.slen + 3); + break; + default: + /* Command */ + pj_strcat(&send_data, &hint[i].name); + cmd_desc = &hint[i].desc; + break; + } + + if ((parse_state == OP_TYPE) || (parse_state == OP_CHOICE) || + ((i+1) >= info->hint_cnt)) + { + /* Add description info */ + send_hint_arg(sess, &send_data, + &hint[i].desc, cmd_length, + max_length); + } + } + pj_strcat2(&send_data, "\r\n"); + pj_strcat(&send_data, &fe->cfg.prompt_str); + if (with_last_cmd) + pj_strcat2(&send_data, (char *)&sess->rcmd->rbuf[0]); + + telnet_sess_send(sess, &send_data); +} + +/* + * This method is to send command completion of the entered command. + */ +static void send_comp_arg(cli_telnet_sess *sess, + pj_cli_exec_info *info) +{ + pj_str_t send_data; + char data[128]; + + pj_strcat2(&info->hint[0].name, " "); + + send_data.ptr = &data[0]; + send_data.slen = 0; + + pj_strcat(&send_data, &info->hint[0].name); + + telnet_sess_send(sess, &send_data); +} + +/* + * This method is to process the alfa numeric character sent by client. + */ +static pj_bool_t handle_alfa_num(cli_telnet_sess *sess, unsigned char *data) +{ + if (is_local_option_state_ena(sess, ECHO)) { + if (recv_buf_right_len(sess->rcmd) > 0) { + /* Cursor is not at EOL, insert character */ + unsigned char echo[5] = {0x1b, 0x5b, 0x31, 0x40, 0x00}; + echo[4] = *data; + telnet_sess_send2(sess, &echo[0], 5); + } else { + /* Append character */ + telnet_sess_send2(sess, data, 1); + } + return PJ_TRUE; + } + return PJ_FALSE; +} + +/* + * This method is to process the backspace character sent by client. + */ +static pj_bool_t handle_backspace(cli_telnet_sess *sess, unsigned char *data) +{ + unsigned rlen = recv_buf_right_len(sess->rcmd); + if (recv_buf_backspace(sess->rcmd)) { + if (rlen) { + /* + * Cursor is not at the end of line, move the characters + * after the cursor to left + */ + unsigned char echo[5] = {0x00, 0x1b, 0x5b, 0x31, 0x50}; + echo[0] = *data; + telnet_sess_send2(sess, &echo[0], 5); + } else { + const static unsigned char echo[3] = {0x08, 0x20, 0x08}; + telnet_sess_send2(sess, &echo[0], 3); + } + return PJ_TRUE; + } + return PJ_FALSE; +} + +/* + * Syntax error handler for parser. + */ +static void on_syntax_error(pj_scanner *scanner) +{ + PJ_UNUSED_ARG(scanner); + PJ_THROW(PJ_EINVAL); +} + +/* + * This method is to process the backspace character sent by client. + */ +static pj_status_t get_last_token(pj_str_t *cmd, pj_str_t *str) +{ + pj_scanner scanner; + PJ_USE_EXCEPTION; + pj_scan_init(&scanner, cmd->ptr, cmd->slen, PJ_SCAN_AUTOSKIP_WS, + &on_syntax_error); + PJ_TRY { + while (!pj_scan_is_eof(&scanner)) { + pj_scan_get_until_chr(&scanner, " \t\r\n", str); + } + } + PJ_CATCH_ANY { + pj_scan_fini(&scanner); + return PJ_GET_EXCEPTION(); + } + PJ_END; + return PJ_SUCCESS; +} + +/* + * This method is to process the tab character sent by client. + */ +static pj_bool_t handle_tab(cli_telnet_sess *sess) +{ + pj_status_t status; + pj_bool_t retval = PJ_TRUE; + unsigned len; + + pj_pool_t *pool; + pj_cli_cmd_val *cmd_val; + pj_cli_exec_info info; + pool = pj_pool_create(sess->pool->factory, "handle_tab", + PJ_CLI_TELNET_POOL_SIZE, PJ_CLI_TELNET_POOL_INC, + NULL); + + cmd_val = PJ_POOL_ZALLOC_T(pool, pj_cli_cmd_val); + + status = pj_cli_sess_parse(&sess->base, (char *)&sess->rcmd->rbuf, cmd_val, + pool, &info); + + len = pj_ansi_strlen((char *)&sess->rcmd->rbuf[0]); + + switch (status) { + case PJ_CLI_EINVARG: + send_inv_arg(sess, &info, PJ_TRUE, PJ_TRUE); + break; + case PJ_CLI_ETOOMANYARGS: + send_too_many_arg(sess, &info, PJ_TRUE, PJ_TRUE); + break; + case PJ_CLI_EMISSINGARG: + case PJ_CLI_EAMBIGUOUS: + send_ambi_arg(sess, &info, PJ_TRUE, PJ_TRUE); + break; + case PJ_SUCCESS: + if (len > sess->rcmd->cur_pos) + { + /* Send the cursor to EOL */ + unsigned rlen = len - sess->rcmd->cur_pos+1; + unsigned char *data_sent = &sess->rcmd->rbuf[sess->rcmd->cur_pos-1]; + telnet_sess_send2(sess, data_sent, rlen); + } + if (info.hint_cnt > 0) { + /* Complete command */ + pj_str_t cmd = pj_str((char *)&sess->rcmd->rbuf[0]); + pj_str_t last_token; + + if (get_last_token(&cmd, &last_token) == PJ_SUCCESS) { + /* Hint contains the match to the last command entered */ + pj_str_t *hint_info = &info.hint[0].name; + pj_strtrim(&last_token); + if (hint_info->slen >= last_token.slen) { + hint_info->slen -= last_token.slen; + pj_memmove(&hint_info->ptr[0], + &hint_info->ptr[last_token.slen], + hint_info->slen); + } + send_comp_arg(sess, &info); + + pj_memcpy(&sess->rcmd->rbuf[len], &info.hint[0].name.ptr[0], + info.hint[0].name.slen); + + len += info.hint[0].name.slen; + sess->rcmd->rbuf[len] = 0; + } + } else { + retval = PJ_FALSE; + } + break; + } + sess->rcmd->len = len; + sess->rcmd->cur_pos = sess->rcmd->len; + + pj_pool_release(pool); + return retval; +} + +/* + * This method is to process the return character sent by client. + */ +static pj_bool_t handle_return(cli_telnet_sess *sess) +{ + pj_status_t status; + pj_bool_t retval = PJ_TRUE; + + pj_pool_t *pool; + pj_cli_exec_info info; + + send_return_key(sess); + insert_history(sess, (char *)&sess->rcmd->rbuf); + + pool = pj_pool_create(sess->pool->factory, "handle_return", + PJ_CLI_TELNET_POOL_SIZE, PJ_CLI_TELNET_POOL_INC, + NULL); + + status = pj_cli_sess_exec(&sess->base, (char *)&sess->rcmd->rbuf, + pool, &info); + + switch (status) { + case PJ_CLI_EINVARG: + send_inv_arg(sess, &info, PJ_FALSE, PJ_FALSE); + break; + case PJ_CLI_ETOOMANYARGS: + send_too_many_arg(sess, &info, PJ_FALSE, PJ_FALSE); + break; + case PJ_CLI_EAMBIGUOUS: + case PJ_CLI_EMISSINGARG: + send_ambi_arg(sess, &info, PJ_FALSE, PJ_FALSE); + break; + case PJ_CLI_EEXIT: + retval = PJ_FALSE; + break; + case PJ_SUCCESS: + send_prompt_str(sess); + break; + } + if (retval) { + sess->rcmd->rbuf[0] = 0; + sess->rcmd->len = 0; + sess->rcmd->cur_pos = sess->rcmd->len; + } + + pj_pool_release(pool); + return retval; +} + +/* + * This method is to process the right key character sent by client. + */ +static pj_bool_t handle_right_key(cli_telnet_sess *sess) +{ + if (recv_buf_right_len(sess->rcmd)) { + unsigned char *data = &sess->rcmd->rbuf[sess->rcmd->cur_pos++]; + telnet_sess_send2(sess, data, 1); + return PJ_TRUE; + } + return PJ_FALSE; +} + +/* + * This method is to process the left key character sent by client. + */ +static pj_bool_t handle_left_key(cli_telnet_sess *sess) +{ + static const unsigned char move_cursor_left = 0x08; + if (sess->rcmd->cur_pos) { + telnet_sess_send2(sess, &move_cursor_left, 1); + --sess->rcmd->cur_pos; + return PJ_TRUE; + } + return PJ_FALSE; +} + +/* + * This method is to process the up/down key character sent by client. + */ +static pj_bool_t handle_up_down(cli_telnet_sess *sess, pj_bool_t is_up) +{ + pj_str_t *history; + + PJ_ASSERT_RETURN(sess, PJ_FALSE); + + history = get_prev_history(sess, is_up); + if (history) { + pj_str_t send_data; + char str[PJ_CLI_MAX_CMDBUF]; + enum { + MOVE_CURSOR_LEFT = 0x08, + CLEAR_CHAR = 0x20 + }; + send_data.ptr = &str[0]; + send_data.slen = 0; + + /* Move cursor position to the beginning of line */ + if (sess->rcmd->cur_pos > 0) { + pj_memset(send_data.ptr, MOVE_CURSOR_LEFT, sess->rcmd->cur_pos); + send_data.slen = sess->rcmd->cur_pos; + } + + if (sess->rcmd->len > (unsigned)history->slen) { + /* Clear the command currently shown*/ + unsigned buf_len = sess->rcmd->len; + pj_memset(&send_data.ptr[send_data.slen], CLEAR_CHAR, buf_len); + send_data.slen += buf_len; + + /* Move cursor position to the beginning of line */ + pj_memset(&send_data.ptr[send_data.slen], MOVE_CURSOR_LEFT, + buf_len); + send_data.slen += buf_len; + } + /* Send data */ + pj_strcat(&send_data, history); + telnet_sess_send(sess, &send_data); + pj_ansi_strncpy((char*)&sess->rcmd->rbuf, history->ptr, history->slen); + sess->rcmd->rbuf[history->slen] = 0; + sess->rcmd->len = history->slen; + sess->rcmd->cur_pos = sess->rcmd->len; + return PJ_TRUE; + } + return PJ_FALSE; +} + +static pj_status_t process_vt100_cmd(cli_telnet_sess *sess, + unsigned char *cmd) +{ + pj_status_t status = PJ_TRUE; + switch (*cmd) { + case TC_ESC: + break; + case TC_UP: + status = handle_up_down(sess, PJ_TRUE); + break; + case TC_DOWN: + status = handle_up_down(sess, PJ_FALSE); + break; + case TC_RIGHT: + status = handle_right_key(sess); + break; + case TC_LEFT: + status = handle_left_key(sess); + break; + case TC_END: + break; + case TC_HOME: + break; + case TC_CTRL_C: + break; + case TC_CR: + break; + case TC_BS: + break; + case TC_TAB: + break; + case TC_QM: + break; + case TC_BELL: + break; + case TC_DEL: + break; + }; + return status; +} + +PJ_DEF(void) pj_cli_telnet_cfg_default(pj_cli_telnet_cfg *param) +{ + pj_assert(param); + + pj_bzero(param, sizeof(*param)); + param->port = PJ_CLI_TELNET_PORT; + param->log_level = PJ_CLI_TELNET_LOG_LEVEL; +} + +/* + * Send a message to a telnet session + */ +static pj_status_t telnet_sess_send(cli_telnet_sess *sess, + const pj_str_t *str) +{ + pj_ssize_t sz; + pj_status_t status = PJ_SUCCESS; + + sz = str->slen; + if (!sz) + return PJ_SUCCESS; + + pj_mutex_lock(sess->smutex); + + if (sess->buf_len == 0) + status = pj_activesock_send(sess->asock, &sess->op_key, + str->ptr, &sz, 0); + /* If we cannot send now, append it at the end of the buffer + * to be sent later. + */ + if (sess->buf_len > 0 || + (status != PJ_SUCCESS && status != PJ_EPENDING)) + { + int clen = (int)sz; + + if (sess->buf_len + clen > CLI_TELNET_BUF_SIZE) + clen = CLI_TELNET_BUF_SIZE - sess->buf_len; + if (clen > 0) + pj_memmove(sess->buf + sess->buf_len, str->ptr, clen); + if (clen < sz) { + pj_ansi_snprintf((char *)sess->buf + CLI_TELNET_BUF_SIZE, + MAX_CUT_MSG_LEN, CUT_MSG); + sess->buf_len = CLI_TELNET_BUF_SIZE + + pj_ansi_strlen((char *)sess->buf+ + CLI_TELNET_BUF_SIZE); + } else + sess->buf_len += clen; + } else if (status == PJ_SUCCESS && sz < str->slen) { + pj_mutex_unlock(sess->smutex); + return PJ_CLI_ETELNETLOST; + } + + pj_mutex_unlock(sess->smutex); + + return PJ_SUCCESS; +} + +/* + * Send a message to a telnet session with formatted text + * (add single linefeed character with carriage return) + */ +static pj_status_t telnet_sess_send_with_format(cli_telnet_sess *sess, + const pj_str_t *str) +{ + pj_scanner scanner; + pj_str_t out_str; + static const pj_str_t CR_LF = {("\r\n"), 2}; + int str_len = 0; + char *str_begin = 0; + + PJ_USE_EXCEPTION; + + pj_scan_init(&scanner, str->ptr, str->slen, + PJ_SCAN_AUTOSKIP_WS, &on_syntax_error); + + str_begin = scanner.begin; + + PJ_TRY { + while (!pj_scan_is_eof(&scanner)) { + pj_scan_get_until_ch(&scanner, '\n', &out_str); + str_len = scanner.curptr - str_begin; + if (*scanner.curptr == '\n') { + if ((str_len > 1) && (out_str.ptr[str_len-2] == '\r')) + { + continue; + } else { + int str_pos = str_begin - scanner.begin; + + if (str_len > 0) { + pj_str_t s; + pj_strset(&s, &str->ptr[str_pos], str_len); + telnet_sess_send(sess, &s); + } + telnet_sess_send(sess, &CR_LF); + + if (!pj_scan_is_eof(&scanner)) { + pj_scan_advance_n(&scanner, 1, PJ_TRUE); + str_begin = scanner.curptr; + } + } + } else { + pj_str_t s; + int str_pos = str_begin - scanner.begin; + + pj_strset(&s, &str->ptr[str_pos], str_len); + telnet_sess_send(sess, &s); + } + } + } + PJ_CATCH_ANY { + pj_scan_fini(&scanner); + return (PJ_GET_EXCEPTION()); + } + PJ_END; + + return PJ_SUCCESS; +} + +static pj_status_t telnet_sess_send2(cli_telnet_sess *sess, + const unsigned char *str, int len) +{ + pj_str_t s; + + pj_strset(&s, (char *)str, len); + return telnet_sess_send(sess, &s); +} + +static void telnet_sess_destroy(pj_cli_sess *sess) +{ + cli_telnet_sess *tsess = (cli_telnet_sess *)sess; + pj_mutex_t *mutex = ((struct cli_telnet_fe *)sess->fe)->mutex; + + pj_mutex_lock(mutex); + pj_list_erase(sess); + pj_mutex_unlock(mutex); + + pj_mutex_lock(tsess->smutex); + pj_mutex_unlock(tsess->smutex); + pj_activesock_close(tsess->asock); + pj_mutex_destroy(tsess->smutex); + pj_pool_release(tsess->pool); +} + +static void telnet_fe_write_log(pj_cli_front_end *fe, int level, + const char *data, int len) +{ + struct cli_telnet_fe * tfe = (struct cli_telnet_fe *)fe; + pj_cli_sess *sess; + + pj_mutex_lock(tfe->mutex); + + sess = tfe->sess_head.next; + while (sess != &tfe->sess_head) { + cli_telnet_sess *tsess = (cli_telnet_sess *)sess; + + sess = sess->next; + if (tsess->base.log_level > level) { + pj_str_t s; + + pj_strset(&s, (char *)data, len); + telnet_sess_send_with_format(tsess, &s); + } + } + + pj_mutex_unlock(tfe->mutex); +} + +static void telnet_fe_destroy(pj_cli_front_end *fe) +{ + struct cli_telnet_fe *tfe = (struct cli_telnet_fe *)fe; + pj_cli_sess *sess; + + tfe->is_quitting = PJ_TRUE; + if (tfe->worker_thread) { + pj_thread_join(tfe->worker_thread); + } + + pj_mutex_lock(tfe->mutex); + + /* Destroy all the sessions */ + sess = tfe->sess_head.next; + while (sess != &tfe->sess_head) { + (*sess->op->destroy)(sess); + sess = tfe->sess_head.next; + } + + pj_mutex_unlock(tfe->mutex); + + pj_activesock_close(tfe->asock); + if (tfe->own_ioqueue) + pj_ioqueue_destroy(tfe->cfg.ioqueue); + + if (tfe->worker_thread) { + pj_thread_destroy(tfe->worker_thread); + tfe->worker_thread = NULL; + } + + pj_mutex_destroy(tfe->mutex); + pj_pool_release(tfe->pool); +} + +static int poll_worker_thread(void *p) +{ + struct cli_telnet_fe *fe = (struct cli_telnet_fe *)p; + + while (!fe->is_quitting) { + pj_time_val delay = {0, 50}; + pj_ioqueue_poll(fe->cfg.ioqueue, &delay); + } + + return 0; +} + +static pj_bool_t telnet_sess_on_data_sent(pj_activesock_t *asock, + pj_ioqueue_op_key_t *op_key, + pj_ssize_t sent) +{ + cli_telnet_sess *sess = (cli_telnet_sess *) + pj_activesock_get_user_data(asock); + + PJ_UNUSED_ARG(op_key); + + if (sent <= 0) { + pj_cli_sess_end_session(&sess->base); + return PJ_FALSE; + } + + pj_mutex_lock(sess->smutex); + + if (sess->buf_len) { + int len = sess->buf_len; + + sess->buf_len = 0; + if (telnet_sess_send2(sess, sess->buf, len) != PJ_SUCCESS) { + pj_mutex_unlock(sess->smutex); + pj_cli_sess_end_session(&sess->base); + return PJ_FALSE; + } + } + + pj_mutex_unlock(sess->smutex); + + return PJ_TRUE; +} + +static pj_bool_t telnet_sess_on_data_read(pj_activesock_t *asock, + void *data, + pj_size_t size, + pj_status_t status, + pj_size_t *remainder) +{ + cli_telnet_sess *sess = (cli_telnet_sess *) + pj_activesock_get_user_data(asock); + struct cli_telnet_fe *tfe = (struct cli_telnet_fe *)sess->base.fe; + unsigned char *cdata = (unsigned char*)data; + pj_status_t is_valid = PJ_TRUE; + + PJ_UNUSED_ARG(size); + PJ_UNUSED_ARG(remainder); + + if (status != PJ_SUCCESS && status != PJ_EPENDING) { + pj_cli_sess_end_session(&sess->base); + return PJ_FALSE; + } + + if (tfe->is_quitting) + return PJ_FALSE; + + pj_mutex_lock(sess->smutex); + + switch (sess->parse_state) { + case ST_CR: + sess->parse_state = ST_NORMAL; + if (*cdata == 0 || *cdata == '\n') + pj_mutex_unlock(sess->smutex); + is_valid = handle_return(sess); + if (!is_valid) + return PJ_FALSE; + pj_mutex_lock(sess->smutex); + break; + case ST_NORMAL: + if (*cdata == IAC) { + sess->parse_state = ST_IAC; + } else if (*cdata == 127) { + is_valid = handle_backspace(sess, cdata); + } else if (*cdata == 27) { + sess->parse_state = ST_ESC; + } else { + if (recv_buf_insert(sess->rcmd, cdata)) { + if (*cdata == '\r') { + sess->parse_state = ST_CR; + } else if ((*cdata == '\t') || (*cdata == '?')) { + is_valid = handle_tab(sess); + } else if (*cdata > 31 && *cdata < 127) { + is_valid = handle_alfa_num(sess, cdata); + } + } else { + is_valid = PJ_FALSE; + } + } + break; + case ST_ESC: + if (*cdata == 91) { + sess->parse_state = ST_VT100; + } else { + sess->parse_state = ST_NORMAL; + } + break; + case ST_VT100: + sess->parse_state = ST_NORMAL; + is_valid = process_vt100_cmd(sess, cdata); + break; + case ST_IAC: + switch ((unsigned) *cdata) { + case DO: + sess->parse_state = ST_DO; + break; + case DONT: + sess->parse_state = ST_DONT; + break; + case WILL: + sess->parse_state = ST_WILL; + break; + case WONT: + sess->parse_state = ST_WONT; + break; + default: + sess->parse_state = ST_NORMAL; + break; + } + break; + case ST_DO: + receive_do(sess, *cdata); + sess->parse_state = ST_NORMAL; + break; + case ST_DONT: + receive_dont(sess, *cdata); + sess->parse_state = ST_NORMAL; + break; + case ST_WILL: + receive_will(sess, *cdata); + sess->parse_state = ST_NORMAL; + break; + case ST_WONT: + receive_wont(sess, *cdata); + sess->parse_state = ST_NORMAL; + break; + default: + sess->parse_state = ST_NORMAL; + break; + } + if (!is_valid) { + send_bell(sess); + } + + pj_mutex_unlock(sess->smutex); + + return PJ_TRUE; +} + +static pj_bool_t telnet_fe_on_accept(pj_activesock_t *asock, + pj_sock_t newsock, + const pj_sockaddr_t *src_addr, + int src_addr_len) +{ + struct cli_telnet_fe *fe = (struct cli_telnet_fe *) + pj_activesock_get_user_data(asock); + pj_status_t sstatus; + pj_pool_t *pool; + cli_telnet_sess *sess; + pj_activesock_cb asock_cb; + + PJ_UNUSED_ARG(src_addr); + PJ_UNUSED_ARG(src_addr_len); + + if (fe->is_quitting) + return PJ_FALSE; + + /* An incoming connection is accepted, create a new session */ + pool = pj_pool_create(fe->pool->factory, "telnet_sess", + PJ_CLI_TELNET_POOL_SIZE, PJ_CLI_TELNET_POOL_INC, + NULL); + if (!pool) { + TRACE_((THIS_FILE, + "Not enough memory to create a new telnet session")); + return PJ_TRUE; + } + + sess = PJ_POOL_ZALLOC_T(pool, cli_telnet_sess); + sess->pool = pool; + sess->base.fe = &fe->base; + sess->base.log_level = fe->cfg.log_level; + sess->base.op = PJ_POOL_ZALLOC_T(pool, struct pj_cli_sess_op); + sess->base.op->destroy = &telnet_sess_destroy; + pj_bzero(&asock_cb, sizeof(asock_cb)); + asock_cb.on_data_read = &telnet_sess_on_data_read; + asock_cb.on_data_sent = &telnet_sess_on_data_sent; + sess->rcmd = PJ_POOL_ZALLOC_T(pool, telnet_recv_buf); + sess->history = PJ_POOL_ZALLOC_T(pool, struct cmd_history); + pj_list_init(sess->history); + sess->active_history = sess->history; + + sstatus = pj_mutex_create_recursive(pool, "mutex_telnet_sess", + &sess->smutex); + if (sstatus != PJ_SUCCESS) + goto on_exit; + + sstatus = pj_activesock_create(pool, newsock, pj_SOCK_STREAM(), + NULL, fe->cfg.ioqueue, + &asock_cb, sess, &sess->asock); + if (sstatus != PJ_SUCCESS) { + TRACE_((THIS_FILE, "Failure creating active socket")); + goto on_exit; + } + + pj_memset(sess->telnet_option, 0, sizeof(sess->telnet_option)); + set_local_option(sess, TRANSMIT_BINARY, PJ_TRUE); + set_local_option(sess, STATUS, PJ_TRUE); + set_local_option(sess, SUPPRESS_GA, PJ_TRUE); + set_local_option(sess, TIMING_MARK, PJ_TRUE); + set_local_option(sess, TERM_SPEED, PJ_TRUE); + set_local_option(sess, TERM_TYPE, PJ_TRUE); + + set_peer_option(sess, TRANSMIT_BINARY, PJ_TRUE); + set_peer_option(sess, SUPPRESS_GA, PJ_TRUE); + set_peer_option(sess, STATUS, PJ_TRUE); + set_peer_option(sess, TIMING_MARK, PJ_TRUE); + set_peer_option(sess, ECHO, PJ_TRUE); + + send_cmd_do(sess, SUPPRESS_GA); + send_cmd_will(sess, ECHO); + send_cmd_will(sess, STATUS); + send_cmd_will(sess, SUPPRESS_GA); + + /* Send prompt string */ + telnet_sess_send(sess, &fe->cfg.prompt_str); + + /* Start reading for input from the new telnet session */ + sstatus = pj_activesock_start_read(sess->asock, pool, 1, 0); + if (sstatus != PJ_SUCCESS) { + TRACE_((THIS_FILE, "Failure reading active socket")); + goto on_exit; + } + + pj_ioqueue_op_key_init(&sess->op_key, sizeof(sess->op_key)); + pj_mutex_lock(fe->mutex); + pj_list_push_back(&fe->sess_head, &sess->base); + pj_mutex_unlock(fe->mutex); + + return PJ_TRUE; + +on_exit: + if (sess->asock) + pj_activesock_close(sess->asock); + else + pj_sock_close(newsock); + + if (sess->smutex) + pj_mutex_destroy(sess->smutex); + + pj_pool_release(pool); + + return PJ_TRUE; +} + +PJ_DEF(pj_status_t) pj_cli_telnet_create(pj_cli_t *cli, + pj_cli_telnet_cfg *param, + pj_cli_front_end **p_fe) +{ + struct cli_telnet_fe *fe; + pj_pool_t *pool; + pj_sock_t sock = PJ_INVALID_SOCKET; + pj_activesock_cb asock_cb; + pj_sockaddr_in addr; + pj_status_t sstatus; + + PJ_ASSERT_RETURN(cli, PJ_EINVAL); + + pool = pj_pool_create(pj_cli_get_param(cli)->pf, "telnet_fe", + PJ_CLI_TELNET_POOL_SIZE, PJ_CLI_TELNET_POOL_INC, + NULL); + fe = PJ_POOL_ZALLOC_T(pool, struct cli_telnet_fe); + if (!fe) + return PJ_ENOMEM; + + fe->base.op = PJ_POOL_ZALLOC_T(pool, struct pj_cli_front_end_op); + + if (!param) + pj_cli_telnet_cfg_default(&fe->cfg); + else + pj_memcpy(&fe->cfg, param, sizeof(*param)); + + pj_list_init(&fe->sess_head); + fe->base.cli = cli; + fe->base.type = PJ_CLI_TELNET_FRONT_END; + fe->base.op->on_write_log = &telnet_fe_write_log; + fe->base.op->on_destroy = &telnet_fe_destroy; + fe->pool = pool; + + if (!fe->cfg.ioqueue) { + /* Create own ioqueue if application doesn't supply one */ + sstatus = pj_ioqueue_create(pool, 8, &fe->cfg.ioqueue); + if (sstatus != PJ_SUCCESS) + goto on_exit; + fe->own_ioqueue = PJ_TRUE; + } + + sstatus = pj_mutex_create_recursive(pool, "mutex_telnet_fe", &fe->mutex); + if (sstatus != PJ_SUCCESS) + goto on_exit; + + /* Start telnet daemon */ + sstatus = pj_sock_socket(pj_AF_INET(), pj_SOCK_STREAM(), 0, + &sock); + if (sstatus != PJ_SUCCESS) + goto on_exit; + + pj_sockaddr_in_init(&addr, NULL, fe->cfg.port); + + sstatus = pj_sock_bind(sock, &addr, sizeof(addr)); + if (sstatus == PJ_SUCCESS) { + pj_sockaddr_in addr; + int addr_len = sizeof(addr); + + sstatus = pj_sock_getsockname(sock, &addr, &addr_len); + if (sstatus != PJ_SUCCESS) + goto on_exit; + + fe->cfg.port = pj_sockaddr_in_get_port(&addr); + if (param) + param->port = fe->cfg.port; + + PJ_LOG(3, (THIS_FILE, "CLI telnet daemon listening at port %d", + fe->cfg.port)); + + if (fe->cfg.prompt_str.slen == 0) { + pj_str_t prompt_sign = {"> ", 2}; + char *prompt_data = pj_pool_alloc(fe->pool, + pj_gethostname()->slen+2); + fe->cfg.prompt_str.ptr = prompt_data; + + pj_strcpy(&fe->cfg.prompt_str, pj_gethostname()); + pj_strcat(&fe->cfg.prompt_str, &prompt_sign); + } + } else { + PJ_LOG(3, (THIS_FILE, "Failed binding the socket")); + goto on_exit; + } + + sstatus = pj_sock_listen(sock, 4); + if (sstatus != PJ_SUCCESS) + goto on_exit; + + pj_bzero(&asock_cb, sizeof(asock_cb)); + asock_cb.on_accept_complete = &telnet_fe_on_accept; + sstatus = pj_activesock_create(pool, sock, pj_SOCK_STREAM(), + NULL, fe->cfg.ioqueue, + &asock_cb, fe, &fe->asock); + if (sstatus != PJ_SUCCESS) + goto on_exit; + + sstatus = pj_activesock_start_accept(fe->asock, pool); + if (sstatus != PJ_SUCCESS) + goto on_exit; + + if (fe->own_ioqueue) { + /* Create our own worker thread */ + sstatus = pj_thread_create(pool, "worker_telnet_fe", + &poll_worker_thread, fe, 0, 0, + &fe->worker_thread); + if (sstatus != PJ_SUCCESS) + goto on_exit; + } + + pj_cli_register_front_end(cli, &fe->base); + + if (p_fe) + *p_fe = &fe->base; + + return PJ_SUCCESS; + +on_exit: + if (fe->asock) + pj_activesock_close(fe->asock); + else if (sock != PJ_INVALID_SOCKET) + pj_sock_close(sock); + + if (fe->own_ioqueue) + pj_ioqueue_destroy(fe->cfg.ioqueue); + + if (fe->mutex) + pj_mutex_destroy(fe->mutex); + + pj_pool_release(pool); + return sstatus; +} diff --git a/pjlib-util/src/pjlib-util/errno.c b/pjlib-util/src/pjlib-util/errno.c index 83a25753..1949d05e 100644 --- a/pjlib-util/src/pjlib-util/errno.c +++ b/pjlib-util/src/pjlib-util/errno.c @@ -96,6 +96,16 @@ static const struct PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINCHDR, "Incomplete response header received"), PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINSBUF, "Insufficient buffer"), PJ_BUILD_ERR( PJLIB_UTIL_EHTTPLOST, "Connection lost"), + + /* CLI */ + PJ_BUILD_ERR( PJ_CLI_EEXIT, "Exit current session"), + PJ_BUILD_ERR( PJ_CLI_EMISSINGARG, "Missing argument"), + PJ_BUILD_ERR( PJ_CLI_ETOOMANYARGS, "Too many arguments"), + PJ_BUILD_ERR( PJ_CLI_EINVARG, "Invalid argument"), + PJ_BUILD_ERR( PJ_CLI_EBADNAME, "Command name already exists"), + PJ_BUILD_ERR( PJ_CLI_EBADID, "Command id already exists"), + PJ_BUILD_ERR( PJ_CLI_EBADXML, "Invalid XML format"), + PJ_BUILD_ERR( PJ_CLI_ETELNETLOST, "Connection lost"), }; #endif /* PJ_HAS_ERROR_STRING */ -- cgit v1.2.3