Main Page | Data Structures | File List | Data Fields | Globals

isisserver.h File Reference

ISIS server application main header. More...

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <termios.h>
#include <fcntl.h>
#include <ctype.h>

Go to the source code of this file.

Data Structures

struct  server
 ISIS server application runtime system table. More...
struct  clients
 ISIS server client table. More...
struct  serial
 ISIS server serial port table. More...
struct  udpPreset
 ISIS preset UDP socket port table. More...

Defines

#define ISIS_VERSION   "0.0"
 Version number placeholder.
#define ISIS_COMPDATE   "0000-00-00"
 Compilation date placeholder.
#define ISIS_COMPTIME   "00:00:00"
 Compilation time placeholder.
#define ISIS_CONFIG   "/lhome/dts/Config/isis.ini"
 ISIS config.
#define ISIS_DCONFIG   "/lhome/dts/Config/isisd.ini"
 isisd daemon config file
#define ISIS_LOGS   "/lhome/Logs/ISIS/isis.log"
 ISIS runtime log.
#define DEFAULT_LOCALHOST   "IS"
 Default ISIS server host ID.
#define DEFAULT_ISISPORT   0
 default ISIS server port number
#define POSIX
#define ISIS_MSGSIZE   4096
 ISIS maximum message size.
#define IMPv2_HOST_SIZE   9
 maximum size of IMPv2 host names 8+1
#define LONG_STR_SIZE   4096
 size of generic a long string
#define MED_STR_SIZE   256
 size of generic a medium-sized string
#define BIG_STR_SIZE   2048
 size of generic a big string
#define SHORT_STR_SIZE   32
 size of generic a short string
#define isis_TRUE   1
 condition is TRUE value
#define isis_FALSE   0
 condition is FALSE value
#define NUL   '\0'
 convenience definition for null string
#define ISIS_SERVER   777
 host table index for the server ("us")
#define BROADCAST   666
 host table index for broadcast (host AL)
#define MSG_NOOP   0
 No reply or forwarding required.
#define MSG_REPLY   1
 Send a reply back to the sender.
#define MSG_FORWARD   2
 Forward message to the destination.
#define MSG_ECHO   3
 Echo the message unprocessed.
#define ERR_UNKNOWN_HOST   -1
 Recipient is an unknown host.
#define ERR_UNKNOWN_FD   -2
 File descriptor is unknown to the host table.
#define ERR_HOSTS_FULL   -3
 Server's client host table is full.
#define NO_STARTUP   0
 no startup tasks required
#define COLD_START   1
 cold startup
#define WARM_START   2
 warm startup
#define UTCDATE   0
 Logs use the UTC date.
#define OBSDAY   1
 Logs use the noon-to-noon local date [Default].
#define MAXCLIENTS   32
 Maximum number of client hosts.
#define UNASSIGNED   0
 No transport method assigned to client.
#define SERIAL   1
 Client uses a serial port.
#define SOCKET   2
 Client uses a UDP network socket.
#define MAXSERIAL   8
 maximum number of serial port connections
#define MAXPRESET   8
 Maximum number of preset UDP ports.

Functions

int openSocket (int)
 Open and setup the ISIS server UDP network socket.
void closeSocket (int)
 Close the ISIS server socket.
int loadConfig (char *)
 Load/parse the server runtime configuration file.
void handShake (void)
 Handshake with the clients on serial ports and preset UDP ports.
void initHostTable ()
 Initialize the server client host table.
int updateHosts (char *, int, int, long, int)
 Update the client host table with client info.
int removeHost (char *)
 Remove an entry from the client host table.
int isKnownHost (char *)
 Verify that client is a known host (i.e., in the client table).
void printHosts (char *)
 Prints the server's client host table on stdout.
void hostInfo (char *, char *)
 Report host information to a remote client.
int initSerialPorts (void)
 Initialize the serial ports listed in the server's serial port table.
int getSerialInfo (int)
 Map a serial port file descriptor onto a serial port table index.
