** Sample Reference Manual for a version of embTelnet **

InterNiche's embTelnet User's Guide
for {chip name, toolchain id}

51 E. Campbell Ave
Suite 160
Campbell, CA.  95008
Copyright ©2011-2012
InterNiche Technologies Inc.
email: Sales@iNiche.com
support: http://www.iniche.com/support

InterNiche Technologies Inc. has made every effort to assure the accuracy of the information contained in this documentation. We appreciate any feedback you may have for improvements. Please send your comments to support@iniche.com.

The software described in this document is furnished under a license and may be used, or copied, only in accordance with the terms of such license.

Copyright © 2012 by InterNiche Technologies, Inc. All Rights Reserved

Revised: August 9, 2012

Trademarks

All terms mentioned in this document that are known to be service marks, tradenames, trademarks, or registered trademarks are property of their respective holders and have been appropriately capitalized. InterNiche Technologies Inc. cannot attest to the complete accuracy of this information. The use of a term in this document should not be regarded as affecting the validity of any service mark, tradename, trademark, or registered trademark.

Table of Contents

  1. Overview
  2. embTelnet
  3. Product Requirements
  4. Installation
  5. Project Integration
  6. Installing the Example1 Demo Application
  7. Sample Application Walkthrough
  8. Debug vs Non-Debug Libraries
  9. Configuration
  10. Tunable and Reference Parameters
  11. API
  12. Example1 Revisited - API Interaction
  13. embTelnet Menu CLI
  14. Related Products
  15. For Additional Information ...

Overview

This Technical reference is provided with the InterNiche embTelnet library. The purpose of this document is to provide enough information so that a moderately experienced "C" programmer with a reasonable understanding of TCP/IP protocols can develop Telnet-based server applications using IAR development tools.

The primary features of this library are:

embTelnet

embTelnet consists of embTelnet.a, embTelnet-debug.a, telnetdata.c, telnetdata.h and a sample telnet application called "example1".

Telnet API for the telnet library is implemented as a set of direct and callback functions. Direct functions are implemented within embTelnet and are invoked directly by the application. Access to these functions is also made available as menu commands.

Product Requirements

Installation

Before you start using this product, it is important that you have successfully built, downloaded and executed some small program using InterNiche's TCP/IP Library to your STM32F207 based board using IAR development tools. This is so that you have some end-to-end experience with your entire development environment and that you have confidence that your Ethernet and TCP/IP stack works.

Project Integration

  1. Begin with a working embTCP or embDUAL project ('debug' mode)
  2. Unzip the package in to the same directory that contains the embsrc, emblibs and emb_h directories
  3. Add embTelnet to your project:
    1. edit tcpdata.c file and make the following modifications:
      • Find the in_modules array and add the following line:
        &telnet_module,
      • Add the following line early in the file:
        extern struct net_module telnet_module;
      • Verify that the file "inmain.c" contains a call to "example_init()" between the call to nichestack_init() and TK_START_OS().
    2. Add emblibs/embTelnet-debug.a to your project
    3. Include the file telnetdata.c into your existing project

This will create an operating system task for embTelnet and will integrate it with the protocol stack.

Installing the Example1 Demo Application

Example1 is a very simple application that uses embTelnet. It is designed to show that embTelnet is functioning and that a remote system can connect to it. Once this is done, it should be removed from your project.

Example1 assumes that it is linked with a DEBUG version of embTCP and that the system has a console.

The file "example1.c" provides a fairly thorough implementation of this package, including initialization activities, callback registration and actions to be taken when a status change occurs on a connection, including open, close and data reception.

To add Example1:

  1. If your existing project contains references to the embTCP example, remove them from your project
  2. Add telnet_examples/example1.c to your project
  3. Add embsrc/telnetdata.c to your project
  4. Build and download the resulting image
  5. Start your application. Once the system begins to execute, it will display on your configured output device a message similar to the following:
    embTelnet - Licensed for XXX. 0000-0000-0000-0000
    Copyright InterNiche Technologies, Inc. 1996-2012. All rights reserved.
    
  6. From another system open a telnet client application and connect to the IP address of the running embTCP and embTelnet. Example1 provides access using username "guest" and password "guest" (no quote characters, of course).
    "Welcome to InterNiche embTelnet server 1.0";
    

