# @(#)RNA 2.0 [revision A]  18 Sep 1990
#
#                 = WELCOME TO RNALIB CONFIGURATION = 
# ------------------------------------------------------------------------
# Your attention please: we strongly suggest that you read carefully
# every comment in the following lines. This configuration comes together
# with necessary documents, step by step. Skip comments at your own
# risk: you may not understand the Operator's Guide later on!
# We all hate reading long docs. This is not long, it's just the minimum
# you need to know about the program. Consider these comments as 
# part of the operator's manual. They are *not by any means 'optionals'.
# ------------------------------------------------------------------------
#
# PATH: rna looks for 'sed', 'head' and other usual unix utilities inside
# this path definition. Put here your usual paths, like..
PATH=/bin:/usr/bin:/usr/local/bin:/etc:/usr/local/etc:.
#
# Administrator's directory: this is a dedicated directory for rna. System
# files such as mail log, accounting etc. will be put here. 
# This directory will not be public, and should be closed to others 
# but  rnalib owner. This directory will not contain garbage.
# You can put the home directory of LOGNAME (see forward).
# RNADIR=/usr/rnalib
RNADIR=/usr/rnalib
#
# Temporary directory: garbage stuff is going to be put here. 
# You might choose a subdirectory of RNADIR; do not choose /tmp, you might
# get problems later on. Use a dedicated directory owned by rna.
# This folder is not going to take much space anyway.
TMPDIR=$RNADIR/tmp
#
# Temporary directory: IF you allow file compression, outgoing stuff will 
# be put here and then compressed before ship. You might choose the same
# place of TMPDIR. USE a dedicated directory, do not use /tmp.
CONVDIR=$RNADIR/convert
#
# The login used as rna entry: tipically 'rnalib'. Create this entry inside
# /etc/passwd. Home directory is not really important: the only needed thing is 
# that this user has to execute RNA and will receive query and rejected mail.
# You'll get more info on how to create this user inside OPER.GUIDE .
# By now, just pick up a name. Users will mail this name to access your
# libraries. But they could use aliases as well. Don't worry now.
# 
LOGNAME=rnalib
#
# The name of your machine, as of 'uname -n' or similar.. Hey, dont put
# another one, use the correct local machine name. Don't cheat.
# If you are under some domain include it. Ex: i2ack.SUBLINK.ORG
# 
#UNAME=host.domain
UNAME=i2ack.sublink.ORG
#
# The local postmaster, i.e. the person which will eventually solve
# remote user's problems.
# If you don't know what a Postmaster is, you are probably in the
# wrong place. Put 'root@$UNAME' and go on, this is only a reference.
# Remember to include username AND host (+ domain, if any), for instance
# venta@i2ack.SUBLINK.ORG . Postmaster need not to be on the same machine
# were RNALIB is placed! Just think of local networks...
#POSTMASTER=boss@host.domain
POSTMASTER=venta@i2ack.sublink.org
#
# When (IF) 'compress 'is used to ship files, their names are extended with
# a '.Z'. If your UNIX is a System V, maximum file name lenght is 14; if you
# are on BSD, it's 256; if you are on a Olivetti LSX it's 128 etc.
# Subtract 2 from your maximum file name lenght and fill the following 
# variable: for instance, if you have max 14 characters names, put (14-2)=12.
MAXLENGTH=12
# 
# The mail file for LOGNAME, complete path. Usually:
# /usr/spool/mail/$LOGNAME  on Xenix systems and SCO unix
# /usr/mail/$LOGNAME  on Unix System V and BSD .
MAILBOX=/usr/mail/$LOGNAME
#
# Name of the file containing all of rna logs, status etc. 
# also called "accounting"..
# Be tidy! Keep it inside RNADIR.
LOGFILE=$RNADIR/account
#
# Name of the file which is going to keep record of ALL incoming mails 
# (NOT the rejected mails...that would be stupid!). You may use this
# file as a normal mail folder for programs like 'ELM'. Remember to
# clear it out once every while ;-)
# Be tidy! Keep it inside RNADIR.
MAIL_LOG=$RNADIR/mail
#
# Name of the public directory for transfers using 'uucp' or 'uusend'.
# We suggest a '~' (which leads to /usr/spool/uucppublic) as default;
# if you are going to change this, remember that remote sites need this
# path to be writable, or your files will be rejected!
# Do also consider that some UUCP emulators - such as UFgate or Waffle -
# do *not recognize "/usr/spool/uucppublic", but *accept "~".
PUBDIR=~
#
# Debugging would occure on stdout, NOT on LOGFILE.
# 1=debug (try it for fun), nodebug= leave it EMPTY, dont put a 0
# Debug is for interactive usage only. Do not set debug mode for daemon task.
DEBUG=1
#
# Some progs never in the same place... please tell me: where is the mailer?
# I mean the one you would use as 'mail user' to send mail to user. 
# Ususally /bin/mail, though on some systems you could try /bin/rmail.
# Since RNA adds its own Subject line, be sure the mailer does not ask for it!
# If RNA messages comes without a Subject this is the reason..
MAILER=/bin/mail
#
# Where is 'uuencode'? I assume you have this utility. If you don't have this
# utility you are not likely to ship binary files via mail. 
# 
UUENCODE=/usr/local/bin/uuencode
#
# Where is 'btoa'? If you don't have it, leave it EMPTY  (nothing after the = )
# Btoa is better than uuencode: it saves some 15% space. You don't really
# need it for RNA, but if you happen to have btoa put it here. Default encoding
# still will be the good-old uuencode. Beware: i am referring to the second
# version of btoa, the one that does not need 'atob' to convert back.
# Still this version is compatible with the old release, BUT syntax to use
# is quite different. If you have an old version of btoa, no problem: find
# the RNA procedure called 'Convert_File()'; there's a 'case' inside, and
# a notice about this matter.
BTOA=/usr/local/bin/btoa
#
# Where is 'compress'? If you don't have it, leave it EMPTY 
# (nothing after the =). It sounds pretty strange to me an empty declaration
# here, since the whole world nowdays has compress. Ask for GNU-compress!
COMPRESS=/usr/local/bin/compress
#
# Where do you keep 'uucp', the usual command?
# I know everybody has one. If you don't want files travelling over
# the network with 'uucp' then omit the declaration: files will be
# travelling in ascii format via normal e-mail. 
# Caution: read Operator's Guide chapter 'Transmission layers'!
UUCP=/usr/bin/uucp
#
# Where is 'uusend'? If you don't have it, leave it EMPTY (nothing after 
# the = ). This is a common utility which replaces 'uuto' and 'uucp' on
# some old (V7) uucp based systems. 
# Caution: read Operator's Guide chapter 'Transmission layers'!
UUSEND=/usr/local/bin/uusend
#
# Where is 'file'? As you should know, this is a Berkeley utility now
# commonly distributed with almost *every serious unix system.
# 'file' examines a specified file and gives informations about it.
# Since RNA has to figure out by itself whether or not requested files
# are ASCII or BINARY, we definitively *need* the berklish 'file'.
# So know, com'on..
BKFILE=/bin/file
#
# Where is 'strings' ? we use it just a couple of times, to grep out
# blank lines from 'pathsize' (you'll learn about it later on).
# This command is pretty standard, however my 3B2 with Unix 3.2 is
# missing it (*sic)! I wrote a small 'strings.c' which you might
# compile and use in case there's no 'strings' on your system.
STRINGS=/usr/local/bin/strings
# 
# This is important (;-)). RNA needs an index file containing libraries'
# names along with their real paths. Since you are installing RNA for
# something, i assume you HAVE at least one 'library', don't you?
# With RNA distribution comes a file named 'libindex' which contains
# some more docs about its structure. "libindex" is my suggested name for..
# [ NOTE: inside OPER.GUIDE we always refer to this suggested name. ]
LIBIND=$RNADIR/libindex
#
# This file contains names/paths which are not allowed to use RNA.
# With RNA distribution comes a file named 'black' which contains some
# more docs about its structure. "black" is my suggested name for..
# [ NOTE: inside OPER.GUIDE we always refer to this suggested name. ]
BLACKLIST=$RNADIR/black
#
# This file contains names/paths which are authorized to forward RNA requests
# for others, i.e.: send files to other people. Normally RNA sends back to
# the original user/system who sent the mail.
# With RNA distribution comes a file named 'white' which contains some
# more docs about its structure. "white" is my suggested name for..
# [ NOTE: inside OPER.GUIDE we always refer to this suggested name. ]
WHITELIST=$RNADIR/white
#
# If something goes wrong with the mail, RNA will receive back its stuff
# from somewhere. Of course this is a dangerous situation, so RNA will
# recognize and skip this mail. A copy will be put inside..
# [ NOTE: inside OPER.GUIDE we always refer to this suggested name. ]
REJECTED=$RNADIR/rejected
#
#
# You may choose to limit rna activities within certain paths to
# a definite amount of bytes transmitted. For instance, you would
# like to keep an host under control: if that host asks for more than
# -say- 300.000 bytes, any further request should be denied. This is
# called 'pathsizing'. RNA will check that any request coming from somewhere
# has 'credits' before accepting its query; afterwards, its credits will be
# updated. Following variable contains the name of the file which is going
# to keep paths&credits notes. 
# If you don't care about 'pathsizing', leave it blank.
# [ NOTE: inside OPER.GUIDE we always refer to this suggested name. ]
PATHSIZE=$RNADIR/pathsize
#
# (Needed only if you chose pathsizing above) 
# If a path is not appearing inside pathsize, by default a no-limit credit
# is given. You may want RNA to automatically add any new path to its
# pathsize, with a default credit given. So...
# Put a  0   if you want that new sites ask to be registered before being
#            authorized to use your RNA service. Any new path will be notified
#            that a membership is required in order to use your service.
# Put a size in bytes -say 200000 (do not put any fullstops!)- as default
#            credit limit for any new path. 'pathsize' will be updated with
#            this new path and this number.
# Leave it BLANK if you don't want to limit new paths. This way only paths
#            already included inside 'pathsize' will be affected by pathsizing.
# More info inside RNA Operator's Guide, chapter 'Pathsizing'.
CREDIT=300000
#
# You are done. No more variables to configure. You need to check for
# RNADIR TMPDIR CONVDIR and (if not '~') PUBDIR existance; remind!
# NOW search forward for ' %%FIX%% ' : these are entry points for
# possible configuration-dependent problems. Do check every %%FIX%%
# and be sure everything is ok. The last %%FIX%% has some more 
# informations for you. Do carefully follow %%FIX%% (again) until
# the last one (it tell's you that you got to the final fix, don't
# worry). Happy 'tuning'!
# 
# ==============================================================
#
# Internal tmp files.
# -------------------
MBOX_COPY=$TMPDIR/tmp
MBOX_CUT=$TMPDIR/cut
CMDS=$TMPDIR/tmpcmds
CMDLOG=$TMPDIR/commlog
POINTERS=$TMPDIR/punt
ERRSTAT=$TMPDIR/err
OUTFILE=$TMPDIR/outfile
UUCP_ADDRESS=$TMPDIR/address
# -------------------- some procedures... ----