void portInfo (char *)
 Create a string with the server's serial port table info.
void ttyHandler (char *line)
 Handle input from the command line (readline callback function).
void socketHandler (int)
 Handle input from a network client socket.
void serialHandler (int)
 Handle input from server serial ports.
void sendMessage (int, char *)
 Send a message string to a client.
void handleMessage (int, int, char *)
 Handle messages received by the ISIS server.
void broadcastMessage (int, char *)
 Broadcast a message to all clients.
int isisCommand (char *, char *)
 Process an ISIS server command.
int serverInfo (char *)
 Report consise server status as an IMPv2-compliant message.
void printInfo (void)
 Report detailed server info on server console (stdout).
void printHelp (void)
 Print a quick summary of ISIS server commands to the console.
void initLog (void)
 Initialize the ISIS server runtime log for this session.
int logMessage (char *)
 Append an entry to the server's runtime log with date/time tagging.
void getUTCTime (void)
 Read the UTC time from the system clock.
char * getFineTime (void)
 Return the UTC time to microsecond precision.
char * getDateTime (void)
 Return the UTC date and time to microsecond precision as a system timestamp.
double sysTimeStamp (void)
 Return the elapsed time in sec since UTC 1970-01-01 with microsec precision.
char * noonDateTag (void)
 Local noon-to-noon date tag in CCYYMMDD format.
void getArg (char *, int, char *)
 Extract an argument from the command line.
void upperCase (char *)
 Convert a string to all uppercase.

Variables

server isis
 ISIS server application runtime system table.
clients clientTab [MAXCLIENTS]
 ISIS server client table.
serial ttyTab [MAXSERIAL]
 ISIS server serial port table.
udpPreset udpTab [MAXPRESET]
 ISIS preset UDP socket port table.


Detailed Description

ISIS server application main header.


Define Documentation

#define ISIS_VERSION   "0.0"
 

Version number placeholder.

#define ISIS_COMPDATE   "0000-00-00"
 

Compilation date placeholder.

#define ISIS_COMPTIME   "00:00:00"
 

Compilation time placeholder.

#define ISIS_CONFIG   "/lhome/dts/Config/isis.ini"
 

ISIS config.

#define ISIS_DCONFIG   "/lhome/dts/Config/isisd.ini"
 

isisd daemon config file

#define ISIS_LOGS   "/lhome/Logs/ISIS/isis.log"
 

ISIS runtime log.

#define DEFAULT_LOCALHOST   "IS"
 

Default ISIS server host ID.

#define DEFAULT_ISISPORT   0
 

default ISIS server port number

#define POSIX
 

#define ISIS_MSGSIZE   4096
 

ISIS maximum message size.

#define IMPv2_HOST_SIZE   9
 

maximum size of IMPv2 host names 8+1

#define LONG_STR_SIZE   4096
 

size of generic a long string

#define MED_STR_SIZE   256
 

size of generic a medium-sized string

#define BIG_STR_SIZE   2048
 

size of generic a big string

#define SHORT_STR_SIZE   32
 

size of generic a short string

#define isis_TRUE   1
 

condition is TRUE value

#define isis_FALSE   0
 

condition is FALSE value

#define NUL   '\0'
 

convenience definition for null string

#define ISIS_SERVER   777
 

host table index for the server ("us")

#define BROADCAST   666
 

host table index for broadcast (host AL)

#define MSG_NOOP   0
 

No reply or forwarding required.

#define MSG_REPLY   1
 

Send a reply back to the sender.

#define MSG_FORWARD   2
 

Forward message to the destination.

#define MSG_ECHO   3
 

Echo the message unprocessed.

#define ERR_UNKNOWN_HOST   -1
 

Recipient is an unknown host.

#define ERR_UNKNOWN_FD   -2
 

File descriptor is unknown to the host table.

#define ERR_HOSTS_FULL   -3
 

Server's client host table is full.

#define NO_STARTUP   0
 

no startup tasks required

#define COLD_START   1
 