Sample Application Walkthrough

Interaction among, telnet client, telnet library(telnet server), example1.c and the telnetdata.c:

The telnet server task creation , global , connection, sessions and application stats initialization will all be done at the initialization time . After the initialization, telnet server will be listening to the telnet client connections.

example1.c , the telnet example application will communicate with the telnet clients through telnet library using telnet API . telnet server invokes function in telnetdata.c which in turn calls functions in example1.c . example1.c , maintains a database of all the clients. The database is an array of structures. The structure is telApp_connstats and the global array variable is telAppstats . Both of these are in example1.c. The maximum number of clients is based on a #define MAX_TELNET_SESS which is in telnetdata.h

telnet server maintains a similar database which is on the heap. This is allocated at the initialization time. The maximum number of clients for this is based on a variable, max_telnet_conn which is initialized to MAX_TELNET_SESS. This variable is in telnetdata.c. If the application developer wants to change this value, that can be done by modifying the value MAX_TELNET_SESS which will get assigned to the variable, max_telnet_conn.

Whenever a user telnets to the server , say for example types in telnet <ip address of iniche server> at the command prompt, telnet server will allocate memory for the connection on the heap and give a connection id for the connection if there are no max telnet connections already. The check will be by comparing the number of existing connections to max_telnet_conn . It then displays a welcome banner and login prompt.

Once the user types in username and password , telnet server will invoke the function validate_telUser() in telnetdata.c. This function has an option to check if the client ip address is valid by calling function check_telipAddr() in example1.c and then this function will validate the typed in username and password. If the valid username and password are not typed in, then the user will be allowed to try for the number of times based on the value in telnet_max_tries, a variable in telnetdata.c. If the login attempts, exceed that limit then, the user will have to telnet again. Once the valid username and valid password are entered by the user, callback functions will be registered by calling telApp_callbcks_reg() in example1.c. This telApp_callbcks_reg () function will register two callback functions telApp_connsts() and telApp_errRecv(). Both these functions are in example1.c. While registering the callback functions, telApp_callbcks_reg(), will use an API function tel_callbckfn_reg() from the library. Its prototype is in telnetdata.h.

When the validate_telUser() function returns success, telnet server will invoke the callback function, telApp_connsts() with connection status as SESS_OPENED. This SESS_OPENED #define is in telnetdata.h. If the call to telApp_connsts() function is success, telnet server will present a "Welcome <username>" message to the client.

When the connection state is SESS_OPENED, telApp_connsts() will:

  1. Assign an entry to the connection in the telAppstats table if max connections are not present already by assigning conn_state, conn_ID,username and context to the private memory of the entry. These conn_ID, conn_state, username and private are all the members of the structure telApp_connstats in example1.c. Connection context will be assigned to the private member by calling the API function , get_context(), whose prototype is in telnetdata.h.
  2. Invoke init_telconn() , an API function for generic I/O stream operations, whose prototype is in telnetdata.h .
  3. Display the cli_prompt at the client window. To display the cli_prompt onto the client it uses the API function call, tel_send(),whose prototype is in telnetdata.h.

Now the application, example1.c will be ready to accept commands from the telnet client. When the user enters carriage return / characters followed by carriage return, telnet server will collect the characters and invoke the same function telApp_connsts() in example1.c but with SESS_HAS_DATA status. This SESS_HAS_DATA #define is in telnetdata.h.

When the connection state is SESS_HAS_DATA, telApp_connsts() will:

  1. Invoke tel_readbuf(), an API function to copy the contents of the telnet session's command buf contents to the applications connection buffer, member char buffer[] in the structure , telApp_connstats. Prototype for tel_readbuf() is in telnetdata.h.
  2. Invokes telApp_cmd_exec() function in example1.c to execute the command entered at the telnet client.