# %%FIX%%
GetMail() {
#	This function does three things; 1st) moves rnalib mailbox into
#	a temporary file. 2nd) creates back a new empty rnalib mailbox
#	3rd) archives the temporary files inside another mailbox file.
#	You might need to fix JUST the 2ND thing..
	rm $MBOX_COPY 2>/dev/null
	mv $MAILBOX $MBOX_COPY
#	.. here it is: we CREATE BACK THE ORIGINAL MAILBOX, for instance
#	/usr/spool/mail/rnalib   or  /usr/mail/rnalib  or whatever.
#	A simple 'touch $MAILBOX' could do; HOWEVER be *very *sure that
#	the new mailbox has the right owner/group permissions once created.
#	This is all you need: a regular empty folder, just like a normal one.
#	Here are some suggestions:
#	'>$MAILBOX'    (easy to start with)
#	'touch $MAILBOX; chown $LOGNAME $MAILBOX; chgrp mail $MAILBOX;
#	 chmod 620 $MAILBOX'   etc. Watch out for that 620, you might need
#	to change it; just an example!
#	Don't panic and carefully fix the following line:
#
	touch $MAILBOX; chown $LOGNAME $MAILBOX; chgrp mail $MAILBOX; chmod 666 $MAILBOX
#
#	That's all. Leave the rest as-it-is. Go on for the next fix..	
	touch $MAIL_LOG; echo "`cat $MBOX_COPY`\n" >>$MAIL_LOG 
}

Startup() {
	touch $LOGFILE
	message=1
}