cold startup

#define WARM_START   2
 

warm startup

#define UTCDATE   0
 

Logs use the UTC date.

#define OBSDAY   1
 

Logs use the noon-to-noon local date [Default].

#define MAXCLIENTS   32
 

Maximum number of client hosts.

#define UNASSIGNED   0
 

No transport method assigned to client.

#define SERIAL   1
 

Client uses a serial port.

#define SOCKET   2
 

Client uses a UDP network socket.

#define MAXSERIAL   8
 

maximum number of serial port connections

#define MAXPRESET   8
 

Maximum number of preset UDP ports.


Function Documentation

int openSocket int  isisPort  ) 
 

Open and setup the ISIS server UDP network socket.

Parameters:
isisPort Port number on localhost for the server socket.
Returns:
0 if successful, -1 if errors occurred.
Creates a UDP socket for the ISIS server applications and sets the file descriptor in the system table. It then binds the socket to the named port on localhost, and stores relevant information in the ISIS system table for future use without having to use thread-unsafe getxxx calls.

Errors are reported to stdout by this routine.

See also:
closeSocket()

void closeSocket int  sockFD  ) 
 

Close the ISIS server socket.

Parameters:
sockFD File descriptor of the open ISIS server socket (see openSocket())
Tears down the ISIS server socket and releases the file descriptor. Currently this is little more than a convenience wrapper for close(), but someday it might do more.

See also:
openSocket()

int loadConfig char *  cfgFile  ) 
 

Load/parse the server runtime configuration file.

Parameters:
cfgFile path/name of the server runtime configuration file.
Returns:
0 if successful, <0 on failure
Reads and parses the contents of the server's runtime configuration file, loading the parameters into the relevant internal variables.

The parameters in the runtime config file take the form of keyword/value pairs. Comments are denoted by a # and skipped by the parser. Blank lines are also ignored.

Unrecognized configuration parameters are ignored except to print a warning message for debugging purposes.

void handShake void   ) 
 

Handshake with the clients on serial ports and preset UDP ports.

Sends a ">AL PING" message to all open serial ports and all preset UDP ports. This is a blind broadcast that should lead to "PONG"s back from any ISIS clients on the serial lines or connected to the UDP socket ports.

This is a placeholder that gives us minimal IMPv2 software handshaking until we can work with the system some and work out better procedures.

All strings transmitted to raw ports must be in proper IMPv2-conformal format, terminated by \r (ASCII 13).

void initHostTable  ) 
 

Initialize the server client host table.

Initializes the contents of the ISIS client table, clearing all host entries. Must be called before filling the client table either at server startup or restart.

int updateHosts char *  hostID,
int  method,
int  fd,
long  addr,
int  port
 

Update the client host table with client info.

Parameters:
hostID new host's ID (IMPv2 format)
method new host's transport method (SERIAL, SOCKET, etc.)
fd new host's port file descriptor
addr new host's 32-bit IP address if method=SOCKET
port new host's port number if method=SOCKET
Returns:
The host table index assigned to this client if successful, or ERR_HOSTS_FULL if the host table is full.
Searches the Client Table (clientTab struct), and either adds or updates the table with the incoming host info. Because it changes the contents of global variables, this particular routine is not very thread-safe without lots of work to wrap mutex_ bits around things.

See isKnownHost() for how to test to see if a recipient is known to the system.

int removeHost char *  hostID  ) 
 

Remove an entry from the client host table.

Parameters:
hostID Name of the client host to remove
Returns:
0 if successful, or ERR_UNKNOWN_HOST if hostID was not in the table.
Removes a single host by name from the ISIS client table. See InitHostTable() for how to clear the entire table all at once.

Since the number of allowed clients is expected to remain a small number, repacking the table to remove gaps does not offer any economies at present, but someday if it is decided it is necessary, the repacking should go in this routine.

int isKnownHost char *  hostID  ) 
 

Verify that client is a known host (i.e., in the client table).