The telApp_cmd_exec() function in example1.c, will execute the command, by invoking the API function , call_clicmd(), whose prototype is in telnetdata.h. telApp_cmd_exec() function will take following actions for the commands entered.

  1. If the command entered is logout, then an API function, tel_closeconn() will be called to close the connection.tel_closeconn() protype is in telnetdata.h.
  2. If any other valid command is entered, it will just display the cli_promt at the client window, after the command is excuted. To display cli_promt, it will use the API function tel_send().
  3. If any invalid command is entered, it will again just display the cli_prompt at the client window, as the printing of the error message is taken care by the API function, call_clicmd().To display cli_promt, it will use the API function tel_send().

A telnet client session will be closed because of the following actions:

Whenever a connection is closed, telnet server will again invoke the function, telApp_connsts() in example1.c but with SESS_CLOSED status.

When the connection state is SESS_CLOSED, telApp_connsts() will:

Free the entry to the connection in the telAppstats table by releasing the conn_ID, conn_state, username and the connection context. To release the connection context, it uses the API function, free_context(), whose prototype is in telnetdata.h.

If the #define MSGS_TO_CONSOLE in telnetdata.h is set to 1, then we can see messages on the console or the serial port for the following actions:

Debug vs Non-Debug Libraries

embTelnet includes two versions of the library: Debug, which is intended for use during initial application development; and Non-Debug, which is appropriate for use in your final product.

Configuration

Tunable and Reference Parameters

The telnetdata.c file contains a set of parameters that may be tuned for the specific implementation. These are show in the following table, and their values are set in telnetdata.h.

ParameterTypeDefault ValueDescription
intmax_telnet_connMAX_TELNET_SESSDefault max no. of telnet sessions
inttelnet_rxbuf_lenTEL_RECV_BUF_SIZEDefault telnet rxbuf len
inttelnet_txbuf_lenTEL_SEND_BUF_SIZEDefault telnet txbuf len
inttelnet_portTELNET_PORTDefault telnet port no
inttelnet_max_triesTEL_MAX_LOGIN_TRIESDefault max no of tries before lock out
inttelnet_idle_timeTEL_IDLE_TIMETime in seconds for which it can be idle
intsess_timeout_enableTEL_SESS_TIMEOUTenable session timeout
char *telclient_banner"Welcome to InterNiche embTelnet server 1.0"String presented to client upon successful connection establishment

From telnetdata.h:

#define  TEL_RECV_BUF_SIZE       256   /* telnet receive buffer size */
#define  TEL_SEND_BUF_SIZE       256   /* telnet transmit buffer size */
#define  TELNET_PORT             23    /* telnet port    */
#define  TEL_MAX_LOGIN_TRIES     5     /* telnet client max no. of login tries */
#define  TEL_IDLE_TIME           600   /* telnet idle time after which connection is deleted */
#define  TEL_SESS_TIMEOUT        1     /* enabling the session timeout */

/* Configurable limit on max number of telnet sessions.
 * Setting this value to 0 or -1 results in no limitation
 * on number of sessions. The default setting is 2.
 */
#define  MAX_TELNET_SESS         2

API

The embTelnet API is implemented as a set of functions falling into two categories:

  1. Direct Functions, Direct functions are implemented at the telnet server. These functions can be invoked by the application. Direct function prototypes are available in telnetdata.h. These functions are also implemented in the form of menu commands.
  2. Callback functions are to be implemented by the application developer. For examples, refer to example1.c.

Direct functions:

Name

tel_startup()

Syntax

int tel_startup(void );

Parameters

None

Description

At the initialization of the telnet module, this function is called. When this function is called, telnet server task would have been created and would be in suspended mode.

This function will initialize all the connections and statistics at the server and start listening to telnet client connections. Then it will resume the telnet server task. This function sets a flag to indicate that this function is called and telnet server is resumed.

Usage:

{
   int err  = 0;
   err = tel_startup();

   if (err  != 0)
      printf("App:Error in tel_startup() \n");
}

This function is implemented as a menu option (telstartup) through the console. This menu option is associated with telnet group.

Returns

int (SUCCESS /error code)

Notes

Name

tel_shutdown()

Syntax

void tel_shutdown( void );

Parameters

None

Description

tel_shutdown() deletes all active connections and sets shut_down_pending flag and signals the telnet task. Task suspension will be done inside the task body after the task checks that the flag is set and there are no active connections.

This function can be invoked by the application.

Usage:

{
   tel_shutdown();
}