ClrTmpFiles() {
	rm -f $CMDLOG 2>/dev/null; touch $CMDLOG
	rm -f $ERRSTAT 2>/dev/null; touch $ERRSTAT
	rm -f $CMDS 2>/dev/null
	rm -f $CONVDIR/*.Z 2>/dev/null
	rm -f $UUCP_ADDRESS 2>/dev/null; touch $UUCP_ADDRESS
	rm -f $OUTFILE 2>/dev/null; touch $OUTFILE
	ARPA_SENDER=""; UUCP_SENDER=""; REQUEST_DATE=""; UUCP_HOST=""
	UUCP_DESTIN=""
}

CutMail() {
NotTheFirst=0
rm -f $POINTERS 2>/dev/null; touch $POINTERS

grep -n '^From ' $MBOX_COPY | PrintSumm
set `cat $MBOX_COPY | wc -l`; echo $1 >>$POINTERS
}

PrintSumm()
{
    IFSorg=$IFS
    while read Linea
    do
	IFS=$IFSorg
	set $Linea

# %%FIX%%
# 	This is a VERY IMPORTANT FIX- watch out!
#	Question: how many fields has the very first 'From' line of a
#	          mail message on YOUR system? 
#	To answer, do a shell escape from your editor NOW and mail yourself
#	a message. Then edit your mailbox, and examine the first From, the
#	one WITHOUT colons. Here's mine, for instance:
#       From deejay!gear!marlor Wed Feb 21 12:32:44 1990
#	 1            2          3   4  5     6       7
#	So i know my mailer adds a 7-field From header.
#	Your mailer could add a timezone as well, and you would get 8 fields.
#	RNA does not trust by default any (apparently) valid header.
#	We extract the beginning of a mail inside our mailbox looking for
#	a 'From '(note the space) standing on a 7 (or whatever) fields line.
#	[ELM 2.2 just looks for a From with a space and more than 2 fields]
#	Replace the following number with the one you need:

	if [ $# = 7 ]
	then
	    IFS=":$IFSorg"
	    set $Linea
	    NumDiLinea=$1
	    if [ $NotTheFirst != 0 ]
	    then
		echo "`expr $NumDiLinea - 2`" >>$POINTERS
	    fi
	    echo "$NumDiLinea \c" >>$POINTERS
	    NotTheFirst=1
	fi
    done

    IFS=$IFSorg
}

Cut_Address() {
	echo "$UUCP_SENDER" >> $UUCP_ADDRESS
if [ "$destination" != "DEFAULT" ]; then
	set `sed -e "s/@/@ /" $UUCP_ADDRESS`; UUCP_HOST=$2"!"
else
	set `sed -e "s/[A-Za-z0-9]*$//g" $UUCP_ADDRESS`; UUCP_HOST=$1
fi
}

GetMessage() {
	set `sed -n "$1 l" $POINTERS`
	sed -n "$1,$2 l" $MBOX_COPY  >$MBOX_CUT
}

GetDir()
# this function gets a library name and returns its related path.
# If library does not exist, nothing is returned. An argument is
# expected. Lines containing " # " in $LIBIND are simply skipped.
{
search=$1
set -f `grep -v '^#' $LIBIND`
while [ "$1" != "" ]
do
	test "$1" = "$search" && shift && echo $1 && break
	shift
done
}


StripPermAndLink()
{
    while read line
    do
	set -- $line
	echo "$3\t$4,$5\t$6\t$7"
    done
}


FileType()
# Arg: file_path  (full)
# Returns: null if file is ASCII-TEXT; output of "file" command if not.
{
filename=$1; IFSorg=$IFS
IFS=":"; set `echo "dummy"; $BKFILE $filename | grep -v text`; IFS=$IFSorg
test -n "$2" && echo $2
}



GetFile()
# Parameters: static $argument $from
# Returns:  path_to_file; null if file does not exist
{
GFpath=`GetDir $from`
if [ "$GFpath" != "" ]; then
	test -r $GFpath/$argument && echo $GFpath/$argument 
fi	
}

ListLib()
# Parameters: library
{
LLlib=$1
LLpath=`GetDir $LLlib`
echo "\nList of files inside \c"

if [ "$LLlib" = "DEFAULT" ]; then
	echo "RNA system library:";
else
	echo "\"$LLlib\" library:\n"
fi

if [ "$LLpath" = "" ] 
then
	NoLibrary_Msg
else
	ls -got $LLpath | StripPermAndLink
fi
}

FindFile()
# Parameters: characters to match in searched file
# Returns: matching libraries and files, if any
{
FFchars=$1; FFmatch=
echo "\nREQUEST: search for file names containing <$FFchars>."
echo "         Look inside all available libraries, and\n\
         try  both  lower/upper case combinations.\n"
echo "=====================================================\n"
set -f `grep -v '#' $LIBIND`
while [ "$1" != "" ]
do
	FFlib=$1; FFpath=$2;
# %%FIX%%
# On Unix V.3.2 (?) like the one from SCO, the 3B2 etc., grep's family
# commands follow Posix. Posix suppressed '-y' and added '-i'.
# Jesus, all we want is a non-case sensitive grep! If you run sco-xenix 386,
# 'grep -y' should work. If you are on SCO-unix, 'fgrep -y' will.
# Generally, 'fgrep -i' is a good chance (3B2 Unix 3.2)
# Have a look at your grep/fgrep and pick up the right one. Change the
# following line, if needed..................++++++++
	ls -got $FFpath | StripPermAndLink | fgrep -i $FFchars && {
		echo "\nfound inside library: \"$FFlib\""
		echo "\n=====================================================\n"
		FFmatch=ok
		}
	shift; shift
done
test -z "$FFmatch" && {
	echo "\tNo matching files found - sorry"
	echo "\n=====================================================\n"
	}

}

Cut_Ls()
# %%FIX%%
# We need to grep out of 'ls -log' the bytes number. Since the output
# of that 'ls' is:   -rwxr-xr-x   1   33275 Feb  8 12:25 RNA
# we use 'cut' (a common text utility) to pick up the right field.
# On my system it came out from the 15th to 23th characters. Check yours too,
# and find the right "-cn-n" (n=number) which extracts bytes. Good luck.
# (Don't panic: on sco xenix386, sco unix, olivetti lsx, hp-ux and at&t 3b2
#  the 15-23 was fine. Probably it's ok for your site also)
#
{
cut -c15-23
}

GetCat()
{
libr=$1
if [ "`GetDir $libr`" = "" ]; then
	NoLibrary_Msg
else
	file="`GetDir $libr`/INDEX"
	test -r $file && echo "\n`cat $file`" || echo "\n\
No index available for \"$1\" library, sorry.\n\
Here comes a list of contents..."
fi
}

BlackList()
# Gets internal uucp-from path and checks if it's blacklisted.
# Returns: blacklist matching, or nothing at all.
{
set -f `grep -v '#' $BLACKLIST`
while [ "$1" != "" ]
do
	test -n "`echo $UUCP_SENDER | grep $1`" && {
	echo "<$1> is matched inside <$UUCP_SENDER>" && break; }
	shift
done
}

ToCheck()
# checks if sender is authorized to use "To" or not.
# returns a string if it's ok, nothing if not.
{
set -f `grep -v '#' $WHITELIST`
#while test -n "$1"
while [ "$1" != "" ]
do
	test -n "`echo $UUCP_SENDER | grep $1`" && {
	echo "<$1> is matched inside <$UUCP_SENDER>" && break; }
	shift
done
}

With_Type() 
{
encode_type="none"; compress_type="none" 
case $with in 
	compr|Compr|COMPR|\
	compress|COMPRESS|Compress)
		encode_type="uuencode"
		compress_type="compress" 
		;;

	compr-btoa|Compr-Btoa|COMPR-BTOA|\
	compress-btoa|COMPRESS-BTOA|\
	Compress-Btoa)
		encode_type="btoa"
		compress_type="compress" 
		;;
	
	compr-uuenc|Compr-Uuenc|COMPR-UUENC|\
	compress-uuencode|COMPRESS-UUENCODE|\
	compress-encode|COMPRESS-ENCODE|\
	Compress-Uuencode|Compress-Encode)
		encode_type="uuencode"
		compress_type="compress" 
		;;

	DEFAULT|UUENCODE|ENCODE|\
	uuencode|encode|ascii|\
	Uuencode|Encode|ASCII)
		encode_type="uuencode"
		compress_type="none"
		;;

	BTOA|btoa|Btoa)	
        	encode_type="btoa"
		compress_type="none"
		;;

#	%%FIX%%
#	The sender used a strange "with" field; a default behaviour
#	follows. Put 'reject' as encode_type if you do not want any mailing
#	whenever there's an invalid 'with'. 
#	Currently this error is ignored (with a warning) and the stuff is
#	shipped all the same using uuencode.
#	This is just to let you know you can do it. No need to touch it
#	for a normal usage.

	*)	
        	encode_type="uuencode"
		compress_type="none"
		WithError_Msg >>$OUTFILE
		NeedHelp_Msg >>$OUTFILE
		;;
esac

if [ "$compress_type" != "none" ]; then
set `echo $argument | wc -c`; length=`expr $1 - 1`
    if [ "$length" -gt "$MAXLENGTH" ]; then
	NoSuffix_Msg >> $OUTFILE
	echo "\
Subject: WARNING, file name too long for RNA compress\n\n\
	Please rename file: \"$fname\" if possible.\n\
	Its name is longer than \"$MAXLENGTH\" characters and\n\
	RNA users can't ask for \"$COMPRESS\" shippings.\n\n\
	                      Your friendly RNALIB DAEMON\n" | $MAILER $POSTMASTER 
	return
    else
	FCPRNAME=$CONVDIR/$argument".Z"
	argument=$argument".Z"
    fi
#	Check if 'compress' is available.
	test $COMPRESS || { NoCompr_Msg >> $OUTFILE; return; } && $COMPRESS -c $fname > $FCPRNAME
	test -s $FCPRNAME || { Already_Msg >> $OUTFILE; return; } && fname=$FCPRNAME 
	Compr_Msg >>$OUTFILE
fi

}

Convert_File()
{
ftype=""; ftype="`FileType $fname`"

if [ "$viasped" != "NO_MAIL" ]; then

# Did the sender request a special "with" for a simple ASCII file?
# If so, we reject his request and ship the file as-it-is.
test $with != "DEFAULT"  && test "$ftype" = ""  && NoNeed_Msg >>$OUTFILE 

if [ "$ftype" = "" ]; then
encode_type="none"
fi

# If user asked for btoa encoding, see if btoa is available.
# If btoa is not available we WON'T use uuencode; i suppose the sender had 
# some reasons to choose btoa...
if [ "$encode_type" = "btoa" ]; then
	test $BTOA || { NoBtoa_Msg >>$OUTFILE; return; } && Convert_Msg >>$OUTFILE
fi
# The following 'fi' refers to 'viasped != no_mail'.
fi

test "$encode_type" = "uuencode" && test "$viasped" != "NO_MAIL" && Convert_Msg >>$OUTFILE

# We are about to ship the stuff; let's see if the destination address is 
# different from the sender. If so, it's an authorized "external request"
# and we want to notify the destination about it. 
# Beware of 'reject' encode_type: we want to be sure that the stuff is sent
# to the external destination only, in this case. Error announcements HAVE
# to go to the original sender (what a mess!).
if [ "$encode_type" != "reject" ]; then
	if [ "$destination" != "DEFAULT" ]; then
		echo "\n\
Note: this is an external request forwarded by $ARPA_SENDER for you.\n\
      Original mail path is: <$UUCP_SENDER> .\n\
		     " >>$OUTFILE
	fi
fi

test "$viasped" != "NO_MAIL" &&
	echo "\n-rnalib---------------------- cut here for \"$argument\" ------------" >>$OUTFILE

case $encode_type in

#	syntax: uuencode path/file internal_filename
	uuencode)
		if [ "$viasped" = "NO_MAIL" ]; then
			NoConv_Msg >> $OUTFILE
		else
			$UUENCODE $fname $argument >>$OUTFILE
		fi ;;

#	%%FIX%%
#	Syntax: btoa path/file -- warning: using old versions of btoa requires
#	'cat $fname | btoa >>$OUTFILE' or something like. Get the new release!
	btoa)
		if [ "$viasped" = "NO_MAIL" ]; then
			NoConv_Msg >> $OUTFILE
		else
			$BTOA $fname >>$OUTFILE
		fi ;;

#	encode_type equals "none" only if file is not binary, or if it
#	going to be shipped with uusend or uucp (if available)
	none)
		if [ "$viasped" = "NO_MAIL" ]; then
			NoConv_Msg >> $OUTFILE
		else
			cat $fname >>$OUTFILE
		fi ;;

#	Configuration choice: if $with is not a valid argument don't ship
#	the binary encoding with "uuencode"; notify the sender, though.
	reject) echo "\nPlease re-submit your request with proper parameter\n" >>$OUTFILE;;
	
	*) echo "\nRNA INTERNAL ERROR inside procedure Convert_File\n" >>$OUTFILE
	echo "WARNING: convert internal error (notified to operator)" >>$LOGFILE
	test $DEBUG && echo "Internal error: encode_type=$encode_type";;

esac

test "$viasped" != "NO_MAIL" &&
	echo "\n-rnalib----------------------- end of file \"$argument\" ------------" >>$OUTFILE

#	Be *very sure we are not shipping errors to an external destination!
if [ "$encode_type" != "reject" ]; then
	if [ "$destination" != "DEFAULT" ]; then

#		change destination...and good luck for delivery!

		UUCP_SENDER=$destination	
		ARPA_SENDER=$destination
	fi
	echo "Sent < $argument from $from - via $via > to $ARPA_SENDER" >>$LOGFILE
fi
       
}


Mail_File()
{
test $DEBUG && echo "Now mailing: $UUCP_SENDER"
Signature >>$OUTFILE
# %%FIX%%
# If you trust or need domain addressing, then change $UUCP_SENDER
# with $ARPA_SENDER. Think about this twice; let the bang routing
# unless you *know *what *you *are *doing. 
# This won't work with external destinations, of course.
# If mail header did not contain an rfc822 arpa address then
# don't worry: arpa_sender will just be a copy of uucp_sender.
cat $OUTFILE | $MAILER $UUCP_SENDER
# We need to grep out of 'ls -log' the bytes number. 
set `ls -log $OUTFILE | Cut_Ls`
echo "Reply of $1 bytes sent to: $UUCP_SENDER" >>$LOGFILE
#
test -n "$PATHSIZE" && Bill $OUTFILE
rm -f $OUTFILE 2>/dev/null; touch $OUTFILE
}


Check_PathSize()
# $1 = path/user to check
# returns: null if unknown path; otherwise current credit size.
{
ps_origin=$1
# Warning: file 'pathsize' in this version of RNA needs a dummy line
# like ' user 0 '  or 'user@host 0' for the *very *first user update.
# In other words, if you are applying pathsizing, your 'pathsize'
# has to contain a first line to work on. Pathsize cannot be empty!
# Technically, what happens is that shell gets angry since it
# cannot shift 'ps_credit'. This will be fixed in future versions.
set -f `grep -v '#' $PATHSIZE`
while [ "$1" != "" ]; do
	ps_path=$1; ps_credit=$2; shift; shift
 	test -n "`echo $ps_origin | grep $ps_path`" && echo $ps_credit && break
done
}


Add_PathSize()
# It's named 'Add', but really it subtracts sizes! 
# $1 = path/user to update; $2 = umount to subtract
{
ps_origin=$1; ps_size=$2;
# strip comments, as usual
set -f `grep -v '#' $PATHSIZE`
while [ "$1" != "" ]; do
	ps_path=$1; ps_credit=$2; shift; shift
#	Is this path matching the one we are checking?
 	test -n "`echo $ps_origin | grep $ps_path`" && {
#		Yep. Let's calculate the new credit, and...
 		ps_size=`expr $ps_credit - $ps_size`
#		..update the pathsize database. Ugly 'ed' script!
		ed - pathsize >/dev/null <<OoPs
			/$ps_path.*$ps_credit/
			s/\(.*\) \(.*\)/\1 $ps_size/
			w
			q
OoPs
#		All done; get back!
		return
 	}
done
# This path does not exist inside our pathsize database. Uhm..
# If CREDIT is defined, we add the new path to our database. We assume
# that CREDIT is not '0': a previous check on this value would have
# rejected any request and we wouldn't be here. So either 'credit' has
# a value different from zero, or it is not defined at all. Trust me!
test -n "$CREDIT" && {
	ps_size=`expr $CREDIT - $ps_size`
	echo "$ps_origin $ps_size" >>$PATHSIZE
	}
}

Bill() {

if [ "$credit" != "UNLIMITED" ]; then

# bill destination of $1 lenght
	( set `ls -log $1 | Cut_Ls`
	Add_PathSize $UUCP_SENDER $1
	)
fi
}


#
# RNA 2.0 MESSAGES - Warning: change at your own risk!
#

Headers_Msg()
{
# DON'T CHANGE the 'X-Mailer' line by *any means. Future versions of
# RNA will talk to each other (sort-of networking!) and will need
# to know exactly which version is on the other side.
spedresult=`Reference_Cmd`
echo "\
X-Mailer: RNALIB 2.0 [Rev.A]\n\
X-Sender: $ARPA_SENDER\n\
Subject: RNA answer: $spedresult"

test -s $RNADIR/notice && cat $RNADIR/notice 
}

NoHuman_Msg()
{
echo "\
This message has been generated by a program. To talk to a human,\n\
send mail to $POSTMASTER. Special requests of details on\n\
RNA delivers may be submitted to this address only."
}

Example_Msg()
{
echo "\
Here are some example requests, in case syntax is the problem:\n\
\n\
	@@ help\n\
	@@ index\n\
	@@ index {library}\n\
	@@ list {library}\n\
	@@ find {filename}\n\
	@@ credits\n\
	@@ send {file} from {library}\n\
	@@ send {file} from {library} with {compress-uuencode}\n\
	@@ send {file} from {library} with {btoa} via {uucp}\n\
	@@ send {file} from {library} with {uuencode} via {uusend}\n\
etc.etc."
}

NeedHelp_Msg()
{
echo "\
If you need help on RNA commands syntax, a doc file is available\n\
here. You might get it by mailing  $LOGNAME@$UNAME , with either\n\
message body or Subject containing:  @@ help."
}

NoFile_Msg()
# $1=LIBRARY  $2=FILE-NAME
{
if [ "$1" != "DEFAULT" ]; then 
	echo "\n\
Sorry, no such file was found. Recheck library contents.\n\
To do that, use the RNAlib command:   @@ list $1\n\
For a verbose description of files use:   @@ index $1" 
else
	echo "\
Sorry no such file was found inside RNALIB system directory.\n\
Please recheck library contents with :   @@ list\n\
For a list of available libraries and description of \n\
available system files try: @@ index " 
fi
echo "\n\
You may also scan the whole library system looking for a particular\n\
file-name or part of it; use: @@ find {chars}. Example: @@ find doc\n\
would list all available files whose names contain \"doc\". \n\
If you insist on this file-name, then try: @@ find $2  \n\
If all of this doesn't explain the problem, send a complaint\n\
to postmaster here: $POSTMASTER"
}

NoLibrary_Msg()
{
echo "\
Sorry, this library does not exist! Recheck the general index.\n\
To do that, try the RNA command: @@ index \n\
If that doesn't explain the problem, send a complaint\n\
to: $POSTMASTER"
}

CantAccess_Msg()
{
echo "\
Sorry, i could not read \"$argument\" inside selected library : \n\
there might be local problems with fileystem permissions here.\n\
Try contacting the postmaster for some explanations."
}

YourMail_Msg()
{
echo "\nYour mail, as received here, was...\n\
--------------------------------------------"
cat -v $MBOX_CUT
echo "\n--------------------------------------------"
}

Syntax_Msg()
{
echo "\
Sorry, the RNAlib program could not understand your request.\n"
NeedHelp_Msg
echo; Example_Msg; echo; YourMail_Msg
}

BadChars_Msg()
{
echo "\
Your request included shell magic characters inside $1 command line(s).\n\
Such characters like \*, | , / , dots etc. are PROHIBITED for security\n\
reasons: the whole message has been discarded for this reason."
}

NoCommands_Msg()
{
echo "\
RNAlib could not find any command-lines inside your mail-request.\n"
NeedHelp_Msg
echo; Example_Msg; echo; YourMail_Msg
}

NoTo_Msg()
{
echo "\
Sorry, you are not authorized to use the \"TO\" field inside RNA requests.\n\
Special permissions should be submitted to $POSTMASTER, along with\n\
some good reasons for such capability."
}

BlackListed_Msg()
{
echo "\
Sorry, you cannot forward RNALIB-requests here: your site is off-limits.\n\
There's also a chance that your site is placed on a blacklisted path,\n\
and though rejected;  it could also be that your address and/or name\n\
just looks exactly as a blacklisted one."
}

Deliver_Msg()
{
echo "\
This is the RNALIB output for a request destinated to you.\n\
Enquiry was sent on $REQUEST_DATE  by <$ARPA_SENDER>."
}


Reference_Cmd()
{
test -z "$action" && echo "problems." && exit
echo "\"$action\c"
test "$argument" != "DEFAULT" && echo " $argument\c"
test "$from" != "DEFAULT" && echo " [from] $from\c"
test "$destination" != "DEFAULT" && echo " [to] $destination\c"
test "$with" != "DEFAULT" && echo " [with] $with\c"
test "$via" != "DEFAULT" && echo " [via] $via\c"
echo "\"\n"
}	

Reference_Msg()
{
echo "Command referenced: `Reference_Cmd`" 
}

Convert_Msg()
{
echo "\
This file appears to be a $ftype:\n\
it has been transformed into an ASCII-format using \"$encode_type\".\n\
"
}

NoNeed_Msg()
{
echo "\
Field \"with\" ignored: file is already ASCII-text."
}

NoSuffix_Msg()
{
echo "\
WARNING: requested file \"$fname\"\n\
         has NOT been compressed since its longer than \"$MAXLENGHT\"\n\
         characters permitted by \"$COMPRESS\". The problem has been\n\
         notified to $POSTMASTER here. Sorry for the inconvenience.\n\
"
}

NoConv_Msg()
{
echo "\
Field \"with\" ignored: file hasn't been converted since\n\
it comes via \"$via\".\n\
"
}

Compr_Msg()
{
echo "\
This file has been converted with utility \"$COMPRESS\"\n\
You need to convert it back with something like \"uncompress\"\n\
or \"compress -d\".\n\
"
}

Ship_Msg()
{
echo "\
File requested for \"$ARPA_SENDER\" and destinated to \"$UUCP_HOST\"\n\
is coming inside your system public directory via \"$via\".\n\
Check it out! It should already be there.\n\
"
}

NoCompr_Msg()
{
echo "\
WARNING: \"compress\" is not available here!\n\
Your file has been sent without any compression. Sorry.\n\
"
}

Already_Msg()
{
echo "\n\
This file hasn't been compressed since it ALREADY was compressed!\n\
Any file whose name terminates with a \".Z\" is compressed: take care!\n\
You can get a list of file names inside a specific library\n\
with RNA command \"list library\".\n\
"
}

ViaError_Msg()
{
echo "\
Warning! Field \"with\" ignored: <$with> is not a valid identifier.\n\
This file has been sent via normal \"e-mail\".\n\
"
}

Pending_Msg() {
echo "\
X-Mailer: RNALIB 2.0 [Rev.A]\n\
Subject: RNA is out of service on $UNAME\n\n\
Hello. RNALIB on $UNAME is temporarily out of service.\n\
Your request of $REQUEST_DATE has been queued and will be processed\n\
as soon as the service is resumed.\n\n\
`cat $RNADIR/hold`\n\n
`Signature`"
}

WithError_Msg()
{
echo "\
Warning! Field \"with\" ignored: <$with> is not a valid identifier.\n\
This file has been transformed into an ASCII-format using \"uuencode\"."
}

NoBtoa_Msg()
{
echo "\n\
WARNING: \"btoa\" translation is not available here!\n\
Please re-submit your request without further \"with\" field;\n\
non-ascii files will be treated with \"uuencode\"."
}

Signature()
{
echo "\n\
--\n\
|RNALIB|SERVER|  | running at: \"$UNAME\"\n\
|rnalib|server|  | postmaster: $POSTMASTER"
}

NoCredit_Msg() {
	echo "\
X-Mailer: RNALIB 2.0 [Rev.A]\n\
Subject: your path is out of RNA credits\n\n\
The mail path you are coming from has exceeded its transmission's limits.\n\
In order to keep network trafic under control, we fix a credit size for\n\
certain paths: currently your site results to be out of credits.\n\
You may ask $POSTMASTER for a credit reset; until then, all\n\
rnalib queries from your path are ignored.\n\
You may in the future ask rnalib which is the current credit size which\n\
applies to your path, using: \"@@ credits\".\n"
YourMail_Msg
NoHuman_Msg
Signature	
}

SubScribe_Msg() {
	echo "\
X-Mailer: RNALIB 2.0 [Rev.A]\n\
Subject: Please subscribe for rnalib service\n\n\
Hello.\n\
RNALIB service here on $UNAME requires a subscription to the \n\
authorized user's list.\n\
Please mail $POSTMASTER asking for registration before any further query.\n\
        Thank You\n"
YourMail_Msg
NoHuman_Msg
Signature
}

# End of messages- 

parse() {
echo "\n`date '+%d.%m.%y - %H:%M:%S'`" >>$LOGFILE
test $DEBUG && echo "Parsing message.."
# Watch out for rejected mails! Don't waste time..

rejected=""; grep "X-Mailer: RNALIB" $MBOX_CUT >/dev/null && rejected=1; 
if [ "$rejected" = "1" ]; then
	test $DEBUG && echo "Skip this mail: it was rejected from remote"
	echo "\n`cat $MBOX_CUT`" >>$REJECTED

	echo "Priority: all\nSubject: RNA delivery rejected\n\n\
An RNA delivery was rejected from remote. A copy of the following\n\
diagnostic has been archived inside $REJECTED as usual.\n\
Here comes the stuff i received....\n\n\
`cat $MBOX_CUT`\n\n   Your friendly RNALIB DAEMON" | $MAILER $POSTMASTER

	return
fi

# get the first From path for a (un)trustable bang-reply ;-)
set `head -1 $MBOX_CUT`; UUCP_SENDER=$2
echo "Request received from: $UUCP_SENDER" >>$LOGFILE
# get the ARPA address of the sender. A real hack upon rfc822..
set `wc -l $MBOX_CUT`; end=$1; rline=2
until [ "$rline" = "$end" ]
do
	rrline=`sed -n "$rline l" $MBOX_CUT`
	test -z "$rrline" && rline=$end && break
	set -f $rrline
	if [ "$1" = "From:" ]; then
#		Here we are, trying to fit the (in)famous rfc822.
#		Rule of dumb: if only one field, it's it.	
		if [ "$#" = "2" ]; then
			ARPA_SENDER=$2
#			Retry: if one of the fields contains "<>", it's it.
#			We just check for the open '<'; we won't consider
#			drunk mailers. We also assume that <address> is the
#			last field on the line.
		elif [ "`echo $@ | grep '<'" != "" ]; then 
			IFSorg=$IFS; IFS="<>"	
			set $@; ARPA_SENDER=$2;
		elif [ "`echo $@ | grep '('" != "" ]; then 
#			Back on: if one of the fields contains "()", the other 
#			is the good one. We assume that (Full Name) is the last
#			field on the line.
			IFSorg=$IFS; IFS="( )"
			set $@; ARPA_SENDER=$2
		fi
#		If this is not enough, you'll have to find out yourself
#		the way to get arpa-addresses on your site. Send a copy of
#		the object header to me, so that i'll add that
#		specification for the next rna release.
		IFS=$IFSorg
	fi	
	test "$1" = "Date:" && REQUEST_DATE="$2 $3 $4"	
	rline=`expr $rline + 1`
done	
test -z "$ARPA_SENDER" && ARPA_SENDER=$UUCP_SENDER
test -z "$REQUEST_DATE" && REQUEST_DATE="(unknown date)"

test $DEBUG && echo "UUCP incoming address: $UUCP_SENDER"
test $DEBUG && echo "ARPA incoming address: $ARPA_SENDER"
test $DEBUG && echo "date of original mail: $REQUEST_DATE"

# Now we know everything we need about our incoming message.
# Let's see if the rna service is on hold for some reason...
test -r $RNADIR/hold && {
# ..yep. We touch and fill 'pending'. An empty 'pending' should *never
# exist. Rna at startup would claim there are pending jobs.
	touch $RNADIR/pending; echo "`cat $MBOX_CUT`\n" >>$RNADIR/pending
	Pending_Msg | $MAILER $UUCP_SENDER
	return
}


# get command lines from the message (if any)
grep '@@' $MBOX_CUT >$CMDS

# Some pre-parsing for naughty characters.. If security problems are
# detected inside command lines belonging to the same message, the WHOLE
# message is rejected. We never know what these hackers can try nowadays ;-)
# BEWARE: what we do is searching with egrep for these characters:
#		* | ? " . /  '
# I gave up trying to grep also:   `  and \  (egrep gives errors).
# Using these characters, though, gives no results from the "hacker's point
# of view". So the stuff should be quite secure right now.
# %%FIX%%
# We use 'egrep' here. If you don't have a 'egrep' try using the normal
# 'grep' with some hacks. The aim is to fit the 'if' condition whenever
# magic characters are detected inside command lines.
# If you can't come to anything working, then replace the following line
# with 'error=0' and watch out for enemies on the net!
error=`egrep -c "\*|\||\?|\"|/|\'" $CMDS`
if [ "$error" != "0" ]; then
	test $DEBUG && echo "WARNING: security problems, mail rejected"
	echo "SECURITY problems with $ARPA_SENDER" >>$LOGFILE
	BadChars_Msg $error >$ERRSTAT
#	We need this so the interpreter will stop arguing about external dest.
	destination=DEFAULT
	return
fi

if test -s $CMDS; then
	set `wc -l $CMDS`; cmds=$1
	test $DEBUG && echo "this message contains $cmds command line(s)"
	echo "Found $cmds command line(s)" >>$LOGFILE
	strings="`cat $CMDS`"
	set -f $strings
#
# This is the MAIN PARSE loop
#
error=0; position=0; action=""; argument=""; destination="DEFAULT"; from="";
with=""; via=""
#
while [ "$1" != "" ]
do
	case $1 in
		@@) 
		test $DEBUG && echo "restart of command line"
		if test $position -gt 0
		then
			echo $action $argument $from $destination $with $via >>$CMDLOG
		fi
		action=""; argument=""; from="DEFAULT"; destination="DEFAULT"
		with="DEFAULT"; via="DEFAULT"; position=0
		shift;;

		[sS][eE][nN][dD])
			test $DEBUG && echo "found \"send\""
			if test $position -eq 0
			then
				action=send
				shift
				if test -z "$1"
				then
					argument="DEFAULT"
					position=1
				else
					if [ "$1" = "@@" ]; then
						argument="DEFAULT"
						position=1
					else
						argument=$1; position=1
						shift
					fi
				fi	
			fi;;
						

		[lL][iI][sS][tT])
			test $DEBUG && echo "found \"list\""
			if test $position -eq 0
			then
				action=list
				shift
				if test -z "$1"
				then
					argument="DEFAULT"
					position=1
				else
					if [ "$1" = "@@" ]; then
						argument="DEFAULT"
						position=1
					else
						argument=$1; position=1
						shift
					fi
				fi	
			fi;;
						

		[iI][nN][dD][eE][xX])
			test $DEBUG && echo "found \"index\""
			if test $position -eq 0
			then
				action=index
				shift
				if test -z "$1"
				then
					argument="DEFAULT"
					position=1
				else
					if [ "$1" = "@@" ]; then
						argument="DEFAULT"
						position=1
					else
						argument=$1; position=1
						shift
					fi
				fi	
			fi;;

		[fF][iI][nN][dD])
			test $DEBUG && echo "found \"find\""
			if test $position -eq 0
			then
				action=find
				shift
				if test -z "$1"
				then
					argument="DEFAULT"
					position=1
				else
					if [ "$1" = "@@" ]; then
						argument="DEFAULT"
						position=1
					else
						argument=$1; position=1
						shift
					fi
				fi	
			fi;;

		[hH][eE][lL][pP]|hilfe|HILFE|aiuto|AIUTO|aled|ALED)
			test $DEBUG && echo "found \"help\""
			if test $position -eq 0
			then
				action=help
				shift
				if test -z "$1"
				then
					argument="DEFAULT"
					position=1
				else
					if [ "$1" = "@@" ]; then
						argument="DEFAULT"
						position=1
					else
						argument=$1; position=1
						shift
					fi
				fi	
			fi;;

		[cC]redits|[cC]redit)
			test $DEBUG && echo "found \"credits\""
			if test $position -eq 0
			then
				action=credits
				shift
				if test -z "$1"
				then
					argument="DEFAULT"
					position=1
				else
					if [ "$1" = "@@" ]; then
						argument="DEFAULT"
						position=1
					else
						argument=$1; position=1
						shift
					fi
				fi	
			fi;;
						

		[fF][rR][oO][mM]|inside|[iI][nN])
			test $DEBUG && echo "found \"from\""
			shift
			if test "$1"
			then
			    test "$1" != "@@" && from=$1 && shift
			fi;;
			

		to|To:)	
			test $DEBUG && echo "found \"to\""
			shift
			if test "$1"
			then
			    test "$1" != "@@" && destination=$1 && shift
			fi;;

		with|With|using|USING)	
			test $DEBUG && echo "found \"with\""
			shift
			if test "$1"
			then
			    test "$1" != "@@" && with=$1 && shift
			fi;;

		[vV][iI][aA]|over|OVER|through|THROUGH)	
			test $DEBUG && echo "found \"via\""
			shift
			if test "$1"
			then
			    test "$1" != "@@" && via=$1 && shift
			fi;;

#		These words are skipped if found before a @@ or after
#		a valid argument shift. 
		*[Pp]lease*|hello|do|[Ss]ubject:|[Aa]ction:)
			test $DEBUG &&	echo "junk \"$1\" skipped"
			shift;;

		*)
			test $DEBUG &&	echo "unknown command: \"$1\""
			echo "\nParser error: unknown command \"$1\"" >>$ERRSTAT
			error=1
			;;
	esac			

	if test $error -gt 0
	then
		test $DEBUG && echo "looking for a new command line"
		while [ "$1" != "@@" ]
		do
			test -z "$1" && test $DEBUG && echo "no more command lines in this message"
			test -z "$1" && break
			shift
		done
		error=0; position=0
		test $DEBUG &&	echo "found a new command line"
	fi


# end while
done

if test $position -gt 0
then
	echo $action $argument $from $destination $with $via>>$CMDLOG
fi
		
# these three lines refer to the test $CMDS at the beginning of parse()

else  
destination=DEFAULT
test $DEBUG && echo "this message does not contain any command line"
fi

}	

interp() {

# If pathsizing is activated, look for credits.. 
test -n "$PATHSIZE" && {
	if [ "$STRINGS" != "" ]; then 
	$STRINGS $PATHSIZE > $TMPDIR/pathstr
	cat $TMPDIR/pathstr > $PATHSIZE
	fi
	if [ "$destination" != "DEFAULT" ]; then
	UUCP_DESTIN=$destination
	credit="`Check_PathSize $UUCP_DESTIN`"
	else
	credit="`Check_PathSize $UUCP_SENDER`"
	fi
	if [ "$credit" = "UNLIMITED" ]; then
	test $DEBUG && echo "Your path: has no limits!"
	echo "Your path: has no limits!" >> $LOGFILE
	else
	if [ "$credit" = "" ]; then
#		Unknown path inside pathsize:
		if [ "$CREDIT" = "0" ]; then
#			New paths need to subscribe!
			test $DEBUG && echo "New path: needs to subscribe!"
			echo "New path: needs to subscribe!" >> $LOGFILE
			SubScribe_Msg | $MAILER $UUCP_SENDER
			rejected=1
		fi
	elif [ "$credit" -le "0" ]; then
		rejected=1
		echo "No more credits for this account" >> $LOGFILE
		NoCredit_Msg | $MAILER $UUCP_SENDER
	fi
	fi
}

test $DEBUG && echo "Interpreter: \c"

if [ "$rejected" = "1" ]; then
	test $DEBUG && echo "Remote rejected or no-credits path: skipping."
	echo "Message from $ARPA_SENDER discarded" >>$LOGFILE
	return;
fi

test -s $RNADIR/hold && {
	test $DEBUG && echo "holding message as pending job"
	echo "Holding message from $ARPA_SENDER" >>$LOGFILE
	return;
}

# First we check if the sender is blacklisted. 
if [ "`BlackList`" != "" ]; then
	test $DEBUG && echo "origin is blacklisted!\nDiagnostic: `BlackList`"
	echo "Origin is Blacklisted: $ARPA_SENDER" >>$LOGFILE
	Headers_Msg >>$OUTFILE
	Deliver_Msg >>$OUTFILE
	echo "\nWARNING, BLACKLIST PROBLEMS!\n`BlackList`\n" >>$OUTFILE
	BlackListed_Msg >>$OUTFILE
	YourMail_Msg >>$OUTFILE
	NoHuman_Msg >>$OUTFILE
	Mail_File
#	I'm done with this message; next one, please..
	return
fi

# Then we check if the sender used "to" field with authorization
if [ "$destination" != "DEFAULT" ]; then
	test $DEBUG && echo "external destination for <$destination>\nChecking for privileges...\c"
	if test -z "`ToCheck`"; then
		test $DEBUG && echo "NO privileges. Request denied!"
		echo "External request denied: $ARPA_SENDER" >>$LOGFILE
		Headers_Msg >>$OUTFILE
		Deliver_Msg >>$OUTFILE
		echo "\nWARNING: no privilege for external destinations\n" >>$OUTFILE
		NoTo_Msg >>$OUTFILE
		YourMail_Msg >>$OUTFILE
		NoHuman_Msg >>$OUTFILE
		Mail_File
#		I'm done with this message; next one, please..
		return
	fi
test $DEBUG && echo "OK, origin is authorized!\nDiagnostic: `ToCheck`"
echo "External Request OK: $ARPA_SENDER" >>$LOGFILE
fi

# And now we check if the parser reported errors..
if test -s $ERRSTAT; then
	test $DEBUG && echo "errors were detected by the parser.\nNotify origin and skip this message."
	echo "Parser rejects: $ARPA_SENDER" >>$LOGFILE
	Headers_Msg >>$OUTFILE
	Deliver_Msg >>$OUTFILE
	cat $ERRSTAT >>$OUTFILE
	Syntax_Msg >>$OUTFILE
	NoHuman_Msg >>$OUTFILE
	Mail_File
#	I'm done with this message; next one, please..
	return
fi

# Work for us?
if test -s $CMDLOG; then
	set `wc -l $CMDLOG`; cmds=$1
	test $DEBUG && echo "working on $cmds valid request(s)"
	echo "Found $cmds valid request(s)" >>$LOGFILE
# following two lines are very important
strings="`cat $CMDLOG`"
set -f $strings
action=""; argument=""; destination=""; via=""; with=""; tok=""
#
# * INTERPRETER LOOP *
# we parse standard 6-fields command lines whose fields are
# <action> <argument> <from-lib> <destination> <with> <via>
# 
while [ "$1" != "" ]
do

action=$1; shift; argument=$1; shift; from=$1; shift; destination=$1
shift; with=$1; shift; via=$1

rm -f $OUTFILE 2>/dev/null
# the following bracket starts the restricted environment of the interpreter:
# since we are using a streamed handling of a "cat", we *need to be sure that
# no procedure is executed within the same environment; so status variables
# won't change and RNA won't loose control of its job. Basically, the main
# effect of such lack is a message like "RNA: cannot shift" . Which takes
# RNA to forget about any command line - and any subsequent mail - aside the
# very first one of the very first income mail. 
(
test $DEBUG && Reference_Msg
Headers_Msg >$OUTFILE 

case $action in

send)	
	Deliver_Msg >>$OUTFILE
	if [ "$argument" = "DEFAULT" ]; then
		test $DEBUG && echo "Missing argument for \"send\""
		echo "\nERROR: command \"send\" requires an argument!\n" >>$OUTFILE
		Syntax_Msg >>$OUTFILE
		NoHuman_Msg >>$OUTFILE
		Mail_File
#		I'm done with this message; next one, please..
		return
	fi
	Reference_Msg >>$OUTFILE
#	Let's see if library and file do really exist
	fname=""; fname="`GetFile $argument $from`" 
	if [ "$fname" != "" ]; then

#	If we are here, file/lib exists , "to" is ok
#	(if there's one), so we may try to ship the stuff.
#       We need to know HOW, first!

# Check the field "via". Sorry for the bad indentation. We all need
# 160 columns monitors nowadays ;-)

case $via in

uusend|UUSEND|Uusend)
	With_Type
	viasped="NO_MAIL"
	Convert_File
	Cut_Address
	Ship_Msg >> $OUTFILE
	test $DEBUG && echo "Now sending file with uusend to :$UUCP_HOST"
	echo "File sent: $argument via $via to: $UUCP_SENDER">>$LOGFILE
# if you don't want to 'bill' uusend shippings, comment next line
	test -n "$PATHSIZE" && Bill $fname
	$UUSEND -r -f -m 666 $fname $UUCP_HOST$PUBDIR"/"$argument ;; 

uucp|UUCP|Uucp)
	With_Type
	viasped="NO_MAIL"
	Convert_File
	Cut_Address
	Ship_Msg >> $OUTFILE
	test $DEBUG && echo "Now send file using uucp to :$UUCP_HOST"
	echo "File sent: $argument via $via to: $UUCP_SENDER">>$LOGFILE
# if you don't want to 'bill' uucp shippings, comment next line
	test -n "$PATHSIZE" && Bill $fname
	$UUCP -r -C $fname $UUCP_HOST$PUBDIR"/"$argument ;;

DEFAULT|default|mail|\
MAIL|Mail|email|EMAIL|E-Mail|\
e-mail|E-MAIL)
	test $DEBUG && echo "Now send file using e-mail to :$UUCP_SENDER"
	With_Type
	viasped=""
	Convert_File 
	echo "File sent: $argument via $via to: $UUCP_SENDER">>$LOGFILE
	;;

*)
	via="DEFAULT"
	With_Type
	viasped=""
	Convert_File
	ViaError_Msg >> $OUTFILE
	test $DEBUG && echo "Now send file using e-mail to :$UUCP_SENDER"
	echo "File sent: $argument via $via to: $UUCP_SENDER">>$LOGFILE
	
esac


	else
#	Something wrong with object file, Scotland Yards investigates..
		if [ "`GetDir $from`" = "" ]; then 
			test $DEBUG && echo "Nonexistent library: \"$from\""
			echo "NO library found: $from" >>$LOGFILE
			NoLibrary_Msg >>$OUTFILE 
		elif [ "`GetFile $argument $from`" = "" ]; then
			test $DEBUG && echo "Nonexistent file: \"$argument\" inside library \"$from\""
			echo "NO file found: $argument" >>$LOGFILE
			NoFile_Msg $from $argument >>$OUTFILE
		else
			CantAccess_Msg >>$OUTFILE
			echo "CANT ACCESS $argument from $from" >>$LOGFILE
			test $DEBUG && echo "WARNING: cannot open \"`GetFile $argument $from`\""
		fi
	fi
	Mail_File ;; 
		
list)	Deliver_Msg >>$OUTFILE
	Reference_Msg >>$OUTFILE
	ListLib $argument >>$OUTFILE
	echo "\nPLEASE use command \"index\" to get more details\n\
	       on library: $argument">>$OUTFILE
	echo "Command executed: list $argument : $ARPA_SENDER" >>$LOGFILE
	Mail_File ;;

index)	Deliver_Msg >>$OUTFILE
	Reference_Msg >>$OUTFILE
	GetCat $argument >>$OUTFILE
	ListLib $argument >>$OUTFILE
	echo "Command executed: index and list $argument : $ARPA_SENDER" >>$LOGFILE
	Mail_File ;;

credits) Deliver_Msg >>$OUTFILE
	Reference_Msg >>$OUTFILE
	if test -n "$PATHSIZE" ; then
		credit="`Check_PathSize $UUCP_SENDER`"
		if [ "$credit" = "" ]; then
			if [ "$CREDIT" != "0" ]; then 
				echo "\nYou are a new user; credits: $CREDIT (bytes)\n" >>$OUTFILE
				echo "(This request will be billed as well, normally about 800 bytes)\n" >>$OUTFILE
			fi
		else
				if [ "$credit" = "UNLIMITED" ]; then
				echo "\nYour path has no limitations.\n" >>$OUTFILE
				else
				echo "\nCredits remaining: $credit out of $CREDIT (bytes)\n" >>$OUTFILE
				echo "(This request will be billed as well, normally about 800 bytes)\n"
				fi
		fi
	else
		echo "\nPathsizing not running here. No limits!\n" >>$OUTFILE
	fi
echo "Command executed: credits for $UUCP_SENDER" >> $LOGFILE
	Mail_File ;;


find)	Deliver_Msg >>$OUTFILE
	Reference_Msg >>$OUTFILE
	if [ "$argument" = "DEFAULT" ]; then
		test $DEBUG && echo "Missing argument for \"find\""
		echo "\nERROR: command \"find\" needs a valid argument!\n" >>$OUTFILE
		NeedHelp_Msg >>$OUTFILE
		NoHuman_Msg >>$OUTFILE
	else
		echo "Command executed: find $argument : $ARPA_SENDER" >>$LOGFILE
		FindFile $argument >>$OUTFILE
	fi
	Mail_File ;;	
help)	Deliver_Msg >>$OUTFILE
	Reference_Msg >>$OUTFILE
	if [ "$argument" != "DEFAULT" ]; then
		echo "\n\
HELP is not available for \"$argument\": try a simple @@ help" >>$OUTFILE
	else
		argument="HELP"; from="DEFAULT";
		hname=""; hname="`GetFile $argument $from`" 
		if [ "$hname" != "" ]; then
			cat $hname >>$OUTFILE
			echo "Command executed: help : $ARPA_SENDER" >>$LOGFILE
		else
			echo "WARNING: NO HELP for $ARPA_SENDER" >>$LOGFILE
			echo "\n\
Cannot open help file inside RNA system directory - sorry" >>$OUTFILE
		fi
	Mail_File 
	fi ;;
	 *)	test $DEBUG && echo "WARNING: interpreter error with token $1"
		echo "WARNING: interp error token $1" >>$LOGFILE
		shift; shift;;

esac
# the following bracket close the restricted environment of the interpreter
)
# recycle next command line (if any)
shift
# end while, recycle
done
else
#	CMDLOG empty: no commands found inside current message
	test $DEBUG && echo "no commands found, notify origin."
	echo "Current message is empty : $ARPA_SENDER" >>$LOGFILE
	Headers_Msg >>$OUTFILE
	Deliver_Msg >>$OUTFILE
	echo "" >>$OUTFILE
	NoCommands_Msg >>$OUTFILE
	Mail_File
fi
}
# End of interpreter

# -----------------------------------
#            main program
# -----------------------------------

test -n "$PATHSIZE" && {
	test -r $PATHSIZE || {
		test $DEBUG && echo "ERROR: cannot open $PATHSIZE"
		exit
	}
}

# Are we out of service?
test -r $RNADIR/hold || {
#	No. Check if we just came out of 'holding' state: in this case we
#	might have a 'pending' file with old jobs to process.
	test -r $RNADIR/pending && {
#		That's it: old requests.. We append them to our current
#		mailbox. New ones are stored before these, i know. 
#		It makes little sense to spend time reordering...
		cat $RNADIR/pending >>$MAILBOX
# %%FIX%%  
# check out that every mail is separated by a null line, in the previous
# cat. Normally, it should. Well, if not, add it. 
		rm $RNADIR/pending
	}
}

test -s $MAILBOX && { 
Startup
GetMail 
CutMail
set `wc -l $POINTERS`
test $DEBUG && echo "New mail found: $1 message(s)"
echo "\n FOUND $1 MESSAGE(S)" >>$LOGFILE
until [ "$message" -gt "$1" ]
do
	test $DEBUG && echo "Now working on message n.$message"
	( ClrTmpFiles
	GetMessage $message
	parse 
	interp )
	test $DEBUG && echo "message n.$message is over"
	message=`expr $message + 1`
done
test $DEBUG && echo "RNA SESSION COMPLETED SUCCESSFULLY"
}


# End of RNA
# %%FIX%%
# Congratulations, you got to the end of RNAlib configuration. If you
# followed indications now you have a working copy of RNA 2.0.
# Before attempting to execute, however, remember you need to create at
# least an index file  (libindex) for libraries.
# In order to make RNA run faster and better, we need to cut off all
# comments from the original configured version. So i strongly recommend
# you make your configuration and modifications on a COMPLETE version of
# RNA, but RUN ALWAYS an extracted rna called 'XRNA'. How do you get
# XRNA out of your RNA? Easy: run 'MAKE_RNA'.
# Every time you need to change something inside RNA, edit RNA and then 
# re-run MAKE_RNA.  -- Paolo 
# 
# RNALIB 2.0 Revision A - END OF CONFIGURATION