Parameters:
hostID Client host name to test
Returns:
Host table index of the recipient if valid, or HostUnknown if not.
Searches the server client table in clientTab struct, and returns the index in the host table of the named client. Called by the various message handlers attached to the select() event handler.

void printHosts char *  hostID  ) 
 

Prints the server's client host table on stdout.

Parameters:
hostID Name of the host to print. If "all", print all hosts.
Prints a table of the clients currently connected to the server onto stdout (i.e., onto the server's console window).

For output tailored for sending back to remote clients (i.e., output as an IMPv2-conformal message string), see hostInfo().

void hostInfo char *  hostID,
char *  reply
 

Report host information to a remote client.

Parameters:
hostID Name of the host of interest. If ALL, send a list of all hosts.
reply String to contain the information.
Generates an IMPv2 message string containing the info the server hass on hostID. If hostID="ALL" it will instead create a string giving a concise listing of all known hosts.

For detailed output tailored for the server's command console window (i.e., printing on stdout), see printHosts().

int initSerialPorts void   ) 
 

Initialize the serial ports listed in the server's serial port table.

Returns:
Number of serial ports opened successfully, <0 if any failed.
Initializes all of the serial ports listed in the server's serial port table (ttyTab struct, defined by entries in the runtime config file). It also attempts to close them first, allowing this function to also be used to re-initialize the ports. One failure is enough to cause an abort.

int getSerialInfo int  testFD  ) 
 

Map a serial port file descriptor onto a serial port table index.

Parameters:
testFD Serial port file descriptor to map
Returns:
The serial port table index of the test file descriptor if present, otherwise it returns ERR_UNKNOWN_FD if no match is found.
Searches for testFD in the server's active serial port table, and returns the index of the port table entry if found. The serial port table is the ttyTab struct defined in the isisserver.h header file.

void portInfo char *  replyStr  ) 
 

Create a string with the server's serial port table info.

Parameters:
replyStr String to hold the serial port table summary
Create a string with as summary of the current serial ports in IMPv2-compliant format suitable for transmission to an ISIS client.

void ttyHandler char *  ttyStr  ) 
 

Handle input from the command line (readline callback function).

Parameters:
ttyStr pointer to the text returned by readline()
This is the callback for readline() that lets our cli make use of the GNU readline and history mechanism (arrow keys and command-line editing). The callback is installed using the rl_callback_hander_install() function of the readline library.

Once we get an error-free string we can use, we then try to interpret it. This is the main cli handler for the server.

When generating IMPv2 messages for direct transmission onto the system, the strings must be terminated with return (\r = ASCII 13) not a newline (\n = ASCII 10).

void socketHandler int  sockFD  ) 
 

Handle input from a network client socket.

Parameters:
sockFD File descriptor of the server's socket.
Read a line of input from the specified network socket file descriptor, and parse the message into components (source host ID, destination host ID, and message body).

If the source and destination are valid, and the message is not blank or malformed, it then passes control off to handleMessage() to do the dirty work. This may permit us to enable multithreading in the future.

When generating IMPv2-compliant messages, the strings must be terminated with return (\r = ASCII 13) not a newline (\n = ASCII 10).

This function is designed to be invoked by a select() loop that watches particular file descriptors. See main.c for how it is implemented.

void serialHandler int  serialFD  ) 
 

Handle input from server serial ports.

Parameters:
serialFD File descriptor of the serial port with input ready.
Reads a line of input from the specified serial port file descriptor, and spits the message into components: source host ID, destination host ID, and message body (including message type).

If the source and destination are valid, and the message is not blank or malformed, it then passes the message off to HandleMessage() to route the message to its intended recipient.

When generating IMPv2 messages for direct transmission through the server, the strings must be terminated with return (\r = ASCII 13) not a newline (\n = ASCII 10).

This function is designed to be invoked by a select() loop that watches particular file descriptors. See main.c for how it is implemented.

void sendMessage int  destHost,
char *  message
 

Send a message string to a client.