This function is implemented as a menu option (telshutdown) through the console . This menu option is associated with telnet group.

Returns

Nothing

Notes

Name

tel_closeconn()

Syntax

int tel_closeconn( int telconnID );

Parameters

telconnIDThe ConnectionID associated with the session being closed. See telApp_connsts() for more infomration concerning conn_ID.

Description

This function can be called by the application. It frees the memory that was allocated for the Telnet connection. It deletes the object from the queue of open telnet connections and also closes the underlying TCP connection. It is used in example1.c

Usage:

{
   int err  = 0;
   int conn_id = 2;

   err = tel_closeconn(conn_id);
   if (err  != 0)
      printf("App:Error in tel_closeconn() \n");
}

This function is available as a menu option (teldelconn) at the console. This menu option is associated with telnet group.

With the menu option, either a single connection can be deleted or all the active connections can be deleted.

Returns

int (SUCCESS/errorcode)

Notes

Name

tel_get_stats()

Syntax

int tel_getstats(struct Tel_API_Stats*);

Parameters

struct Tel_API_Stats *Memory address into which the results will be written.

Description

This function can be called by the application. It copies global and sessions statistics to the memory provided by the calling application.

Usage:

{
   struct Tel_API_Stats *stats;

   stats = (struct Tel_API_Stats *)malloc(sizeof (struct Tel_API_Stats)); /* Assuming malloc () memory alloc function used */
   if (stats)
  {
      err   = tel_get_stats(stats);

      printf( "Total connections opened = %ld\n", stats->telStats.conn_opened);

      free (stats);  /* Assuming free() is memory dealloc function used */
   }
   else
}

This is accessible as a menu option (telstats). This menu option is associated with telnet group.

Returns

int (SUCCESS/errorcode)

Notes

Name

tel_send()

Syntax

int tel_send(int telconnID, char *buf, int len);

Parameters

connectionIDConnectionID of this Telnet Session. See telApp_connsts() for more information on conn_ID
bufAddress of data to send
lenLen of the data to be sent

Description

This function should be called by the application whenever it wants to send data to the remote client.

Usage:

{
   int  bytes_sent = 0;
   char  *message = "Hello.";

   bytes_sent = tel_send(conn_id, message, strlen(message));
   if  (bytes_sent != (int)strlen(message))
      printf("error  sending\n");
}

Returns

number of bytes sent

Name

tel_readbuf()

Syntax

int tel_readbuf(int telconnID, char *buf, int len);

Parameters

connectionIDConnectionID of this Telnet Session. See telApp_connsts() for more information on connection IDs
bufMemory address of the buffer for received data
lenLength of the receive buffer

Description

This function copies received data into the application buffer.

Usage:

{
   int  bytes_rcvd  = 0;
   char  buf[32];
   int conn_id = 2;

   bytes_rcvd  =  tel_readbuf(conn_id, buf, 32);

}

Returns

int - number of bytes copied into the application buffer

Name

tel_callbckfn_reg()

Syntax

int tel_callbckfn_reg(int connID, int code_type, int (*func_ptr)(int, void *));

Parameters

connectionIDThis is provided by embTelnet through the validate_telUser() function.
code_typeeither CONN_STS or ERR_CODE
func_ptraddress of function being registered with embTelnet

Description

This function registers a call back function and should be invoked once validate_telUser() determines that the new user is valid. Currently, two callback functions can be registered per telnet session: "telApp_connsts()" and "telApp_errRecv()".

Usage:

{
   int err = 0;

   err = tel_callbckfn_reg(connID, CONN_STS, &telApp_connsts); /* Conn status call back registration */

}

Returns

int - SUCCESS or error code

Name

init_telconn()

Syntax

int init_telconn(int telconnID, void *desc, char *username);

Parameters

connectionIDThis was previously provided to the application through the telApp_connsts() callback function.
descPrivate memory of the application used for CLI context
usernameusername used to verify if the telnet user is same as the application user

Description

This is initializing of of the telnet client connection. This function does registering of I/O operations used by CLI to communicate with the client window. It is used in example1.c

Usage:

{
   int   err = 0;
   void *conn_mem;
   char  username[32]

   strcpy(username,"guest");

   conn_mem  = (void *)get_context();

   err = init_telconn(conn_ID,conn_mem,username);
}