Parameters:
destHost Index of the destination client host in the server's client table
message The message to send
Sends the message to a client. The message must by this point be in the form of a valid IMPv2 protocol message:
 XX>YY message_text\r 
for passing. The transport mechanism is based on the entries for destHost in the client host table. This presumes that the calling routine has already validated the destination host as valid.

The message must be properly terminated with \r (ASCII 13) as per the IMPv2 message format specification.

Designed to be lightweight and thread safe. All routines called by this (and the routine itself) must not alter global variables. this means that logging is the responsibility of calling programs upstream.

void handleMessage int  sendHost,
int  destHost,
char *  msgBody
 

Handle messages received by the ISIS server.

Parameters:
sendHost Client table index of the sending client host
destHost Client table index of the destination host
msgBody Body of the message
Figures out what to do with a message received and already validated by the calling procedure. There are three possibilities:
  1. It is an ISIS server command request to be passed to isisCommand() for processing.
  2. It is a broadcast message to be copied out to all known ISIS client hosts (passed to broadcastMessage()), as well as being processed by the server proper (passed to isisCommand()).
  3. It is a message to be routed to another client host using sendMessage().
This routine is designed to be safe for future multithreading.

IMPv2 messages are terminated with return (\r = ASCII 13), not with a newline (\n = ASCII 10). Messages prepared for further routing by sendMessage() must be correctly terminated. Those printed to stdout do not require termination, as the printing routine will strip any termination and provide a \r as required.

BEWARE: No terminination checking is done by sendMessage()!

void broadcastMessage int  sendHost,
char *  msgBody
 

Broadcast a message to all clients.

Parameters:
sendHost Client table index of the sending host
msgBody Body of the broadcast message.
Sends a broadcast message out to all known clients on the system. Broadcast messages take the form of
 XX>AL message_text\r 
If XX is the local host, we pass it to all ports in this order:
  1. to each active serial port
  2. to each active network client
If XX is one of our known clients, we pass the message along only to ports other than the one the sending client is using.

This is a key distinction: broadcasts are blind-sent to ports not hosts. We have to be careful not to echo a broadcast back to the sender, which risks starting infinite regressions.

Designed to be lightweight and thread safe. All routines called by this (and the routine itself) must not alter global variables. this means that logging is the responsibility of calling programs upstream.

int isisCommand char *  cmdStr,
char *  replyStr
 

Process an ISIS server command.

Parameters:
cmdStr String with command and arguments to process.
replyStr String to hold any reply generated by cmdStr
Returns:
MSG_REPLY if command generates a reply message to the caller MSG_NOOP if command does not require a reply or an error occurred MSG_ECHO if the entire message, including address header, is to be echoed to stdout.
The individual command actions are encapsulated in this routine, except for serverInfo() - someday we'll do this in a less hacky fashion.

int serverInfo char *  replyStr  ) 
 

Report consise server status as an IMPv2-compliant message.

Parameters:
replyStr String to contain the server status message
Returns:
MSG_REPLY (never returns an error).
Creates an IMPv2-compliant string with a summary of the current server status. Meant to be sent back as a DONE: or STATUS: type message to the client who requested the info.

void printInfo void   ) 
 

Report detailed server info on server console (stdout).

printInfo() makes a detailed, formatted report of the current server status on stdout.

For generic, concise info services, see serverInfo().

void printHelp void   ) 
 

Print a quick summary of ISIS server commands to the console.

Prints the current command list to the console intended as an aide-memoire, not a proper help utility. Don't expect much from it (besides, the command set is SMALL, that's the idea).

void initLog void   ) 
 

Initialize the ISIS server runtime log for this session.

Opens the server's runtime log. Log entries are created by the logMessage() function.

int logMessage char *  message  ) 
 

Append an entry to the server's runtime log with date/time tagging.

Parameters:
message String with the log entry to append to the log.
Returns:
0 if successful, <0 if an error occurred.
Appends the message string given into the server's runtime log, along with a date and time tag. If errors occur, messages are printed on the server's command console.

If the date tag has changed, start a new logfile for a new observing day.

Returns 0 if the logging has been disabled, making it look the same as if the log had been updated.

void getUTCTime void   ) 
 

Read the UTC time from the system clock.

Reads the system's UTC time clock and puts date/time information into the system table.

Time info is stored as follows:

  • isis.dateTag has a date tag in ccyymmdd format
  • isis.utcDate has the UTC date in ISO8601-compliant CCYY-MM-DD format
  • isis.utcTime has the UTC time in hh:mm:ss format

char* getFineTime void   ) 
 

Return the UTC time to microsecond precision.

Reads the system's UTC time clock and returns a pointer to a string with the fine-grained UTC time in hh:mm:ss.ssssss format.

Based on gf_time() from Stevens, W.R., 1998, Unix Network Programming, Vol 2, Prentice Hall, Figure 15.6, but I make a string, and restrict the output of seconds to msec rather than usec.

Of course, it may return microsecond precision, microsecond accuracy is quite another thing...

char* getDateTime void   ) 
 

Return the UTC date and time to microsecond precision as a system timestamp.

Reads the system's UTC time clock and returns a pointer to a string with the fine-grained UTC time in hh:mm:ss.ssssss format.

Based on gf_time() from Stevens, W.R., 1998, Unix Network Programming, Vol 2, Prentice Hall, Figure 15.6, but I make a string, and restrict the output of seconds to msec rather than usec.

Of course, it may return microsecond precision, microsecond accuracy is quite another thing...

double sysTimeStamp void   ) 
 

Return the elapsed time in sec since UTC 1970-01-01 with microsec precision.

Reads the system's time clock and returns a double-precision value with the time in seconds and microseconds since UTC 1970-01-01. This provides us with a fine-grained numerical timestamp for the system.

Of course, it may return microsecond precision, microsecond accuracy is quite another thing. The relative time should be as stable as PC system clocks ever are.

char* noonDateTag void   ) 
 

Local noon-to-noon date tag in CCYYMMDD format.

Convenience function for creating noon-to-noon date tags in the local time zone. If the time is after noon, it uses the current local date. If before noon, it uses *yesterday's* local date.

This convention is used for "observing day", to avoid the problem with UTC that afternoon calibrations end up in the previous night's logs, or with using local midnight where logs of a night's observing are divided between two "civil day" logs.

void getArg char *  argStr,
int  argNum,
char *  returnStr
 

Extract an argument from the command line.

Parameters:
argStr string containing the argument list
argNum number of the argument to extract
returnStr string to contain the extracted argnum-th argument
Simple command-line argument parser. Works OK, but will probably replace someday by something fancier of the need arises.

Returns a null (\0) in regarg if the argnum-th argument doesn't exist.

If any stray nulls are found in the string, it replaces them with spaces.

void upperCase char *  str  ) 
 

Convert a string to all uppercase.

Parameters:
str String to convert to uppercase
BEWARE: Changes the string being converted!


Variable Documentation

struct server isis
 

ISIS server application runtime system table.

Contains the runtime parameters of the ISIS server application.

struct clients clientTab[MAXCLIENTS]
 

ISIS server client table.

Contains the parameters of known ISIS clients. ISIS clients are added to the client table every time they pass messages through the server. This allows clients to come and go dynamically.

The maximum number of allowed clients is MAXCLIENTS.

struct serial ttyTab[MAXSERIAL]
 

ISIS server serial port table.

Contains the parameters of serial ports opened by the ISIS server. The maximum number of allowed ports opened at startup is MAXSERIAL.

struct udpPreset udpTab[MAXPRESET]
 

ISIS preset UDP socket port table.

Contains the parameters of up to MAXPRESET preset UDP socket hosts and ports. Preset UDP ports are pinged on startup and restart to re-establish connections on server restart with active clients.


Generated on Tue Apr 16 17:04:08 2013 for ISIS Server by  doxygen 1.3.9.1