Returns

int - SUCCESS or error code

Name

call_clicmd ()

Syntax

int call_clicmd( void *ctx, char *cmd);

Parameters

ctxcontext pointer retrieved from an earlier call to get_context()
cmdcommand line to execute

Description

This function calls cli command execution. It is used in example1.c

Usage:

{
   int err  = 0;
   void *ctx;
   char *cmdbuf = "telstats -c -g -s";

   /* ctx was acquired from get_context() */
   err = call_clicmd(ctx, cmdbuf);
}

Returns

int - SUCCESS or error code

Name

get_context()

Syntax

void *get_context( );

Parameters

None.

Description

This function allocates a context to be used for subsequent use in call_clicmd() function calls. It is recommended that this be called by the callback function tellApp_connsts() when a new connection is opened.

Usage:

{
   void *ctx;

   ctx  = (void *)get_context();
}

Returns

void *ctx

Name

free_context()

Syntax

void free_context(void *ctx );

Parameters

ctxthe context being freed

Description

This function frees context for the connection. This function's usage is shown in example1.c

This function frees a previously allocated context and should be called when tellApp_connsts() learns that a connection has been closed.

Usage:

{
   free_context(ctx);
}

Returns

Nothing

Callback functions:

These functions will be called by the telnet server.

Name

telApp_connsts()

Syntax

int telApp_connsts(int conn_ID, void *parm1);

Parameters

conn_IDThis is the Connection ID used to uniquely identify this connection for use in all "direct" calls.
paramThe address of a struct tel_conn_sts_parm{ } structure (see telnetdata.h)

Description

Telnet server invokes this function when it recognizes one of the following events occurring on a telnet client:

Returns

int - SUCCESS or error code

Notes

Example

int telApp_connsts(int conn_ID, void *parm1) {
   ...
   $info = (struct struct tel_conn_sts_parms *)parm1;
   switch( $info->status ) {
   case SESS_OPENED:
      printf("user %s has just logged in with Connection ID = %d\n", info->username, conn_ID);
      break;
   case SESS_CLOSED:
      printf("user %s has logged out\n", info->username);
      break;
   case SESS_HAS_DATA:
      len = tel_readbuf( conn_ID, bigbuffer, biglen );
      printf("user %s has provided the following %d bytes of data:\n", info->username, len);
      printf(">>>>> %s\n", bigbuffer);
      break;
   }
}

Name

telApp_errRecv()

Syntax

int telApp_errRecv(int conn_ID, void *parm1);

Parameters

conn_IDUnique identifier of this telnet session. (See telApp_connsts() for more information about conn_ID)
paramparameter passed for this function , which has error code and error string

Description

embTelnet invokes this function when there is an error. This function displays the error string. An example implementation of this function is shown in example1.c

Returns

int - SUCCESS or error code

Name

validate_telUser()

Syntax

int validate_telUser(int connID, char *username, char *password, struct sockaddr sin);

Parameters

conn_IDconn_ID should be used as a parameter to tel_callbckfn_reg()
usernameusername
passwordpassword
sinsocket address of remote station

Description

This is called from the telnet server. Telnet Application is expected to validate the username and password. Here a very simple user validation is implemented verifying if the username and password both are guest. If the user validation is success, this function does the following:

  1. Invoke callbacks registration function.
  2. Invoke a function which can implement ip filtering for the telnet client ip address

Returns

int - SUCCESS/Error code

Notes

Example1 Revisited - API Interaction

The following functions have been provided in example1.c to support the API. They are provided as an example of how the embTelnet integrator may wish to perform similar functions.

Name

example_init()

Syntax

void example_init(void);

Parameters

None

Description

This function is called by the in_main.c module at initialization time.

Put all the initialization needed by the application here.

Returns

Nothing

Name

check_telipAddr()

Syntax

int check_telipAddr(struct sockaddr sin);

Parameters

sinThis is the socket address of the telnet client

Description

If IP filtering needs to be implemented for the IP address, from where telnet clients can login to the telnet server, that can be done in this function. This function is invoked by validate_telUser() function in telnetdata.c

Returns

int - SUCCESS/Error code

Notes

The IP Address 10.0.0.155 will be represented as 0x0A00009B

Name

telApp_callbcks_reg ()

Syntax

int telApp_callbcks_reg(int connID,char *username);

Parameters

connidUnique connection id provided by validate_telUser()
usernamename provided by validate_telUser()

Description

This function registers the callback functions for the telnet application.

There are two call back functions, one for the connection status and the other for error code. This function is invoked by validate_telUser() function in telnetdata.c

Returns

int - SUCCESS/Error code

Name

telApp_cmd_exec()

Syntax

int telApp_cmd_exec(int conn_ID, char *cmdline, int len);

Parameters

conn_IDUnique identifier of this telnet session. (See telApp_connsts() for more information about conn_ID)
commandlineThe complete command string
lenlength (in bytes) of the command string

Description

It will execute the menu command typed in by the user. This uses the call_clicmd() function from the built in library.

Returns

int - SUCCESS/Error code

embTelnet Menu CLI

logout - Terminate a Telnet session

logout

logout - Terminate a Telnet session

Syntax

logout

Parameters

none

Description

This command terminates a Telnet session.

Notes/Status

Location

This command is provided by the Telnet module when LOGOUT is defined in telnetdata.c.

Example

-> logout

telstats - Display Telnet statistics

telstats

telstats - Display Telnet statistics

Syntax

telstats [-c] [-g] [-s]

Parameters

-cDisplay Connection stats.
-gDisplay Global variables
-sDisplay session stats

none

Description

This command displays telnet stats. If '-c' is specified, the connection stats are displayed. If '-g' is specified, global variables are displayed, If '-s' is specified, session stats are displayed. Specifying no parameters is an error.

Notes

Location

This command is provided by the Telnet module when TELSTATS is defined in telnetdata.c

Example

-> telstats -c -g -s

telhexdump - Display the hexdump of the telnet stats structure

Name

telhexdump - Display the hexdump of the telnet stats structure

Syntax

telhexdump

Parameters

None

Description

This command displays the hexdump of the telnet stats structure.

Location

This command is provided by the Telnet module when TELHEXDUMP is defined in telnetdata.c.

Example

-> telhexdump

teldelconn - Delete telnet connection/connections

Name

teldelconn - Delete telnet connection/connections

Syntax

teldelconn -c -n -a

Parameters

-cDelete a connection
-nConnection id
-aDelete all the active connections

Description

This command deletes a connection or all active connections.

Notes

Location

This command is provided by the Telnet module when TELDELCONN is defined in telnetdata.c.

Examples

  1. To delete a specific connection:
    -> teldelconn -c -n 2
    
    Where in this example "2" is the connection id.
  2. To delete all the active connections:
    -> teldelconn -a
    

telecho - This command echoes the string.

Name

telecho - This command echoes the string.

Syntax

telecho -s STRING -n INT -a

Parameters

-sString to be echoed
-nConnection id/code>
-aSend the string to all open connections

Description

Server echoes the typed string onto the client window whose connection id is given in the command.

Location

This command is provided by the Telnet module when TELECHO is defined in telnetdata.c.

Example

telshutdown - Suspend telnet task

Name

telshutdown - Suspend telnet task

Syntax

telshutdown

Parameters

None.

Description

This command suspends telnet task. This cannot be executed from the telnet client window. This command is only valid at the console.

Location

This command is provided by the Telnet module when TELSRVSHUTDOWN is defined in telnetdata.c.

Example

-> telshutdown

telstartup - Start telnet task

Name

telstartup - Start telnet task

Syntax

telstartup

Parameters

None.

Description

This command resumes/starts telnet task. This cannot be executed from the telnet client window. This command is only valid at the console.

Location

This command is provided by the Telnet module when TELSRVSTARTUP is defined in telnetdata.c.

Example

This command is provided by the Telnet module when TELSRVSTARTUP is defined in telnetdata.c.

-> telstartup

Related Products

This product was derived from a portable, flexible and more full-featured product available from InterNiche Technologies, Inc. For more information about this SOURCE CODE PRODUCT, please visit www.iNiche.com or email Sales@iNiche.com.

For Additional Information ...