avios151.c
avios/avios151.c · 214.3 KB
From the archive avios151.tar.gz
Download the archive « Back to the archive contents
/****************************************************************************
AVIOS version 1.5.1
A VIrtual Operating System, Copyright (C) Neil Robertson 1997-1998
Version date: 26th March 1998
Created out of blood and sweat using incantations of the C after dusk and
in dark dungeons found in London, England from January 1997 to March 1998.
Please read the README & COPYRIGHT files.
Neil Robertson.
Email : neil@ogham.demon.co.uk
Web pages: http://www.ogham.demon.co.uk/avios.html and /neil.html
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#ifdef _AIX
#include <sys/select.h>
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#ifdef LINUX
#include <sys/ioctl.h>
#endif
#include <time.h>
#include <termio.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <signal.h>
#include <unistd.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>
#include "avios151.h"
#define VERSION "1.5.1"
struct streams *get_stream();
int write_syslog(char *, ...);
/*** The main procedure which initialises the system then calls the
mainloop function. ***/
main(argc,argv)
int argc;
char *argv[];
{
qbm=0; /* quiet bootup mode to off */
/* Setup the build string */
setup_build_string();
/* Go through command line args */
parse_command_line(argc,argv);
/* Startup */
if (!qbm) {
printf("\n*** AVIOS version %s ***\n\n",VERSION);
printf("Build: %s\n\nSystem booting...\n\n",build);
}
if (be_daemon && syslog_file==NULL) {
fprintf(stderr,"ERROR: A syslog file must be specified if the system is to run as a daemon.\n");
exit(1);
}
if (init_file==NULL) init_file=INIT_FILE;
init_system();
create_system_variables();
parse_init_file();
/* Fork after all the parsing so that we don't waste OS time doing this if
theres a boot error. */
if (be_daemon) {
switch(fork()) {
case -1: perror("ERROR: Unable to fork"); exit(-1);
case 0: break;
default: exit(0);
}
#ifdef LINUX
/* Dissociate from tty. This only works on Linux for some reason
even though it should work on all unix's. Don't need to do call it
for stdout and err (1 & 2) as well as process seems to lose tty
after stdin (0) dissociated but do them anyway just to be sure... */
ioctl(0,TIOCNOTTY,NULL);
ioctl(1,TIOCNOTTY,NULL);
ioctl(2,TIOCNOTTY,NULL);
#endif
}
write_syslog("*** System booted with Unix PID %d ***",getpid());
setup_signals();
mainloop();
}
/*** Setup the build parameter string ***/
setup_build_string()
{
/* Set up build parameter string. */
build[0]='\0';
#ifdef LINUX
strcat(build,"LINUX");
#endif
#ifdef FREEBSD
if (build[0]) strcat(build,", ");
strcat(build,"FREEBSD");
#endif
#ifdef NO_USLEEP
if (build[0]) strcat(build,", ");
strcat(build,"NO_USLEEP");
#endif
#ifdef NO_CRYPT
if (build[0]) strcat(build,", ");
strcat(build,"NO_CRYPT");
#endif
#ifdef SUN_BSD_BUG
if (build[0]) strcat(build,", ");
strcat(build,"SUN_BSD_BUG");
#endif
if (!build[0]) strcpy(build,"STANDARD");
}
/*** Parse the command line arguments ***/
parse_command_line(argc,argv)
int argc;
char *argv[];
{
char *usage="Usage: %s [-i <init file>] [-s <syslog file>] [-q] [-d] [-v] [-h]\n";
int i;
/* These 3 vars are globals */
init_file=NULL;
syslog_file=NULL;
be_daemon=0;
/* Loop through args */
for(i=1;i<argc;++i) {
if (!strcmp(argv[i],"-i")) {
if (i==argc-1) { fprintf(stderr,usage,argv[0]); exit(-1); }
++i; init_file=argv[i];
continue;
}
if (!strcmp(argv[i],"-s")) {
if (i==argc-1) { fprintf(stderr,usage,argv[0]); exit(-1); }
++i; syslog_file=argv[i];
continue;
}
if (!strcmp(argv[i],"-d")) { be_daemon=1; continue; }
if (!strcmp(argv[i],"-q")) { qbm=1; continue; }
if (!strcmp(argv[i],"-v")) { printf("%s %s\n",VERSION,build); exit(0); }
if (!strcmp(argv[i],"-h")) {
printf("\nAVIOS version %s\n\nBuild: %s\n\n",VERSION,build);
printf("Copyright (C) Neil Robertson 1997-1998\n\n");
printf(usage,argv[0]);
puts("\n-i: Set the initalisation file (default is 'init').");
puts("-s: Set the system log file (default is standard output).");
puts("-d: Run as a daemon.");
puts("-q: Quiet bootup mode (no non system log messages).");
puts("-v: Print version and build.");
puts("-h: Print this help message.\n");
exit(0);
}
fprintf(stderr,usage,argv[0]);
exit(-1);
}
}
/*** Initialise system stuff and non process specific variables ***/
init_system()
{
umask(0); /* So permissions with mkdir work properly */
srand((int)time(0));
boottime=0;
/* These are initialised to defaults in case they're not set in init file */
code_path[0]='\0';
root_path[0]='\0';
max_processes=MAX_PROCESSES;
max_mesgs=MAX_MESGS;
max_errors=MAX_ERRORS;
exit_remain=EXIT_REMAIN;
swapout_after=SWAPOUT_AFTER;
colour_def=ON;
ignore_sigterm=NO;
kill_any=NO;
child_die=NO;
wait_on_dint=YES;
pause_on_sigtstp=YES;
allow_ur_path=YES;
enhanced_dump=NO;
connect_timeout=0; /* 0 means wait for TCP timeout */
tuning_delay=0;
process_count=1;
first_pcs=NULL;
last_pcs=NULL;
current_pcs=NULL;
real_current_pcs=NULL;
first_port=NULL;
last_port=NULL;
first_stream=NULL;
last_stream=NULL;
}
/*** Create a dummy process that holds all the common system variables.
The dummy process will *always* be first_pcs and we can refer to it
in the code using that variable. ***/
create_system_variables()
{
struct utsname un;
struct passwd *pwd;
int i,ret,flags;
if ((ret=create_process("system_dummy",1))!=OK) goto ERROR;
set_string(&first_pcs->site,"<null>");
/* Create process name array and process count */
flags=READONLY | ARRAY;
if ((ret=create_variable("$pcs",NULL,NULL,flags,1))!=OK) goto ERROR;
if ((ret=set_variable("$pcs:\"1\"",NULL,"system_dummy",1))!=OK) goto ERROR;
if ((ret=create_variable("$pcs_count",NULL,NULL,READONLY,1))!=OK) goto ERROR;
if ((ret=set_variable("$pcs_count",NULL,"1",1))!=OK) goto ERROR;
/* Avios build */
if ((ret=create_variable("$build",NULL,NULL,READONLY,1))!=OK) goto ERROR;
if ((ret=set_variable("$build",NULL,build,1))!=OK) goto ERROR;
/* Avios version */
if ((ret=create_variable("$version",NULL,NULL,READONLY,1))!=OK) goto ERROR;
if ((ret=set_variable("$version",NULL,VERSION,1))!=OK) goto ERROR;
/* Version of Unix we're on - same as "uname -a" unix command output */
uname(&un);
sprintf(text,"%s %s %s %s %s",un.sysname,un.nodename,un.release,un.version,un.machine);
if ((ret=create_variable("$uname",NULL,NULL,READONLY,1))!=OK) goto ERROR;
if ((ret=set_variable("$uname",NULL,text,1))!=OK) goto ERROR;
/* Info on the user who's running the system. If for some reason there is no
info then just leave variable blank. Don't include users encrypted password
here for obvious security reasons. */
if ((ret=create_variable("$unixuser",NULL,NULL,flags,1))!=OK) goto ERROR;
if ((pwd=getpwuid(getuid()))!=NULL) {
set_variable("$unixuser:\"login\"",NULL,pwd->pw_name,1);
sprintf(text,"%d",pwd->pw_uid);
set_variable("$unixuser:\"uid\"",NULL,text,1);
sprintf(text,"%d",pwd->pw_gid);
set_variable("$unixuser:\"gid\"",NULL,text,1);
set_variable("$unixuser:\"gecos\"",NULL,pwd->pw_gecos,1);
set_variable("$unixuser:\"home\"",NULL,pwd->pw_dir,1);
set_variable("$unixuser:\"shell\"",NULL,pwd->pw_shell,1);
}
/* Create error array. Ignore "OK" 'error' as we can't have an array position
zero anyway. */
if ((ret=create_variable("$error",NULL,NULL,flags,1))!=OK) goto ERROR;
for(i=1;i<NUM_ERRS;++i) {
sprintf(text,"$error:\"%d\"",i);
if ((ret=set_variable(text,NULL,error_mesg[i],1))!=OK) goto ERROR;
}
/* Max messages in queues - set after init file parsed */
if ((ret=create_variable("$max_mesgs",NULL,NULL,READONLY,1))!=OK) goto ERROR;
save_process_state(first_pcs,1);
return;
ERROR:
fprintf(stderr,"ERROR: %s whilst creating the system_dummy process.\n",error_mesg[ret]);
exit(ret);
}
/*** Load and parse the init file ***/
parse_init_file()
{
FILE *fp;
int line_num,done_params;
char line[ARR_SIZE+1],word[ARR_SIZE+1];
if (!(fp=fopen(init_file,"r"))) {
perror("ERROR: Unable to open the init file"); exit(-1);
}
if (!qbm) printf("Parsing init file...\n");
line_num=0;
done_params=0;
/* Find a section header */
fgets(line,ARR_SIZE,fp);
while(!feof(fp)) {
++line_num;
word[0]='\0';
sscanf(line,"%s",word);
if (!strlen(word) || word[0]=='#') {
fgets(line,ARR_SIZE,fp); continue;
}
if (!strcmp(word,"PARAMETERS:")) {
line_num=parse_param_section(fp,line_num);
done_params=1;
}
else {
if (!strcmp(word,"PROCESSES:")) {
if (!done_params) {
fprintf(stderr,"INIT ERROR: PARAMETERS section header must come before PROCESSES on line %d.\n",line_num);
exit(-1);
}
parse_process_section(fp,line_num);
return;
}
else {
fprintf(stderr,"INIT ERROR: Invalid section header \"%s\" on line %d.\n",word,line_num);
fclose(fp);
exit(-1);
}
}
fgets(line,ARR_SIZE,fp);
}
fclose(fp);
fprintf(stderr,"INIT ERROR: PROCESSES section header missing.\n");
exit(-1);
}
/*** Parse the PARAMETERS section of the init file ***/
parse_param_section(fp,line_num)
FILE *fp;
int line_num;
{
int i,val,yesno;
char line[ARR_SIZE+1],w1[ARR_SIZE+1],w2[ARR_SIZE+1],*s;
char *coms[]={
"code_path", "root_path", "colour_def", "allow_ur_path",
"kill_any", "child_die", "ignore_sigterm","wait_on_dint",
"pause_on_sigtstp","enhanced_dump","max_errors", "max_mesgs",
"max_processes", "exit_remain", "swapout_after", "connect_timeout",
"tuning_delay",
};
fgets(line,ARR_SIZE,fp);
while(!feof(fp)) {
++line_num;
if (line[0]=='#') {
fgets(line,ARR_SIZE,fp); continue;
}
w1[0]='\0'; w2[0]='\0';
sscanf(line,"%s %s",w1,w2);
/* Newline means end of section so return */
if (!strlen(w1)) {
sprintf(text,"%d",max_mesgs);
set_variable("$max_mesgs",NULL,text,1);
return line_num;
}
s=w1; while(*s) { *s=tolower(*s); ++s; }
if (!strcmp(w1,"waffle")) waffle();
if (!strcmp(w2,"NO") || !strcmp(w2,"no")) yesno=0;
else if (!strcmp(w2,"YES") || !strcmp(w2,"yes")) yesno=1;
else yesno=-1;
for(i=0;i<17;++i) {
if (!strcmp(coms[i],w1)) {
val=atoi(w2);
/* This looks yucky, but it works so fuck style... */
if (i>2 && i<10 && yesno==-1) goto ERROR;
if (i>9 && !isinteger(w2,0)) goto ERROR;
if (i>10 && i<15 && val<1) goto ERROR;
if ((i==10 || i>14) && val<0) goto ERROR;
switch(i) {
case 0:
strcpy(code_path,w2);
if (code_path[strlen(code_path)-1]!='/')
strcat(code_path,"/");
break;
case 1:
strcpy(root_path,w2);
if (root_path[strlen(root_path)-1]!='/')
strcat(root_path,"/");
break;
case 2:
if (!strcmp(w2,"ON") || !strcmp(w2,"on"))
colour_def=1;
else
if (!strcmp(w2,"OFF") || !strcmp(w2,"off"))
colour_def=0;
else goto ERROR;
break;
case 3: allow_ur_path=yesno; break;
case 4: kill_any=yesno; break;
case 5: child_die=yesno; break;
case 6: ignore_sigterm=yesno; break;
case 7: wait_on_dint=yesno; break;
case 8: pause_on_sigtstp=yesno; break;
case 9: enhanced_dump=yesno; break;
case 10: max_errors=val; break;
case 11: max_mesgs=val; break;
case 12: max_processes=val; break;
case 13: exit_remain=val; break;
case 14: swapout_after=val; break;
case 15: connect_timeout=val; break;
case 16:
#ifndef NO_USLEEP
tuning_delay=val; break;
#else
fprintf(stderr,"INIT ERROR: \"tuning_delay\" option not supported in this build on line %d.\n",line_num);
exit(-1);
#endif
}
break;
}
}
if (i==17) {
fprintf(stderr,"INIT ERROR: Invalid option \"%s\" on line %d.\n",w1,line_num);
exit(-1);
}
fgets(line,ARR_SIZE,fp);
}
ERROR:
fprintf(stderr,"INIT ERROR: Invalid option value \"%s\" on line %d.\n",w2,line_num);
exit(-1);
}
/*** Yackety yack ***/
waffle()
{
char *data="\
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\
4!////!3!////!2!////!BBBBOOOE!BDUJPO!////!(Dpohsbuvmbujpot!po!gjoejoh!\
uijt!boe!xfmdpnf!up!uif!Bwjpt!Fbtufs!Fhh/!Bt!jt!usbejujpobm!xjui!uiftf\
!uijoht!J(e!cfuufs!hfu!po!xjui!uif!dsfejut-!uibolt!boe!tuvgg!cfgpsf!zp\
v!bmm!hfu!cpsfe////!DSFEJUT;!Ofjm!Spcfsutpo!)Nf*/!J!xspuf!uijt!bmm!cz!\
nz!mjuumf!mpoftpnf/!UIBOLT;!Cpccz-!Sjdibse-!Nbsujo-!Kfbo!'!Nbsl!gps!uf\
tujoh!)xjuujohmz!ps!puifsxjtf!;*!tpnf!pg!nz!Bwjpt!qsphsbnt/!TUVGG;!Bwj\
pt!jt!Dpqzsjhiu!)D*!Ofjm!Spcfsutpo!2::8.2::9!boe!J!xspuf!ju!kvtu!up!tf\
f!jg!J!dpvme-!boe!///!J!dpvme!;*!Jg!zpv!epo(u!mjlf!ju-!xfmm-!J!epo(u!h\
jwf!b!tiju!gsbolmz!tp!hp!uzqf!sn!.sg!+!boe!hfu!mptu///////!Gps!uiptf!p\
g!zpv!tujmm!sfbejoh!bu!uijt!qpjou!uibol!zpv!gps!vtjoh!Bwjpt!boe!ibwf!g\
vo/(!//////!BBBBBOOE!DVU/!Pl!fwfszpof-!jut!b!xsbq//////!!!!!!!!!!!!!!!\
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
char *sptr,*cptr,*ptr;
int spaces,i;
spaces=1;
cptr=sptr=data;
printf("@=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-)\n");
while(1) {
ptr=cptr;
printf("\r |");
for(i=0;i<70;++i) {
if (*ptr=='\0') ptr=sptr;
putchar(*ptr-1); ++ptr;
}
putchar('|');
fflush(stdout);
if (*(++cptr)=='\0') cptr=sptr;
if (spaces) {
if (*sptr=='!') ++sptr; else spaces=0;
}
#ifdef NO_USLEEP
sleep(1);
#else
usleep(200000);
#endif
}
}
/*** Parse the PROCESSES section of the init file ***/
parse_process_section(fp,line_num)
FILE *fp;
int line_num;
{
struct streams *st;
char line[ARR_SIZE+1],*argv[MAX_ARGC+1];
char filename[100],pid[30],devname[100];
char *s,*s2,*swpos,c;
int i,ret,argc,option;
int port,dev,new_pid,images,back,swapout;
/* Loop through init file */
images=0;
fgets(line,ARR_SIZE,fp);
while(!feof(fp)) {
++line_num;
/* Get arguments from the input line. Its inefficient to create the
argv array only to destroy it after its been used but what the
hell, its neater that creating the system vars here. */
argc=0;
s=line;
s2=NULL;
option=0;
/* Loop through chars on current init file line */
while(1) {
while(*s<33 && *s) ++s;
if (!*s) {
if (option && option!=3) {
fprintf(stderr,"INIT ERROR: Syntax error on line %d.\n",line_num);
exit(-1);
}
}
s2=s;
while(*s2>32 && *s2!='#') ++s2;
if (*s2=='#') break;
c=*s2; *s2='\0';
/* Check options */
switch(option) {
case 0:
/* First see if we've got a swapout value */
if (swpos=(char *)strchr(s,',')) {
if ((swapout=atoi(++swpos))<1) {
fprintf(stderr,"INIT ERROR: Invalid swapout value \"%s\" on line %d.\n",swpos,line_num);
exit(-1);
}
*(swpos-1)='\0';
}
else swapout=0;
/* Now check where its to be run */
back=0; port=0; dev=0;
if (strcmp(s,"TERM") && strcmp(s,"term")) {
if (!strcmp(s,"BACK") || !strcmp(s,"back"))
back=1;
else {
if (isinteger(s,0)) {
if ((port=atoi(s))<1 || port>65535) {
fprintf(stderr,"INIT ERROR: Invalid port \"%s\" on line %d.\n",s,line_num);
exit(-1);
}
}
else {
if (!strncmp(s,"/dev/",5)) strcpy(devname,s);
else sprintf(devname,"/dev/%s",s);
dev=open_char_device(devname,line_num);
}
}
}
if (be_daemon && !port && !back && !dev) {
fprintf(stderr,"INIT ERROR: Cannot have terminal processes if the system is to run as a daemon on line %d.\n",line_num);
exit(-1);
}
*s2=c; s=s2; option=1;
continue;
case 1:
strcpy(filename,s);
*s2=c; s=s2; option=2;
continue;
}
option=3;
/* Got to process name and number */
if ((argv[argc]=(char *)malloc((int)(s2-s)+1))==NULL) {
fprintf(stderr,"INIT ERROR: Memory allocation error on line %d.\n",line_num);
exit(-1);
}
strcpy(argv[argc],s);
*s2=c; s=s2;
if (!*s || ++argc>MAX_ARGC) break;
} /* end while */
/* Rem'ed out line */
if (!option) {
fgets(line,ARR_SIZE,fp); continue;
}
/* Got process info , now create it */
if ((new_pid=get_new_pid())==-1) {
fprintf(stderr,"INIT ERROR: Too many processes on line %d.\n",line_num);
exit(-1);
}
/* Set system process array entry. */
load_process_state(first_pcs);
sprintf(pid,"$pcs:\"%d\"",new_pid);
set_variable(pid,NULL,argv[0],1);
save_process_state(first_pcs,0);
/* Create a process list entry, create its port then load a program
into its space. If process will be sitting on a port we create an
image which will be used to spawn copies on every connect, else if
process is running on the terminal we just run it straight away. */
if (!qbm) printf("\n=> Creating ");
if (port) {
if (!qbm) printf("image");
images++;
}
else
if (!qbm) {
if (back) printf("background");
else if (dev) printf("device (%s)",devname);
else printf("terminal");
}
if (!qbm) {
printf(" process %d (%s)\n",new_pid,argv[0]);
if (swapout) printf(" Swapout_after set to %d\n",swapout);
}
if (create_process(argv[0],new_pid)!=OK) {
fprintf(stderr,"INIT ERROR: Memory allocation error on line %d.\n",line_num);
exit(-1);
}
if (port) {
set_string(¤t_pcs->site,"<null>");
current_pcs->local_port=port;
create_port_entry(current_pcs,port,line_num);
}
else {
if (back) set_string(¤t_pcs->site,"<BACK>");
else
if (dev) {
sprintf(text,"<%s>",devname);
set_string(¤t_pcs->site,text);
}
else set_string(¤t_pcs->site,"<TERM>");
current_pcs->status=RUNNING;
}
set_string(¤t_pcs->filename,filename);
if (swapout) current_pcs->swapout_after=swapout;
/* Load the actual program */
if (!qbm) printf(" Loading program file \"%s\"\n",filename);
real_line=-1;
if ((ret=process_setup(filename,argc,argv,0))!=OK) {
if (real_line!=-1) {
if (incf==NULL) incf=filename;
fprintf(stderr,"ERROR: %s in file \"%s\" on line %d (Init line %d).\n",error_mesg[ret],incf,real_line,line_num);
}
else fprintf(stderr,"ERROR: %s for file \"%s\" (Init line %d).\n",error_mesg[ret],filename,line_num);
exit(ret);
}
if (back) {
/* Background processes not attached to terminal or socket */
get_stream("STDIN")->external=-1;
get_stream("STDOUT")->external=-1;
}
else
if (dev) {
(st=get_stream("STDIN"))->external=dev;
st->device=1;
(st=get_stream("STDOUT"))->external=dev;
st->device=1;
}
current_pcs->pc=current_proc->start_pos;
save_process_state(current_pcs,1);
/* Free temp arg vars */
for(i=0;i<argc;++i) free(argv[i]);
fgets(line,ARR_SIZE,fp);
}
fclose(fp);
if (process_count==1) { /* 1 cos always have system dummy process */
fprintf(stderr,"INIT ERROR: PROCESSES section is empty.\n");
exit(-1);
}
if (!qbm) printf("\nAll processes loaded: %d real, %d images.\n\n",process_count-images-1,images);
}
/*** Open a character device to use as standard I/O for the process ***/
open_char_device(name,line_num)
char *name;
int line_num;
{
struct stat fs;
struct termio tio;
int fd;
/* Stat device to make sure its a character device */
if (stat(name,&fs)==-1) {
fprintf(stderr,"INIT ERROR: Cannot stat device %s on line %d: %s\n",name,line_num,sys_errlist[errno]);
exit(-1);
}
if ((fs.st_mode & S_IFMT)!=S_IFCHR) {
fprintf(stderr,"INIT ERROR: %s is not a character device on line %d.\n",name,line_num);
exit(-1);
}
/* Now open it */
if ((fd=open(name,O_RDWR))==-1) {
fprintf(stderr,"INIT ERROR: Cannot open device %s on line %d: %s\n",name,line_num,sys_errlist[errno]);
exit(-1);
}
/* Set it to canonical (buffered) mode (probably is by default anyway) */
ioctl(fd,TCGETA,&tio);
tio.c_lflag |= ICANON;
ioctl(fd,TCSETA,&tio);
return fd;
}
/*****************************************************************************
SIGNAL FUNCTIONS
*****************************************************************************/
/*** This will catch a signal , print message to the log and exit the
whole server ***/
void sig_handler(sig)
int sig;
{
struct process *pcs;
char line[100],fname[13],pcsname[11];
int pcnt,icnt,ppid;
switch(sig) {
case SIGTERM:
if (ignore_sigterm) {
write_syslog("SIGTERM (termination signal) received; ignoring...");
signal(SIGTERM,sig_handler);
return;
}
write_syslog("SIGTERM (termination signal) received; exiting...");
break;
case SIGINT:
write_syslog("SIGINT (^C at terminal) received; exiting...");
break;
case SIGQUIT:
write_syslog("SIGQUIT (^\\ at terminal) received; exiting...");
break;
case SIGTSTP:
write_syslog("SIGTSTP (^Z at terminal) received; dumping status...");
break;
case SIGSEGV:
signal(SIGSEGV,SIG_DFL);
write_syslog("PANIC!: A SIGSEGV (segmentation fault) occured; exiting...");
break;
/* You'll never get a bus error with linux on a PC since the x86
hardware does not generate the equivalent hardware interrupt */
case SIGBUS:
signal(SIGBUS,SIG_DFL);
write_syslog("PANIC!: A SIGBUS (bus error) occured; exiting...");
}
/* If we're still booting then just exit. */
if (!boottime) exit(-1);
/* Display processes loaded. Give process id, name, status and current line
number being executed. "-->" shows which process system was executing when
interrupt occured unless system wasn't inside main for() loop in which
case it won't be shown. */
ppid=0;
pcnt=0;
icnt=0;
write_syslog("");
write_syslog("PROCESS STATUS DUMP:");
write_syslog(" PID NAME PPID STATUS FILE LINE COMMAND");
if (enhanced_dump) write_syslog(" (ENHANCED)");
/* This doesn't list the system_dummy process , no point in doing so */
for(pcs=first_pcs->next;pcs!=NULL;pcs=pcs->next) {
if (pcs==real_current_pcs) sprintf(line,"-->%3d",pcs->pid);
else sprintf(line," %3d",pcs->pid);
if (pcs->parent!=NULL) ppid=pcs->parent->pid; else ppid=0;
/* If process or filenames are too long to fit nicely onscreen then
put dots at the end of them */
strncpy(pcsname,pcs->name,10);
pcsname[10]='\0';
if (strlen(pcs->name)>10) {
pcsname[8]='.'; pcsname[9]='.';
}
strncpy(fname,pcs->prog_word[pcs->pc].filename,12);
fname[12]='\0';
if (strlen(pcs->prog_word[pcs->pc].filename)>12) {
fname[10]='.'; fname[11]='.';
}
write_syslog("%s %-10s %3d %-12s %-12s %3d %s",line,pcsname,ppid,status_name[pcs->status],fname,pcs->prog_word[pcs->pc].real_line,pcs->prog_word[pcs->pc].word);
if (enhanced_dump) {
write_syslog(" ( 1: %d, %s, %d, %d, %d, %d )",pcs->created,pcs->site,pcs->remote_port,pcs->int_enabled,pcs->interrupted,pcs->colour);
write_syslog(" ( 2: %lu, %lu, %lu, %lu )",pcs->run_cnt[0],pcs->run_cnt[1],pcs->run_cnt[2],pcs->run_cnt[3]);
write_syslog("");
}
if (pcs->status==IMAGE) ++icnt;
++pcnt;
}
write_syslog("Total of %d processes (%d real, %d images).",pcnt,pcnt-icnt,icnt);
write_syslog("");
/* If ^Z caught then pause else exit */
if (sig==SIGTSTP) {
/* Can't pause if daemon 'cos can't use getchar */
if (!be_daemon && pause_on_sigtstp) {
write_syslog("SYSTEM PAUSED: Press any key to continue...");
getchar();
}
write_syslog("Continuing...");
signal(SIGTSTP,sig_handler);
return;
}
uptime();
write_syslog("*** System halted: All processes killed. ***");
reset_echoing();
exit(-1);
}
/*** Set up some signal handling. ***/
setup_signals()
{
signal(SIGINT,sig_handler);
signal(SIGQUIT,sig_handler);
signal(SIGTSTP,sig_handler);
signal(SIGTERM,sig_handler);
signal(SIGSEGV,sig_handler);
signal(SIGBUS,sig_handler);
signal(SIGILL,SIG_IGN);
signal(SIGTRAP,SIG_IGN);
signal(SIGIOT,SIG_IGN);
signal(SIGCONT,SIG_IGN);
signal(SIGHUP,SIG_IGN);
signal(SIGABRT,SIG_IGN);
signal(SIGFPE,SIG_IGN);
signal(SIGPIPE,SIG_IGN);
signal(SIGTTIN,SIG_IGN);
signal(SIGTTOU,SIG_IGN);
}
/*****************************************************************************
PORT/SOCKET FUNCTIONS
*****************************************************************************/
create_port_entry(pcs,port,line_num)
struct process *pcs;
int port,line_num;
{
struct ports *new,*old;
/* See if port is already reserved */
for(old=first_port;old!=NULL;old=old->next)
if (old->port==port) break;
/* Create new entry */
if ((new=(struct ports *)malloc(sizeof(struct ports)))==NULL) {
fprintf(stderr,"INIT ERROR: Memory allocation error on line %d.\n",line_num);
exit(-1);
}
if (first_port==NULL) first_port=new;
else last_port->next=new;
last_port=new;
new->next=NULL;
new->port=port;
new->process=pcs;
/* Create the socket itself */
if (old==NULL) create_listen_socket(new,line_num);
else new->listen_sock=old->listen_sock;
}
/*** Create the listen socket ***/
create_listen_socket(new,line_num)
struct ports *new;
int line_num;
{
struct sockaddr_in bind_addr;
int size,on;
if (!qbm) printf(" Creating socket on port %d\n",new->port);
/* Create socket */
if ((new->listen_sock=socket(AF_INET,SOCK_STREAM,0))==-1) {
fprintf(stderr,"INIT ERROR: Socket creation error on line %d: %s\n",line_num,sys_errlist[errno]);
exit(-1);
}
/* Allow ports to be re-used when on a TIME_WAIT */
on=1;
size=sizeof(struct sockaddr_in);
setsockopt(new->listen_sock,SOL_SOCKET,SO_REUSEADDR,(char *)&on,sizeof(on));
/* Bind socket to address */
bind_addr.sin_family=AF_INET;
bind_addr.sin_addr.s_addr=INADDR_ANY;
bind_addr.sin_port=htons(new->port);
if (bind(new->listen_sock,(struct sockaddr *)&bind_addr,size)==-1) {
fprintf(stderr,"INIT ERROR: Socket bind() error on line %d: %s\n",line_num,sys_errlist[errno]);
exit(-1);
}
/* Make it listen for connections */
if (listen(new->listen_sock,20)==-1) {
fprintf(stderr,"INIT ERROR: Socket listen() error on line %d: %s\n",line_num,sys_errlist[errno]);
exit(-1);
}
}
/*** Get net address of accepted connection ***/
char *get_ip_address(acc_addr)
struct sockaddr_in acc_addr;
{
static char site[100];
struct hostent *host;
strcpy(site,(char *)inet_ntoa(acc_addr.sin_addr)); /* get number addr */
if ((host=gethostbyaddr((char *)&acc_addr.sin_addr,4,AF_INET))!=NULL)
strcpy(site,host->h_name); /* copy name addr. */
return site;
}
/*** Check to see if we have any connections on the TCP ports ***/
check_for_connects()
{
struct ports *pt,*pt2;
struct timeval tm;
struct sockaddr_in acc_addr;
fd_set mask;
int accept_sock,size,ret,done;
char port[6];
FD_ZERO(&mask);
for(pt=first_port;pt!=NULL;pt=pt->next)
FD_SET(pt->listen_sock,&mask);
tm.tv_sec=0;
tm.tv_usec=0;
errno=0;
do { select(FD_SETSIZE,&mask,0,0,&tm); } while (errno==EINTR);
/* Go through the list of listening ports and see if we have a new connect on
any of them. If we do, spawn new copies of any processes attached to that
port and set their stdin & out to be the accept_sock */
for(pt=first_port;pt!=NULL;pt=pt->next) {
/* See if we've checked same socket already */
done=0;
for(pt2=first_port;pt2!=pt;pt2=pt2->next) {
if (pt2->listen_sock==pt->listen_sock) { done=1; break; }
}
/* See if listen socket has been connected to */
if (!done && FD_ISSET(pt->listen_sock,&mask)) {
/* Accept connection */
size=sizeof(struct sockaddr_in);
if ((accept_sock=accept(pt->listen_sock,(struct sockaddr *)&acc_addr,&size))==-1) {
write_syslog("ERROR: Socket accept() error on port %d for process \"%s\": %s",pt2->port,pt2->process->name,sys_errlist[errno]);
continue;
}
/* Set socket to non-blocking */
if ((fcntl(accept_sock,F_SETFL,O_NONBLOCK))==-1) {
write_syslog("ERROR: Socket fcntl() error on port %d for process \"%s\": %s",pt2->port,pt2->process->name,sys_errlist[errno]);
close(accept_sock);
continue;
}
/* Spawn all processes sharing same port */
for(pt2=pt;pt2!=NULL;pt2=pt2->next) {
if (pt2->listen_sock!=pt->listen_sock) continue;
if ((ret=spawn_process(pt2->process,0,0,0,0,NULL))!=OK) {
write_syslog("ERROR: Unable to spawn process \"%s\": %s.",pt2->process->name,error_mesg[ret]);
close(accept_sock);
continue;
}
load_process_state(last_pcs);
/* Set up some process vars */
current_pcs->status=RUNNING;
current_pcs->pc=pt2->process->pc;
current_pcs->remote_port=(int)ntohs(acc_addr.sin_port);
free(current_pcs->site);
current_pcs->site=NULL;
set_string(¤t_pcs->site,get_ip_address(acc_addr));
set_variable("$site",NULL,current_pcs->site,1);
sprintf(port,"%d",current_pcs->remote_port);
set_variable("$rport",NULL,port,1);
/* If get_stream returns NULL here the whole thing is
fucked anyway so it won't matter if we crash with
a SIGSEGV */
get_stream("STDIN")->external=accept_sock;
get_stream("STDOUT")->external=accept_sock;
write_syslog("Connection on %d from %s:%s; spawned process %d (%s).",pt->port,current_pcs->site,port,current_pcs->pid,current_pcs->name);
}
} /* end if */
}
}
/*****************************************************************************
PROCESS CONTROL FUNCTIONS
*****************************************************************************/
/*** Add a process entry to the process list ***/
create_process(name,pid)
char *name;
int pid;
{
struct process *pcs;
int i;
if ((pcs=(struct process *)malloc(sizeof(struct process)))==NULL)
return ERR_MALLOC;
/* Disable signals temporarily 'cos we might crash if we jump to sig handler
and process list has dangling ->next pointer or entry data not set unless
the system is booting. */
if (boottime) {
signal(SIGINT,SIG_IGN);
signal(SIGQUIT,SIG_IGN);
signal(SIGTSTP,SIG_IGN);
signal(SIGTERM,SIG_IGN);
}
/* Update process count */
if (pid!=1) {
process_count++;
load_process_state(first_pcs);
sprintf(text,"%d",process_count);
set_variable("$pcs_count",NULL,text,1);
}
if (first_pcs==NULL) {
first_pcs=pcs; pcs->prev=NULL;
}
else {
last_pcs->next=pcs; pcs->prev=last_pcs;
}
pcs->next=NULL;
last_pcs=pcs;
current_pcs=pcs;
/* Set process name & stuff */
pcs->name=NULL;
set_string(&pcs->name,name);
pcs->filename=NULL;
set_string(&pcs->filename,"<null>");
pcs->site=NULL;
pcs->pid=pid;
pcs->status=IMAGE;
pcs->old_status=IMAGE;
pcs->pc=0;
pcs->swapout_after=swapout_after;
pcs->over=0;
pcs->local_port=0;
pcs->remote_port=0;
pcs->eof=0;
pcs->sleep_sec=0;
pcs->sleep_usec=0;
pcs->exit_code=OK;
pcs->parent=NULL;
pcs->input_buff=NULL;
pcs->mesg_q=NULL;
pcs->mesg_cnt=0;
pcs->timer_sec=0;
pcs->timer_usec=0;
pcs->death_pid=0;
pcs->death_mesg=NULL;
pcs->wait_pid=0;
pcs->wait_var=NULL;
pcs->wait_var_proc=NULL;
pcs->c_int_proc=NULL; /* child interrupt proc */
pcs->n_int_proc=NULL; /* nonchild */
pcs->t_int_proc=NULL; /* timer */
pcs->int_enabled=1;
pcs->interrupted=0;
pcs->colour=colour_def;
pcs->err_cnt=0;
pcs->exit_cnt=0;
pcs->input_vnum=1;
for(i=0;i<4;++i) pcs->run_cnt[i]=0;
/* Initialise structure pointers */
pcs->prog_word=NULL;
pcs->rstack_start=NULL;
pcs->rstack_ptr=NULL;
pcs->pstack_start=NULL;
pcs->pstack_ptr=NULL;
pcs->lstack_start=NULL;
pcs->lstack_ptr=NULL;
pcs->first_proc=NULL;
pcs->last_proc=NULL;
pcs->current_proc=NULL;
pcs->first_var=NULL;
pcs->last_var=NULL;
pcs->current_var=NULL;
pcs->first_loop=NULL;
pcs->last_loop=NULL;
pcs->current_loop=NULL;
pcs->first_label=NULL;
pcs->last_label=NULL;
pcs->current_instream=NULL;
pcs->current_outstream=NULL;
pcs->created=time(0);
/* Reset signals */
if (boottime) {
signal(SIGINT,sig_handler);
signal(SIGQUIT,sig_handler);
signal(SIGTSTP,sig_handler);
signal(SIGTERM,sig_handler);
}
return OK;
}
/*** Remove a process entry from the process list ***/
destroy_process(pcs)
struct process *pcs;
{
struct process *pcs2;
struct array *arr,*arrprev;
char pid[10];
/* Disable signals. See create_process() function as to why. */
if (boottime) {
signal(SIGINT,SIG_IGN);
signal(SIGQUIT,SIG_IGN);
signal(SIGTSTP,SIG_IGN);
signal(SIGTERM,SIG_IGN);
}
sprintf(pid,"%d",pcs->pid);
/* Reset any parent flags of other processes */
for(pcs2=first_pcs;pcs2!=NULL;pcs2=pcs2->next) {
if (pcs2->parent==pcs) pcs2->parent=pcs->parent;
}
/* Destroy process */
if (pcs==first_pcs) {
first_pcs=pcs->next;
if (first_pcs==NULL) last_pcs=NULL;
else first_pcs->prev=NULL;
}
else {
pcs->prev->next=pcs->next;
if (pcs==last_pcs) last_pcs=pcs->prev;
else pcs->next->prev=pcs->prev;
}
free(pcs);
/* Remove process $pcs entry */
load_process_state(first_pcs);
get_variable("$pcs",NULL); /* Set current_var. $pcs guaraunteed to exist */
arrprev=NULL;
for(arr=current_var->arr;arr!=NULL;arr=arr->next) {
if (!strcmp(arr->subscript,pid)) {
if (arrprev==NULL) current_var->arr=arr->next;
else arrprev->next=arr->next;
free(arr->subscript);
FREE(arr->value);
free(arr);
break;
}
arrprev=arr;
}
/* Reset signals */
if (boottime) {
signal(SIGINT,sig_handler);
signal(SIGQUIT,sig_handler);
signal(SIGTSTP,sig_handler);
signal(SIGTERM,sig_handler);
}
load_process_state(first_pcs);
/* Set new process count and return */
sprintf(text,"%d",--process_count);
return set_variable("$pcs_count",NULL,text,1);
}
/*** Recreate a new process in the image of the parent. This function looks
horrid to read and it was horrid to write but theres no simpler way
that I can think of to do this. And yes I know it doesn't check every
call for malloc errors, if the system runs out of memory then it'll
probably crash elsewhere anyway :) ***/
spawn_process(par,child,preserve,type,dev,devname)
struct process *par;
int child,preserve,type,dev;
char *devname;
{
struct process *cur,*new;
struct procedures *proc,*newproc,*oldproc;
struct vars *var,*newvar,*oldvar;
struct array *arr,*arrnext;
struct loops_choose *loop,*newloop,*oldloop;
struct labels *label,*newlabel,*oldlabel;
struct streams *st,*stnext;
struct proc_stack *ps;
struct result_stack *rs;
struct loop_stack *ls;
int ret,w,w2,ok,size,new_pid;
char pid[10],ppid[10];
if ((new_pid=get_new_pid())==-1) return ERR_MAX_PROCESSES;
if (preserve) {
cur=current_pcs; save_process_state(cur,0);
}
/* Create new process (which also initialises all its pointers) */
if ((ret=create_process(par->name,new_pid))!=OK) {
if (preserve) load_process_state(cur);
return ret;
}
new=current_pcs;
/* Set some parameters according to type. Ie using current parent port,
terminal or background */
switch(type) {
case 0:
set_string(&new->site,par->site);
new->local_port=par->local_port;
new->remote_port=par->remote_port;
break;
case 1:
set_string(&new->site,"<TERM>");
break;
case 2:
set_string(&new->site,"<BACK>");
break;
case 3:
sprintf(text,"<%s>",devname);
set_string(&new->site,devname);
}
/* Do the simple bit copying. Some of these should not need to be copied since
the should not be set if the process is spawning (eg sleep_sec, wait_var) but
just in case I alter the code in the future I won't have to worry ... */
set_string(&new->filename,par->filename);
new->pid=new_pid;
new->num_words=par->num_words;
new->status=par->status;
new->old_status=par->old_status;
new->swapout_after=par->swapout_after;
new->over=0;
new->eof=par->eof;
new->pc=par->prog_word[par->pc].end_pos+1;
new->int_enabled=par->int_enabled;
new->interrupted=par->interrupted;
new->sleep_sec=par->sleep_sec;
new->sleep_usec=par->sleep_usec;
new->wait_pid=par->wait_pid;
new->mesg_cnt=par->mesg_cnt;
new->timer_sec=par->timer_sec;
new->timer_usec=par->timer_usec;
new->input_vnum=par->input_vnum;
new->colour=par->colour;
if (par->mesg_q) set_string(&new->mesg_q,par->mesg_q);
if (par->input_buff) set_string(&new->input_buff,par->input_buff);
if (par->wait_var) set_string(&new->wait_var,par->wait_var);
if (par->death_mesg) set_string(&new->death_mesg,par->death_mesg);
if (child) new->parent=par;
/* Now the hard parts, start with the program text */
size=sizeof(struct program)*par->num_words+1;
if (!(new->prog_word=(struct program *)malloc(size))) {
ret=ERR_MALLOC; goto ERROR;
}
memcpy(new->prog_word,par->prog_word,size);
for(w=0;w<par->num_words;++w) {
if (!(new->prog_word[w].word=(char *)malloc(strlen(par->prog_word[w].word)+1))) {
ret=ERR_MALLOC; goto ERROR;
}
new->prog_word[w].word=NULL;
set_string(&new->prog_word[w].word,par->prog_word[w].word);
new->prog_word[w].filename=NULL;
set_string(&new->prog_word[w].filename,par->prog_word[w].filename);
/* Don't copy any parsed equations. Not worth it. */
new->prog_word[w].equa=NULL;
new->prog_word[w].equacnt=0;
}
/* .. then copy the procedures */
oldproc=NULL;
newproc=NULL;
for(proc=par->first_proc;proc!=NULL;proc=proc->next) {
if (!(newproc=(struct procedures *)malloc(sizeof(struct procedures)))) {
ret=ERR_MALLOC; goto ERROR;
}
if (oldproc!=NULL) oldproc->next=newproc;
else new->first_proc=newproc;
newproc->name=NULL;
set_string(&newproc->name,proc->name);
newproc->start_pos=proc->start_pos;
newproc->ei_di_int=proc->ei_di_int;
newproc->old_int=proc->old_int;
newproc->next=NULL;
proc->copy=newproc;
oldproc=newproc;
}
new->current_proc=par->current_proc->copy;
new->last_proc=newproc;
if (par->wait_var_proc!=NULL) new->wait_var_proc=par->wait_var_proc->copy;
if (par->c_int_proc!=NULL) new->c_int_proc=par->c_int_proc->copy;
if (par->n_int_proc!=NULL) new->n_int_proc=par->n_int_proc->copy;
if (par->t_int_proc!=NULL) new->t_int_proc=par->t_int_proc->copy;
/* Now the variables... */
ok=0;
oldvar=NULL;
newvar=NULL;
for(var=par->first_var;var!=NULL;var=var->next) {
ok=1;
if (!(newvar=(struct vars *)malloc(sizeof(struct vars)))) {
ret=ERR_MALLOC; goto ERROR;
}
newvar->prev=oldvar;
if (oldvar!=NULL) oldvar->next=newvar;
else new->first_var=newvar;
newvar->name=NULL;
set_string(&newvar->name,var->name);
newvar->value=NULL;
set_string(&newvar->value,var->value);
newvar->flags=var->flags;
newvar->arr=NULL;
copy_array(var,newvar);
newvar->proc=var->proc;
if (var->proc!=NULL) newvar->proc=var->proc->copy;
newvar->next=NULL;
var->copy=newvar;
oldvar=newvar;
}
if (ok) {
/* Set any reference variables. var->copy will refer to the just
created twin variable in the new process. */
for(var=par->first_var;var!=NULL;var=var->next) {
if (var->refvar!=NULL) var->copy->refvar=var->refvar->copy;
else var->copy->refvar=NULL;
}
}
new->last_var=newvar;
first_var=new->first_var;
last_var=new->last_var;
sprintf(pid,"%d",new_pid);
if ((ret=set_variable("$pid",NULL,pid,1))!=OK) goto ERROR;
if (child) sprintf(ppid,"%d",par->pid); else strcpy(ppid,"0");
if ((ret=set_variable("$ppid",NULL,ppid,1))!=OK) goto ERROR;
/*.. and now the loops .. */
ok=0;
oldloop=NULL;
newloop=NULL;
for(loop=par->first_loop;loop!=NULL;loop=loop->next) {
ok=1;
if (!(newloop=(struct loops_choose *)malloc(sizeof(struct loops_choose)))) {
ret=ERR_MALLOC; goto ERROR;
}
if (oldloop!=NULL) oldloop->next=newloop;
else new->first_loop=newloop;
memcpy(newloop,loop,sizeof(struct loops_choose));
newloop->proc=loop->proc->copy;
if (loop->foreach_var!=NULL)
newloop->foreach_var=loop->foreach_var->copy;
newloop->next=NULL;
loop->copy=newloop;
oldloop=newloop;
}
if (ok) {
if (par->current_loop!=NULL) new->current_loop=par->current_loop->copy;
else new->current_loop=NULL;
}
new->last_loop=newloop;
/* .. and the labels, *yawn* this is getting tedious */
oldlabel=NULL;
newlabel=NULL;
for(label=par->first_label;label!=NULL;label=label->next) {
if (!(newlabel=(struct labels *)malloc(sizeof(struct labels)))) {
ret=ERR_MALLOC; goto ERROR;
}
if (oldlabel!=NULL) oldlabel->next=newlabel;
else new->first_label=newlabel;
newlabel->name=NULL;
set_string(&newlabel->name,label->name);
newlabel->pos=label->pos;
if (label->proc!=NULL) newlabel->proc=label->proc->copy;
newlabel->next=NULL;
oldlabel=newlabel;
}
new->last_label=newlabel;
/* Copy streams (except for specific parent pid mesg_q stream) */
sprintf(pid,"%d",new_pid);
sprintf(ppid,"%d",par->pid);
for(st=first_stream;st!=NULL;st=st->next) {
if (st->owner!=par || !strcmp(st->name,ppid)) continue;
if ((ret=create_stream(st->name,st->filename,st->external,st->internal,st->rw,new))!=OK)
goto ERROR;
/* Newly created stream is last on list */
last_stream->device=st->device;
last_stream->block=st->block;
last_stream->echo=st->echo;
last_stream->con_sock=st->con_sock;
last_stream->locked=st->locked;
if (st==par->current_instream) new->current_instream=last_stream;
if (st==par->current_outstream) new->current_outstream=last_stream;
}
if ((ret=create_stream(pid,NULL,-1,MESG_Q,READWRITE,new))!=OK) goto ERROR;
/* Copy proc stack */
pstack_start=NULL;
pstack_ptr=NULL;
for(ps=par->pstack_start;ps!=NULL;ps=ps->next) {
push_pstack(ps->proc->copy);
pstack_ptr->ret_pc=ps->ret_pc;
}
new->pstack_start=pstack_start;
new->pstack_ptr=pstack_ptr;
/* Copy loop stack */
lstack_start=NULL;
lstack_ptr=NULL;
for(ls=par->lstack_start;ls!=NULL;ls=ls->next) push_lstack(ls->loop->copy);
new->lstack_start=lstack_start;
new->lstack_ptr=lstack_ptr;
/* Copy result stack even though it should always be empty as spawn can't
be nested. */
rstack_start=NULL;
rstack_ptr=NULL;
for(rs=par->rstack_start;rs!=NULL;rs=rs->next) push_rstack(rs->value);
new->rstack_start=rstack_start;
new->rstack_ptr=rstack_ptr;
/* Set some things based on IO type. If type = 0 (ie keep connected to port
of parent process) keep things as they are. */
switch(type) {
case 1: /* running on terminal */
set_variable("$lport",NULL,"0",1);
set_variable("$rport",NULL,"0",1);
get_stream("STDIN")->external=0;
get_stream("STDOUT")->external=1;
break;
case 2:
set_variable("$lport",NULL,"0",1);
set_variable("$rport",NULL,"0",1);
get_stream("STDIN")->external=-1;
get_stream("STDOUT")->external=-1;
break;
case 3:
set_variable("$lport",NULL,"0",1);
set_variable("$rport",NULL,"0",1);
get_stream("STDIN")->external=dev;
get_stream("STDOUT")->external=dev;
}
/* Set system process array entry */
load_process_state(first_pcs);
sprintf(pid,"$pcs:\"%d\"",new->pid);
if ((ret=set_variable(pid,NULL,new->name,1))!=OK) goto ERROR;
save_process_state(first_pcs,0);
if (preserve) load_process_state(cur);
return OK;
/* Here I have to free everything thats been reserved. Yuk. Pity there isn't
some C facility to free all memory malloced within the current function */
ERROR:
/* Delete some process attributes */
FREE(new->name);
FREE(new->filename);
FREE(new->mesg_q);
FREE(new->input_buff);
FREE(new->wait_var);
FREE(new->site);
/* Delete program text */
if (new->prog_word) {
for(w2=0;w2<w;++w2) free(new->prog_word[w2].word);
free(new->prog_word);
}
/* Delete procedures */
for(proc=new->first_proc;proc!=NULL;proc=newproc) {
newproc=proc->next; free(proc->name); free(proc);
}
/* Delete variables and any array data they hold */
for(var=new->first_var;var!=NULL;var=newvar) {
newvar=var->next;
free(var->name);
FREE(var->value);
for(arr=var->arr;arr!=NULL;arr=arrnext) {
arrnext=arr->next;
free(arr->subscript);
FREE(arr->value);
free(arr);
}
free(var);
}
/* Delete loops */
for(loop=new->first_loop;loop!=NULL;loop=newloop) {
newloop=loop->next; free(loop);
}
/* Delete labels */
for(label=new->first_label;label!=NULL;label=newlabel) {
newlabel=label->next; free(label->name); free(label);
}
/* Delete streams owned by process. Don't need to check if any other
process is referencing them as they won't have had a chance to. */
for(st=first_stream;st!=NULL;st=stnext) {
stnext=st->next;
if (st->owner==new) destroy_stream(st);
}
/* Delete stacks */
pstack_start=new->pstack_start;
while(pstack_start) pop_pstack();
lstack_start=new->lstack_start;
while(lstack_start) pop_lstack();
rstack_start=new->rstack_start;
while(rstack_start) pop_rstack();
/* Remove process from linked list and reload calling process if appropriate */
destroy_process(new);
if (preserve) load_process_state(cur);
return ret;
}
/*** Save process data & pointers. If we are running we only need to save the
ones that change but if we have just loaded a program save them all ***/
save_process_state(pcs,all)
struct process *pcs;
int all;
{
if (pcs==NULL) return;
pcs->rstack_start=rstack_start;
pcs->rstack_ptr=rstack_ptr;
pcs->pstack_start=pstack_start;
pcs->pstack_ptr=pstack_ptr;
pcs->lstack_start=lstack_start;
pcs->lstack_ptr=lstack_ptr;
pcs->first_var=first_var;
pcs->last_var=last_var;
pcs->current_proc=current_proc;
pcs->current_loop=current_loop;
pcs->current_instream=current_instream;
pcs->current_outstream=current_outstream;
if (all) {
pcs->prog_word=prog_word;
pcs->num_words=num_words;
pcs->first_proc=first_proc;
pcs->last_proc=last_proc;
pcs->first_loop=first_loop;
pcs->last_loop=last_loop;
pcs->first_label=first_label;
pcs->last_label=last_label;
}
}
/*** Load process data & pointers ***/
load_process_state(pcs)
struct process *pcs;
{
if (pcs==NULL) return;
prog_word=pcs->prog_word;
num_words=pcs->num_words;
rstack_start=pcs->rstack_start;
rstack_ptr=pcs->rstack_ptr;
pstack_start=pcs->pstack_start;
pstack_ptr=pcs->pstack_ptr;
lstack_start=pcs->lstack_start;
lstack_ptr=pcs->lstack_ptr;
first_proc=pcs->first_proc;
last_proc=pcs->last_proc;
current_proc=pcs->current_proc;
first_var=pcs->first_var;
last_var=pcs->last_var;
current_var=pcs->current_var;
first_loop=pcs->first_loop;
last_loop=pcs->last_loop;
current_loop=pcs->current_loop;
first_label=pcs->first_label;
last_label=pcs->last_label;
current_instream=pcs->current_instream;
current_outstream=pcs->current_outstream;
current_pcs=pcs;
}
/*** Interrupt the current process ***/
interrupt_process()
{
struct procedures *proc;
int status;
status=current_pcs->status;
current_pcs->status=RUNNING;
switch(status) {
case CHILD_INT:
/* If no interrupt procedure to jump to do nothing */
if (current_pcs->c_int_proc==NULL) {
current_pcs->status=current_pcs->old_status; return OK;
}
proc=current_pcs->c_int_proc;
break;
case NONCHILD_INT:
if (current_pcs->n_int_proc==NULL) {
current_pcs->status=current_pcs->old_status; return OK;
}
proc=current_pcs->n_int_proc;
break;
case TIMER_INT:
if (current_pcs->t_int_proc==NULL) {
current_pcs->status=current_pcs->old_status; return OK;
}
proc=current_pcs->t_int_proc;
}
/* Set up pstack data and pc */
pstack_ptr->ret_pc=current_pcs->pc;
current_pcs->pc=prog_word[proc->start_pos].end_pos+1;
current_proc=proc;
current_pcs->interrupted=1;
/* This needs to be done (even though from a cursary glance it seems
completely pointless) to avoid a problem which is too boring to
explain here */
if (proc->ei_di_int) {
proc->old_int=current_pcs->int_enabled;
current_pcs->int_enabled=proc->ei_di_int-1;
sprintf(text,"%d",current_pcs->int_enabled);
set_variable("$int_enabled",NULL,text,1);
}
return push_pstack(proc);
}
/*** Get a process by its pid ***/
struct process *get_process(pid)
int pid;
{
struct process *pcs;
for(pcs=first_pcs;pcs!=NULL;pcs=pcs->next)
if (pcs->pid==pid) return pcs;
return NULL;
}
/*** Free all allocated memory used by the current process before we exit ***/
process_exit()
{
struct process *parent,*pcs,*pcs2,*ipcs;
struct procedures *pnext;
struct loops_choose *lnext;
struct labels *label,*labnext;
struct vars *vnext;
struct array *arr,*arrnext;
struct streams *st,*stnext;
char pid[10];
int w,e,int_type;
int hours,mins,secs;
pcs=current_pcs;
if (pcs->exit_cnt++<exit_remain) return;
/* If we're to interrupt another process on death see if we can interrupt it.
If its already exiting itself just continue else we may need to wait if
wait_on_dint set depending on its status. */
if (pcs->death_pid &&
(ipcs=get_process(pcs->death_pid)) &&
ipcs->status!=EXITING) {
/* Can we interrupt process? */
if (!ipcs->int_enabled ||
ipcs->interrupted ||
ipcs->status==CHILD_INT ||
ipcs->status==NONCHILD_INT ||
ipcs->status==TIMER_INT ||
ipcs->status==HALTED) {
/* No we can't at the moment */
if (wait_on_dint) return; /* MUST interrupt before we die */
else goto SKIP;
}
/* See if process to interrupt is a parent of deceased process */
if (pcs->parent==ipcs) int_type=CHILD_INT; else int_type=NONCHILD_INT;
/* Set other processes vars */
save_process_state(pcs,0);
load_process_state(ipcs);
if (pcs->death_mesg) sprintf(text,"%d %s",pcs->pid,pcs->death_mesg);
else sprintf(text,"%d",pcs->pid);
set_variable("$int_mesg",NULL,text,1);
ipcs->old_status=ipcs->status;
ipcs->status=int_type;
save_process_state(ipcs,0);
load_process_state(pcs);
}
SKIP:
FREE(pcs->death_mesg);
/* If exit_code < 0 then exit was initiated by "exit" command within the
process else it was done by the system */
if (current_pcs->exit_code<0)
sprintf(text,"Process %d (%s) exited with process code %d.",pcs->pid,pcs->name,-current_pcs->exit_code-1);
else sprintf(text,"Process %d (%s) exited with system code %d.",pcs->pid,pcs->name,current_pcs->exit_code);
/* Give process runtime */
secs=(int)(time(0) - pcs->created);
hours=secs/3600; secs%=3600;
mins=secs/60; secs%=60;
write_syslog("%s Runtime: %02d:%02d:%02d",text,hours,mins,secs);
/* Free some stuff */
free(pcs->name);
free(pcs->filename);
FREE(pcs->mesg_q);
FREE(pcs->site);
FREE(pcs->input_buff);
FREE(pcs->wait_var);
/* Delete program text and any parsed equations */
if (prog_word==NULL) return;
for(w=0;w<num_words;++w) {
free(prog_word[w].word);
free(prog_word[w].filename);
if (prog_word[w].equacnt) {
for(e=0;e<prog_word[w].equacnt;++e)
FREE(prog_word[w].equa[e].word);
free(prog_word[w].equa);
}
}
free(prog_word);
/* Delete procedure list */
for(current_proc=first_proc;current_proc!=NULL;current_proc=pnext) {
pnext=current_proc->next;
FREE(current_proc->name);
free(current_proc);
}
/* Delete loops */
for(current_loop=first_loop;current_loop!=NULL;current_loop=lnext) {
lnext=current_loop->next; free(current_loop);
}
/* Delete labels */
for(label=first_label;label!=NULL;label=labnext) {
labnext=label->next; FREE(label->name); free(label);
}
/* Delete vars */
for(current_var=first_var;current_var!=NULL;current_var=vnext) {
vnext=current_var->next;
FREE(current_var->name);
FREE(current_var->value);
for(arr=current_var->arr;arr!=NULL;arr=arrnext) {
arrnext=arr->next;
FREE(arr->subscript);
FREE(arr->value);
free(arr);
}
free(current_var);
}
/* Delete stacks */
while(pstack_start) pop_pstack();
while(lstack_start) pop_lstack();
while(rstack_start) pop_rstack();
/* Delete streams owned by process */
for(st=first_stream;st!=NULL;st=stnext) {
stnext=st->next;
if (st->owner==pcs) {
/* See if another process is referencing it (eg if a mesg q).
Another processes instream should never be set to one of
our streams but check anyway just in case. */
for(pcs2=first_pcs;pcs2!=NULL;pcs2=pcs2->next) {
if (pcs2->current_outstream==st)
pcs2->current_outstream=NULL;
if (pcs2->current_instream==st)
pcs2->current_instream=NULL;
}
destroy_stream(st);
}
}
parent=pcs->parent;
sprintf(pid,"%d",pcs->pid);
/* If parent process is on CHILD_DWAIT notify it of death */
if (parent!=NULL && parent->status==CHILD_DWAIT) {
load_process_state(parent);
current_pcs->status=RUNNING;
set_variable(parent->wait_var,parent->wait_var_proc,pid,1);
free(parent->wait_var);
parent->wait_var=NULL;
parent->pc+=2; /* Advance parents counter */
save_process_state(parent,0);
}
/* See if any process is waiting for us to die and also if we're to kill any
child processes upon exiting do that too. */
for(pcs2=first_pcs;pcs2!=NULL;pcs2=pcs2->next) {
if (pcs2->status==SPEC_DWAIT && pcs2->wait_pid==pcs->pid) {
pcs2->pc=pcs2->prog_word[pcs2->pc].end_pos+1;
pcs2->status=RUNNING;
}
/* This will cause a cascade effect as child processes killed here
run this function too */
if (child_die && pcs2->parent==pcs) {
write_syslog("Child process %d (%s) being terminated.",pcs2->pid,pcs2->name);
pcs2->status=EXITING;
pcs2->exit_code=OK;
}
}
/* Remove process from list */
destroy_process(pcs);
}
/*** Get a process id for a new process. ***/
get_new_pid()
{
struct process *pcs;
int max,pid;
/* Find current maximum and make new_pid one beyond that. Max processes
doesn't count the system dummy */
max=1;
for(pcs=first_pcs;pcs!=NULL;pcs=pcs->next) if (pcs->pid>max) max=pcs->pid;
if (max<=max_processes) return max+1;
/* Find any free process id. Start from 2 cos system_dummy (pid 1) is always
present */
for(pid=2;pid<=max_processes+1;++pid)
if (get_process(pid)==NULL) return pid;
/* Reached max processes */
return -1;
}
/*****************************************************************************
STREAM FUNCTIONS
These perform all the necessary actions to control the systems internal and
external streams.
****************************************************************************/
/*** Get a stream based on its name. If name is just a number then we
are looking for a process message queue. ***/
struct streams *get_stream(name)
char *name;
{
struct streams *st;
int is_q;
if (name==NULL) return NULL;
/* Convert dummy message queue name into real message queue name */
if (!strcmp(name,"MESG_Q") && current_pcs) {
sprintf(name,"%d",current_pcs->pid); is_q=1;
}
else is_q=isinteger(name,0);
for(st=first_stream;st!=NULL;st=st->next) {
/* If looking for message queue ignore owner */
if ((is_q || st->owner==current_pcs) && !strcmp(st->name,name))
return st;
}
return NULL;
}
/*** Create a stream that either points to an external file pointer or an
internal memory area. ***/
create_stream(name,file,ex,in,rw,owner)
char *name,*file;
int ex,in,rw;
struct process *owner;
{
struct streams *st;
if ((st=get_stream(name))!=NULL) return OK;
if ((st=(struct streams *)malloc(sizeof(struct streams)))==NULL)
return ERR_MALLOC;
if (first_stream==NULL) {
first_stream=st; st->prev=NULL;
}
else {
last_stream->next=st; st->prev=last_stream;
}
last_stream=st;
st->next=NULL;
st->external=ex;
st->internal=in;
st->device=0;
st->block=1;
st->con_sock=0;
st->echo=1;
st->locked=0;
st->rw=rw;
st->owner=owner;
st->filename=NULL;
if (file!=NULL) set_string(&st->filename,file);
st->name=NULL;
return set_string(&st->name,name);
}
/*** Destroy a stream entry. No return value as there's no error it can
give that we need to know about */
destroy_stream(st)
struct streams *st;
{
struct streams *st2;
if (st==first_stream) {
first_stream=st->next;
if (first_stream==NULL) last_stream=NULL;
else first_stream->prev=NULL;
}
else {
st->prev->next=st->next;
if (st==last_stream) last_stream=st->prev;
else st->next->prev=st->prev;
}
if (current_instream==st) current_instream=NULL;
if (current_outstream==st) current_outstream=NULL;
/* If external file descriptor is a file or socket then close it but only
if we don't have another process still using it (ie the process spawned or
was spawned as a child/orphan and is hence sharing the _unix_ descriptor) */
if (st->external>2) {
for(st2=first_stream;st2!=NULL;st2=st2->next)
if (st2->external==st->external) goto END;
close(st->external);
}
END:
free(st->name);
FREE(st->filename);
free(st);
}
/** Set the current input or output stream ***/
set_iostreams(out,name)
int out;
char *name;
{
struct streams *st;
int ret;
if ((st=get_stream(name))==NULL) return ERR_INVALID_STREAM;
if (out) {
/* Can't write to a stream unless WRITE, READWRITE or APPEND */
if (st->rw==READ) return ERR_INVALID_STREAM_DIR;
if ((ret=set_variable("$out",NULL,name,1))!=OK) return ret;
current_outstream=st;
}
else {
/* Can't read from a stream if no the owner */
if (st->owner!=current_pcs) return ERR_INVALID_STREAM;
/* Can't read from a stream unless READ or READWRITE */
if (st->rw!=READ && st->rw!=READWRITE) return ERR_INVALID_STREAM_DIR;
if ((ret=set_variable("$in",NULL,name,1))!=OK) return ret;
current_instream=st;
}
return OK;
}
/*** Write to the current output stream ***/
write_stream(str)
char *str;
{
struct process *owner,*old_pcs;
char cnt[10],tmp[20],*str2;
int ret;
if (current_outstream==NULL) return ERR_INVALID_STREAM;
if (current_outstream->external!=-1) {
/* Replace colour commands with escape codes so user see's the colour
unless we're writing to a file or a process created connect socket
(ie as long as we're writing to STDOUT) */
if (current_outstream->filename==NULL && !current_outstream->con_sock) {
if ((ret=replace_colour_coms(str,&str2))!=OK) return ret;
/* EINTR means operation interrupted by a signal */
errno=0;
do {
ret=write(current_outstream->external,str2,strlen(str2));
} while(ret==-1 && errno==EINTR);
}
else {
errno=0;
do {
ret=write(current_outstream->external,str,strlen(str));
} while(ret==-1 && errno==EINTR);
}
if (ret==-1) {
if (!current_outstream->con_sock &&
is_sock_stream(current_outstream)) {
/* Socket is controlling port socket which has closed
remotely. Theres nothing we can do about it so kill
process */
current_pcs->status=EXITING; return OK;
}
return ERR_WRITE_FAILED;
}
return OK;
}
/* Internal streams. If string is nothing more than a single newline
then don't bother sending it. There is only 1 type of internal stream
at the moment which is MESG_Q */
if (current_outstream->internal!=MESG_Q) return ERR_UNSET_STREAM;
if (strlen(str)==1 && *str=='\n') return OK;
/* Write our pid and name onto other processes queue as id first then write
message and end marker. Make sure we don't have 255 in the message string
first though. */
str2=str;
while(*str2) if ((u_char)*(str2++)==255) return ERR_ILLEGAL_CHAR;
owner=current_outstream->owner;
sprintf(tmp,"%d\n",current_pcs->pid);
append_string(&(owner->mesg_q),tmp);
append_string(&(owner->mesg_q),str);
sprintf(tmp,"%c",255);
append_string(&(owner->mesg_q),tmp);
/* This is an ugly fudge but it works. Don't need to save owner state
as no var pointers will be changed, only a var value. */
old_pcs=current_pcs;
save_process_state(old_pcs,0);
load_process_state(owner);
owner->mesg_cnt++;
sprintf(cnt,"%d",owner->mesg_cnt);
if ((ret=set_variable("$mesg_cnt",NULL,cnt,1))!=OK) return ret;
load_process_state(old_pcs);
return OK;
}
/*** Go through string an replace colour/terminal commands with ansi escape
codes ***/
replace_colour_coms(str,str2)
char *str,**str2;
{
char *s,*s2;
int com,got,ncnt,len,col,addres;
s=str;
if (col=current_pcs->colour) {
/* Double the size of the input string will be enough though we need a
minimum size so reset codes will fit in so count num of newlines. */
ncnt=0;
while(*s) if (*s++=='\n') ++ncnt;
len=(strlen(str)+1)*2+ncnt*5+5; /* +5 so have minimum size */
}
else len=strlen(str)+1; /* No colour codes so same length or less */
if ((*str2=(char *)malloc(len))==NULL) return ERR_MALLOC;
/* Go through string */
s=str;
s2=*str2;
addres=0;
while(*s) {
addres=0;
if (*s=='\n') {
if (col) {
addres=1;
memcpy(s2,"\033[0m\n",5); /* newline reset */
s2+=5;
}
else *s2++='\n';
++s;
continue;
}
if (*s=='/' && *(s+1)=='~') { ++s; continue; }
if (*s=='~') {
if (s>str && *(s-1)=='/') {
*s2++='~'; ++s; continue;
}
/* Ok , we've perhaps got a colour command */
++s; got=0;
for(com=0;com<NUM_COLS;++com) {
if (!strncmp(s,colcom[com],2)) {
if (col) {
memcpy(s2,colcode[com],strlen(colcode[com]));
s2+=strlen(colcode[com]);
}
s+=2; got=1;
break;
}
}
if (got) continue;
*s2++='~';
}
*s2++=*s++;
}
if (col && !addres) memcpy(s2,"\033[0m\0",5); /* end of line reset */
else *s2='\0';
return OK;
}
/*** Read from the current input stream and put data in current processes
input buffer. ***/
read_stream()
{
int rlen,ex,pos,readit,ret,is_sock;
struct timeval tm;
fd_set mask;
u_char c,*mesg,*tmp;
char cnt[10];
if (current_instream==NULL) return ERR_INVALID_STREAM;
current_pcs->eof=0;
/* External streams */
if (current_instream->external!=-1) {
ex=current_instream->external;
is_sock=is_sock_stream(current_instream);
/* Get input from a non-blocking select (done by setting timeval
to zero) */
c='\0';
pos=0;
rlen=0;
readit=0;
tm.tv_sec=0;
tm.tv_usec=0;
FD_ZERO(&mask);
FD_SET(ex,&mask);
errno=0;
do { select(FD_SETSIZE,&mask,0,0,&tm); } while(errno==EINTR);
/* See if we got anything. We read data into text buffer because
calling append_string for each character read would be horribly
slow */
if (!FD_ISSET(ex,&mask)) return set_variable("$eof",NULL,"0",1);
/* EINTR means read returned due to a signal interrupt */
errno=0;
while((rlen=read(ex,&c,1))>0 || (rlen==-1 && errno==EINTR)) {
readit=1;
if (c=='\r') continue;
if (c=='\n') break;
text[pos]=c;
if (++pos==ARR_SIZE-1) {
text[ARR_SIZE-1]='\0';
append_string(¤t_pcs->input_buff,text);
pos=0;
}
}
text[pos]='\0';
/* If 1st char is 255 then its a telopt control code; ignore */
if ((u_char)text[0]==255 && is_sock) return OK;
/* Its a controlling port socket which has been closed so
kill process */
if (!readit && !current_instream->con_sock && is_sock) {
current_pcs->status=EXITING; return OK;
}
append_string(¤t_pcs->input_buff,text);
/* If we've hit end of the line unsuspend process. */
if (c=='\n') current_pcs->status=RUNNING;
/* If select said there was something to read and read returned 0 or
-1 then we've hit the end of the file or theres no data */
if (rlen<1) {
/* If its socket which might be talking to a char mode
client see if we've really finished. */
if (c && is_sock) return set_variable("$eof",NULL,"0",1);
current_pcs->eof=1;
/* unsuspend process whether we've hit a newline or not */
current_pcs->status=RUNNING;
return set_variable("$eof",NULL,"1",1);
}
return set_variable("$eof",NULL,"0",1);
}
/* Internal stream. Only the one type (MESG_Q) at the moment */
if (current_instream->internal!=MESG_Q) return ERR_UNSET_STREAM;
/* Read data off message q onto input buffer. This is an inefficient
method but it allows compatability with external input using the
input buffer at the same time. */
if ((mesg=(u_char *)current_pcs->mesg_q)==NULL) return OK;
current_pcs->status=RUNNING; /* data on queue,unsuspend process */
/* Go along queue and read one line into input buffer. We should never
hit a '\0' before a '\n' because of the way write_stream works but
just to be sure check in while() anyway */
pos=0;
while(*mesg && *mesg!='\n' && *mesg!=255) {
text[pos]=*mesg;
if (++pos==ARR_SIZE) {
text[ARR_SIZE-1]='\0';
append_string(¤t_pcs->input_buff,text);
pos=0;
}
++mesg;
}
text[pos]='\0';
append_string(¤t_pcs->input_buff,text);
/* Have we reached end of an individual message? */
if (*mesg==255) {
current_pcs->mesg_cnt--; /* end marker */
sprintf(cnt,"%d",current_pcs->mesg_cnt);
if ((ret=set_variable("$mesg_cnt",NULL,cnt,1))!=OK) return ret;
}
/* Have we reached end of the queue itself? */
if (!*mesg || !*(mesg+1)) {
current_pcs->eof=1;
free(current_pcs->mesg_q);
current_pcs->mesg_q=NULL;
return set_variable("$eof",NULL,"1",1);
}
/* Still data on queue , shift start of data down. */
++mesg; /* To skip terminating '\n' */
if ((tmp=(u_char *)malloc(strlen(mesg)+1))==NULL)
return ERR_MALLOC;
strcpy(tmp,mesg);
free(current_pcs->mesg_q);
current_pcs->mesg_q=(char *)tmp;
return set_variable("$eof",NULL,"0",1);
}
/*** Seek along the current input stream ***/
seek_stream(com_num,whence,offset)
int com_num,whence,offset;
{
u_char *mesg,*m;
char cnt[10],c;
int lines,rlen,ex,mcnt;
if (current_instream==NULL) return ERR_INVALID_STREAM;
/* External stream */
if ((ex=current_instream->external)!=-1) {
if (com_num==CSEEK) {
if (lseek(ex,offset,whence)==-1) return push_rstack("0");
return push_rstack("1");
}
/* LSEEK. Return to start of file if SEEK_SET */
if (whence==SEEK_SET && lseek(ex,0,SEEK_SET)==-1)
return push_rstack("0"); /* Can't return to start */
if (!offset) return push_rstack("1");
/* Count lines */
lines=0;
errno=0;
while((rlen=read(ex,&c,1))>0 || (rlen==-1 && errno==EINTR)) {
if (c=='\n') ++lines;
if (lines==offset) return push_rstack("1");
}
return push_rstack("0");
}
if (current_instream->internal!=MESG_Q) return ERR_INVALID_STREAM;
/* Whence is ignored here because the current position will always be
the start. Can't seek backwards or on an empty queue or off the end
of the queue. */
if (!offset) return push_rstack("1");
mesg=(u_char *)current_pcs->mesg_q;
if (com_num==LSEEK) {
if (offset<0 || mesg==NULL) return push_rstack("0");
/* Go through lines */
lines=0; mcnt=0;
while(*mesg && lines<offset) {
if (*mesg=='\n') lines++;
else if (*mesg==255) { lines++; mcnt++; }
mesg++;
}
if (lines!=offset || !*(mesg+1)) return push_rstack("0");
if (*(mesg+1)==255) { mcnt++; mesg++; }
/* Set queue */
if ((m=(u_char *)malloc(strlen(mesg)+1))==NULL)
return ERR_MALLOC;
strcpy(m,mesg);
free(current_pcs->mesg_q);
current_pcs->mesg_q=(char *)m;
current_pcs->mesg_cnt-=mcnt;
sprintf(cnt,"%d",current_pcs->mesg_cnt);
set_variable("$mesg_cnt",NULL,cnt,1);
return push_rstack("1");
}
/* CSEEK */
if (offset<0 || mesg==NULL || offset>=strlen(mesg)) return push_rstack("0");
offset+=(*(mesg+offset)=='\n'); /* Don't want to start next mesg on a \n */
if ((mesg=(u_char *)malloc(strlen(mesg)+1-offset))==NULL)
return ERR_MALLOC;
strcpy(mesg,current_pcs->mesg_q+offset);
/* See how messages we've skipped */
m=(u_char *)current_pcs->mesg_q;
while(offset--) {
if (*m==255) {
current_pcs->mesg_cnt--; /* end marker */
sprintf(cnt,"%d",current_pcs->mesg_cnt);
set_variable("$mesg_cnt",NULL,cnt,1);
}
}
free(current_pcs->mesg_q);
/* Have we reached end of the queue itself? */
if (!*mesg || !*(mesg+1)) {
current_pcs->eof=1;
current_pcs->mesg_q=NULL;
set_variable("$eof",NULL,"1",1);
return push_rstack("1");
}
current_pcs->mesg_q=(char *)mesg;
return push_rstack("1");
}
/*** See if stream is a socket stream or not ***/
is_sock_stream(st)
struct streams *st;
{
if (st!=NULL &&
st->external>2 &&
!st->device &&
st->filename==NULL &&
!isinteger(st->name,0)) return 1;
return 0;
}
/*****************************************************************************
MISCELLANIOUS FUNCTIONS
Miscellanious code which doesn't really belong anywhere else.
*****************************************************************************/
/*** Print uptime in system log for when system has stopped ***/
uptime()
{
int days,hours,mins,secs;
secs=(int)(time(0)-boottime);
days=secs/86400; secs%=86400;
hours=secs/3600; secs%=3600;
mins=secs/60; secs%=60;
write_syslog("Uptime: %d days, %d hours, %d mins, %d secs.",days,hours,mins,secs);
}
/*** Return a string containing the time and date ***/
char *timestr()
{
static char str[20];
struct tm *tms;
time_t tm_num;
/* Set up the structure */
time(&tm_num);
tms=localtime(&tm_num);
sprintf(str,"%02d/%02d, %02d:%02d:%02d",tms->tm_mday,tms->tm_mon+1,tms->tm_hour,tms->tm_min,tms->tm_sec);
return str;
}
/*** Write to the system log. This is a variadic function which saves having
to use sprintf all the time before calling it ***/
write_syslog(char *str, ...)
{
FILE *fp;
va_list args;
va_start(args,str);
if (syslog_file==NULL) {
printf("%s: ",timestr());
vprintf(str,args);
putchar('\n');
va_end(args);
return 1;
}
if (!(fp=fopen(syslog_file,"a"))) return 0; /* Can't do much about it */
fprintf(fp,"%s: ",timestr());
vfprintf(fp,str,args);
putc('\n',fp);
va_end(args);
fclose(fp);
return 1;
}
/*** Return 1 if a string is NULL or consists only of '\0'. This saves
doing this comparison everywhere ***/
isnull(str)
char *str;
{
return (str==NULL || *str=='\0');
}
/*** See if string is an integer, if neg set then allows negative numbers ***/
isinteger(str,neg)
char *str;
int neg;
{
char *s;
if ((s=str)==NULL) return 0;
while(*s) {
if (neg && s==str && *s=='-') ++s;
if (!isdigit(*s)) return 0;
++s;
}
if (s==str) return 0;
return 1;
}
/*** See if string is alphanumeric ***/
isalnumstr(str)
char *str;
{
char *s;
if ((s=str)==NULL) return 0;
while(*s) {
if (!isalnum(*s) && *s!='_' && *s!='.') return 0;
++s;
}
if (s==str) return 0;
return 1;
}
/*** Match a string with a wildcard pattern. Returns 1 or 0 ***/
wildmatch(str,pat)
char *str,*pat;
{
char *pat2,*str2,*pstart;
int ok;
if (!*pat) {
if (!*str) return 1; else return 0;
}
pstart=pat;
while(*str && *pat) {
switch(*pat) {
case '?': ++pat; break;
case '*':
/* Compare section from * in pat (up to next * or end) with
rest of str */
ok=1;
for(pat2=pat+1,str2=str+1;*pat2!='*';++pat2,++str2) {
if (*pat2=='?') continue;
if (*pat2!=*str2) { ok=0; break; }
if (!*str2 || !*pat2) break;
}
if (ok) { pat=pat2; str=str2-1; }
break;
default:
if (*str!=*pat) return 0;
++pat;
}
++str;
}
if (*str) return 0;
if (*pat && (*pat!='*' || pat!=pstart+(strlen(pstart)-1))) return 0;
return 1;
}
/*** Get the number of the command ***/
get_command_number(word)
char *word;
{
int i;
char *s;
s=text;
strcpy(text,word);
while(*s) { *s=tolower(*s); ++s; }
for(i=0;i<NUM_COMS;++i)
if (!strcmp(commands[i].command,text)) return i;
return -1;
}
/*** Give a string a value. The return value of this function is mostly not
checked simply because its called so often. The code would become a
complete mess if I checked it every time I used it. If we do run out of
memory we'll soon know about it anyway. ***/
set_string(strptr,value)
char **strptr,*value;
{
/* If we can fit new string into old don't free mem */
if (*strptr!=NULL && value!=NULL && strlen(value)>strlen(*strptr)) {
free(*strptr); *strptr=NULL;
}
if (value==NULL) {
FREE(*strptr); *strptr=NULL; return OK;
}
if (*strptr==NULL && (*strptr=(char *)malloc(strlen(value)+1))==NULL)
return ERR_MALLOC;
strcpy(*strptr,value);
return OK;
}
/*** Append a value onto a string. The return value of this is currently
never checked. ***/
append_string(strptr,value)
char **strptr,*value;
{
char *newstr;
int slen;
if (value==NULL) return OK; /* append nothing */
if (*strptr==NULL) slen=0; else slen=strlen(*strptr);
if ((newstr=(char *)malloc(slen+strlen(value)+1))==NULL) return ERR_MALLOC;
*newstr='\0';
if (*strptr!=NULL) {
strcpy(newstr,*strptr); free(*strptr);
}
strcat(newstr,value);
*strptr=newstr;
return OK;
}
/*** Compare 2 strings ***/
compare_strings(str1,str2)
char *str1,*str2;
{
if (str1==NULL && str2==NULL) return 0;
else {
if (str1==NULL) return (!strlen(str2) ? 0 : -1);
else if (str2==NULL) return (!strlen(str1) ? 0 : 1);
}
return strcoll(str1,str2);
}
/*** Exit function for when theres an error with a process ***/
error_exit(err,line)
int err,line;
{
sprintf(text,"ERROR: Process %d (%s): ",current_pcs->pid,current_pcs->name);
if (real_line==-1) write_syslog("%s%s.",text,error_mesg[err]);
else write_syslog("%s%s in file \"%s\" on line %d.",text,error_mesg[err],prog_word[current_pcs->pc].filename,line);
if (!max_errors || current_pcs->err_cnt<max_errors) return;
if (max_errors>1)
write_syslog("Process %d (%s) reached maximum error count, terminating...",current_pcs->pid,current_pcs->name);
current_pcs->status=EXITING;
current_pcs->exit_code=err;
process_exit();
}
/*** Create a file pathname using the root_path as appropriate ***/
char *create_path(path)
char *path;
{
static char fullpath[200];
if (*path=='/') {
/* If allowing full unix root path don't append our root path. */
if (allow_ur_path) {
strcpy(fullpath,path); return fullpath;
}
/* Don't include slash at start of path */
sprintf(fullpath,"%s%s",root_path,path+1);
return fullpath;
}
sprintf(fullpath,"%s%s",root_path,path);
return fullpath;
}
/*** Switch echoing to on for console and all devices when we exit in case
system died while prompting for a password etc. If echo was already off
when the system started tough shit. ***/
reset_echoing()
{
struct streams *st;
struct termio tio;
/* Reset stdin */
if (!be_daemon) {
ioctl(0,TCGETA,&tio);
tio.c_lflag |= ECHO;
ioctl(0,TCSETA,&tio);
}
/* Reset any devices */
for(st=first_stream;st!=NULL;st=st->next) {
if (st->device) {
ioctl(st->external,TCGETA,&tio);
tio.c_lflag |= ECHO;
ioctl(st->external,TCSETA,&tio);
}
}
}
/*****************************************************************************
Process load and parse functions
*****************************************************************************/
/*** Call the load and parse routines. ***/
process_setup(filename,argc,argv,com_num)
int argc,com_num;
char *filename,*argv[];
{
struct procedures *proc;
int ret;
incf=NULL;
if ((ret=init_process_globals())!=OK) return ret;
if ((ret=load_and_first_parse(filename,com_num))!=OK) return ret;
if ((ret=second_parse())!=OK) return ret;
if ((ret=third_parse())!=OK) return ret;
if ((ret=create_process_variables())!=OK) return ret;
/* Set up globals */
if ((ret=exec_process(0,1))!=OK) return ret;
/* Find program start */
for(proc=first_proc;proc!=NULL;proc=proc->next) {
if (!strcmp(proc->name,"main")) {
current_proc=proc;
if ((ret=push_pstack(proc))!=OK) return ret;
return setup_arg_vars(argc,argv);
}
}
real_line=-1;
return ERR_MAIN_PROC_MISSING;
}
/*** Initialise process variables ***/
init_process_globals()
{
memory_reserve=MEMORY_RESERVE;
if ((prog_word=(struct program *)malloc((memory_reserve+1)*sizeof(struct program)))==NULL)
return ERR_MALLOC;
num_words=0;
rstack_start=NULL;
rstack_ptr=NULL;
pstack_start=NULL;
pstack_ptr=NULL;
lstack_start=NULL;
lstack_ptr=NULL;
first_proc=NULL;
last_proc=NULL;
current_proc=NULL;
first_var=NULL;
last_var=NULL;
current_var=NULL;
first_loop=NULL;
last_loop=NULL;
current_loop=NULL;
first_label=NULL;
last_label=NULL;
current_instream=NULL;
current_outstream=NULL;
return OK;
}
/*** Load program words into prog_words structure and sort out operators.
This function is messy but that can't be helped. ***/
load_and_first_parse(file_prog,com_num)
char *file_prog;
int com_num;
{
char c,pathname[ARR_SIZE];
char *opstr="[]<>!="; /* The order is VITAL! */
int prog_line,got_word,brackets,ip,ret,ipos,i;
int word,tpos,in_string,in_rem,whitespace;
static struct {
FILE *fp;
char filename[100];
int real_line;
} incst[MAX_INCLUDE_LEVELS+1];
real_line=1;
prog_line=1;
got_word=0;
word=0;
tpos=0;
in_string=0;
in_rem=0;
brackets=0;
whitespace=1;
/* Initialise structure */
if (com_num!=IEXEC) strcpy(incst[0].filename,file_prog);
else strcpy(incst[0].filename,"<INLINE>");
incst[0].fp=NULL;
incst[0].real_line=1;
for(ipos=1;ipos<=MAX_INCLUDE_LEVELS;++ipos) {
incst[ipos].fp=NULL;
incst[ipos].filename[0]='\0';
incst[ipos].real_line=1;
}
ipos=0;
/* Open main process file if not IEXEC */
if (com_num!=IEXEC) {
sprintf(pathname,"%s%s",code_path,file_prog);
if (!(incst[0].fp=fopen(pathname,"r"))) {
real_line=-1; return ERR_CANT_OPEN_FILE_OR_DIR;
}
c=getc(incst[0].fp);
if (feof(incst[0].fp)) {
fclose(incst[0].fp); return ERR_UNEXPECTED_EOF;
}
}
else if (!(c=*file_prog)) return ERR_UNEXPECTED_EOF;
/* Go through file */
while(1) {
incf=incst[ipos].filename;
/* If we've overun reserved mem , realloc an increased amount */
if (word>=memory_reserve) {
memory_reserve+=MEMORY_RESERVE;
if ((prog_word=(struct program *)realloc(prog_word,(memory_reserve+1)*sizeof(struct program)))==NULL) {
ret=ERR_MALLOC; goto ERROR;
}
}
/* Deal with include files */
if (c=='&' && whitespace && !in_rem && !in_string) {
if (ipos==MAX_INCLUDE_LEVELS) {
ret=ERR_MAX_INCLUDE; goto ERROR;
}
incst[ipos].real_line=real_line;
/* get filename */
ip=0;
if (com_num!=IEXEC || ipos) c=getc(incst[ipos].fp);
else c=*++file_prog;
while(c>32 && c!=';') {
if ((com_num!=IEXEC || ipos) && feof(incst[ipos].fp))
break;
incst[ipos+1].filename[ip]=c; ip++;
if (com_num!=IEXEC || ipos) c=getc(incst[ipos].fp);
else c=*++file_prog;
}
if (!ip) { ret=ERR_SYNTAX; goto ERROR; }
incst[ipos+1].filename[ip]='\0';
++ipos;
if (!com_num && !qbm) {
printf(" ");
for(i=0;i<ipos;++i) putchar('>');
printf(" Loading include file \"%s\"\n",incst[ipos].filename);
}
sprintf(pathname,"%s%s",code_path,incst[ipos].filename);
if (!(incst[ipos].fp=fopen(pathname,"r"))) {
ret=ERR_CANT_OPEN_FILE_OR_DIR; --ipos; goto ERROR;
}
if (c=='\n') incst[ipos-1].real_line++;
real_line=1;
c=getc(incst[ipos].fp);
continue;
}
/* Deal with rem statements */
if (!in_rem && whitespace && c=='#' && !in_string) {
/* Fool it into thinking its the end of the line */
in_rem=1; c='\n'; real_line--;
}
else {
if (in_rem) {
if (c=='\n') { in_rem=0; real_line++; }
goto CONT;
}
}
/* Deal with char */
switch(c) {
case '\\':
if (com_num!=IEXEC || ipos) c=getc(incst[ipos].fp);
else c=*++file_prog;
if (c=='\n') { real_line++; goto CONT; }
if (!c || ((com_num!=IEXEC || ipos) && feof(incst[ipos].fp))) {
ret=ERR_UNEXPECTED_EOF; goto ERROR;
}
if (com_num!=IEXEC || ipos) ungetc(c,incst[ipos].fp);
else file_prog--;
whitespace=0;
text[tpos]='\\';
if (++tpos>ARR_SIZE) { ret=ERR_LINE_TOO_LONG; goto ERROR; }
goto CONT;
case '\0':
case '\n':
if (in_string) { ret=ERR_UNTERMINATED_STRING; goto ERROR; }
if (brackets) { ret=ERR_MISSING_BRACKET; goto ERROR; }
case ';':
case ' ':
case TAB:
/* End of word/line */
if (in_string) break;
whitespace=1;
if (tpos) {
text[tpos]='\0';
prog_word[word].word=NULL;
set_string(&prog_word[word].word,text);
prog_word[word].filename=NULL;
set_string(&prog_word[word].filename,incst[ipos].filename);
prog_word[word].equa=NULL;
prog_word[word].equacnt=0;
prog_word[word].real_line=real_line;
prog_word[word].prog_line=prog_line;
prog_word[word].op_num=-1;
word++;
}
if (got_word && (c=='\0' || c=='\n' || c==';')) {
prog_line++; got_word=0;
}
if (c=='\n' || !c) real_line++;
tpos=0;
goto CONT;
case '[': brackets++;
case ']': if (c==']') brackets--; /* need if in case of fall through */
case '<':
case '>':
case '!':
case '=':
/* Single character operators */
if (in_string) break;
whitespace=0;
if (tpos) {
/* Save word up to current operator */
text[tpos]='\0';
prog_word[word].word=NULL;
set_string(&prog_word[word].word,text);
prog_word[word].filename=NULL;
set_string(&prog_word[word].filename,incst[ipos].filename);
prog_word[word].equa=NULL;
prog_word[word].equacnt=0;
prog_word[word].real_line=real_line;
prog_word[word].prog_line=prog_line;
prog_word[word].op_num=-1;
word++;
}
else {
/* Check for ,'<=','>=' and '!=' operators */
if (word && c=='=') {
switch(prog_word[word-1].word[0]) {
case '!':
set_string(&prog_word[word-1].word,"!=");
prog_word[word-1].op_num=NOT_EQUAL;
tpos=0; goto CONT;
case '<':
set_string(&prog_word[word-1].word,"<=");
prog_word[word-1].op_num=LESS_THAN_EQUALS;
tpos=0; goto CONT;
case '>':
set_string(&prog_word[word-1].word,">=");
prog_word[word-1].op_num=GREATER_THAN_EQUALS;
tpos=0; goto CONT;
}
}
}
sprintf(text,"%c",c);
prog_word[word].word=NULL;
set_string(&prog_word[word].word,text);
prog_word[word].filename=NULL;
set_string(&prog_word[word].filename,incst[ipos].filename);
prog_word[word].equa=NULL;
prog_word[word].equacnt=0;
prog_word[word].real_line=real_line;
prog_word[word].prog_line=prog_line;
prog_word[word].op_num=(int)strchr(opstr,c)-(int)opstr;
word++; tpos=0;
goto CONT;
case '"':
/* Check if we're trying to print a quote using \" in string */
if (in_string && tpos && text[tpos-1]=='\\') break;
in_string=!in_string;
break;
default: whitespace=0;
}
text[tpos]=c;
if (++tpos>ARR_SIZE) { ret=ERR_LINE_TOO_LONG; goto ERROR; }
CONT:
got_word=1;
if (com_num!=IEXEC || ipos) {
c=getc(incst[ipos].fp);
if (feof(incst[ipos].fp)) {
if (!ipos) break;
fclose(incst[ipos].fp);
ipos--;
real_line=incst[ipos].real_line;
if (com_num!=IEXEC || ipos) {
c=getc(incst[ipos].fp);
if (feof(incst[ipos].fp)) break;
}
else c=*++file_prog;
}
}
else {
/* Check for \0 first so that it will have gone round loop
once to make EOF of inline code */
if (!c) break;
c=*++file_prog;
}
}
if (in_string || in_rem) { ret=ERR_UNEXPECTED_EOF; goto ERROR; }
if (com_num!=IEXEC) fclose(incst[0].fp);
/* Terminate array with dummy entry */
prog_word[word].word=NULL;
prog_word[word].filename=NULL;
prog_word[word].equa=NULL;
prog_word[word].equacnt=0;
prog_word[word].com_num=-1;
prog_word[word].op_num=-1;
prog_word[word].real_line=0;
prog_word[word].prog_line=0;
num_words=word;
return OK;
ERROR:
if (com_num!=IEXEC) fclose(incst[0].fp);
for(i=1;i<=ipos;++i) fclose(incst[ipos].fp);
return ret;
}
/*** This sets up the command variables in prog_words, makes sure commands
are inside a procedure and checks the bracket count ***/
second_parse()
{
int i,j,brackets1,brackets2,in_proc;
int prog_line,com_num,prev_com_num;
char *w;
brackets1=0;
prog_line=0;
in_proc=0;
prev_com_num=-1;
/* go through word list and pick out commands */
for(i=0;i<num_words;++i) {
w=prog_word[i].word;
real_line=prog_word[i].real_line;
incf=prog_word[i].filename;
if (w[0]=='[') {
brackets1++;
if (i && prog_word[i-1].word[0]=='[') return ERR_SYNTAX;
}
if (w[0]==']') brackets1--;
if ((com_num=prog_word[i].com_num=get_command_number(w))==-1) continue;
prog_line=prog_word[i].prog_line;
/* If we've got here then we're dealing with a command */
if (i) prev_com_num=prog_word[i-1].com_num;
if (prev_com_num!=-1 &&
prev_com_num!=ALIAS &&
prog_line==prog_word[i-1].prog_line) return ERR_SYNTAX;
switch(com_num) {
case PROC : in_proc=1; break;
case ENDPROC: in_proc=0; break;
case ALIAS :
case VAR :
case SET :
case SHARE :
case UNSHARE: break;
default :
if (!in_proc && prev_com_num!=ALIAS)
return ERR_UNEXPECTED_COMMAND;
}
/* find where command ends */
brackets2=1;
for(j=i+1;j<num_words;++j) {
w=prog_word[j].word;
if (w[0]=='[') brackets2++;
if (w[0]==']') brackets2--;
/* See if terminating bracket found */
if (brackets1 && !brackets2 && w[0]==']') {
prog_word[i].end_pos=j-1; break;
}
if (prog_word[j].prog_line!=prog_line) {
prog_word[i].end_pos=j-1; break;
}
}
prog_word[i].end_pos=j-1;
}
if (in_proc) return ERR_UNEXPECTED_EOF;
return OK;
}
/*** Set up aliases, procs, loops, switches and label lists ***/
third_parse()
{
int pc,com_num,ret;
for(pc=0;pc<num_words;++pc) {
com_num=prog_word[pc].com_num;
real_line=prog_word[pc].real_line;
incf=prog_word[pc].filename;
switch(com_num) {
case ALIAS :
if ((ret=set_aliases(pc))!=OK) return ret;
continue;
case WHILE :
case FOR :
case FOREACH:
case DO :
case CHOOSE :
if ((ret=create_loop_entry(com_num,pc))!=OK) return ret;
continue;
case LABEL :
if ((ret=create_label_entry(pc))!=OK) return ret;
continue;
case PROC :
if (current_proc) return ERR_UNEXPECTED_COMMAND;
if ((ret=create_procedure_entry(pc))!=OK) return ret;
continue;
case ENDPROC:
if (current_proc==NULL) return ERR_UNEXPECTED_COMMAND;
current_proc=NULL;
}
}
return OK;
}
/*** Set up all the internal process $xxx interpreter variables and also set
up some default stream stuff. ***/
create_process_variables()
{
struct procedures *proc;
int ret,flags,w;
char pvar[20],pid[10],port[6];
flags=READONLY | ARRAY;
/* Create program code array. Each entry will have multiple elements depending
on what the program word consists of, but the program word line number (not
the real file line number) will always be the last one. */
if ((ret=create_variable("$prog",NULL,NULL,flags,1))!=OK) return ret;
w=0;
while(prog_word[w].prog_line) {
sprintf(pvar,"$prog:\"%d\"",w+1);
sprintf(text,"%s %d %d %s",prog_word[w].word,prog_word[w].prog_line,prog_word[w].real_line,prog_word[w].filename);
if ((ret=set_variable(pvar,NULL,text,1))!=OK) return ret;
++w;
}
/* Create procedure return value array and result var. $result is set after
every procedure call but $proc stores the last returned values of each
individual procedure for later reference so you don't have to check $result
after each procedure call. */
if ((ret=create_variable("$proc",NULL,NULL,flags,1))!=OK) return ret;
for(proc=first_proc;proc!=NULL;proc=proc->next) {
sprintf(text,"$proc:\"%s\"",proc->name);
if ((ret=set_variable(text,NULL,NULL,1))!=OK) return ret;
}
if ((ret=create_variable("$result",NULL,NULL,READONLY,1))!=OK) return ret;
/* Process name */
if ((ret=create_variable("$name",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=set_variable("$name",NULL,current_pcs->name,1))!=OK) return ret;
/* Process filename */
if ((ret=create_variable("$filename",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=set_variable("$filename",NULL,current_pcs->filename,1))!=OK) return ret;
/* Parent process id */
if (current_pcs->parent!=NULL) sprintf(pid,"%d",current_pcs->parent->pid);
else strcpy(pid,"0");
if ((ret=create_variable("$ppid",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=set_variable("$ppid",NULL,pid,1))!=OK) return ret;
/* Process id */
sprintf(pid,"%d",current_pcs->pid);
if ((ret=create_variable("$pid",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=set_variable("$pid",NULL,pid,1))!=OK) return ret;
/* No. of messages on message queue */
if ((ret=create_variable("$mesg_cnt",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=set_variable("$mesg_cnt",NULL,"0",1))!=OK) return ret;
/* Interrupt vars */
if ((ret=create_variable("$int_mesg",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=create_variable("$int_enabled",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=set_variable("$int_enabled",NULL,"1",1))!=OK) return ret;
/* Last error trapped by "trap" command */
if ((ret=create_variable("$last_error",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=set_variable("$last_error",NULL,"0",1))!=OK) return ret;
/* End of file flag */
if ((ret=create_variable("$eof",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=set_variable("$eof",NULL,"0",1))!=OK) return ret;
/* Current input and output streams */
if ((ret=create_variable("$in",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=create_variable("$out",NULL,NULL,READONLY,1))!=OK) return ret;
/* This is set to 0 if a print command failed on a non-blocking stream else
is set to 1 */
if ((ret=create_variable("$print_ok",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=set_variable("$print_ok",NULL,"0",1))!=OK) return ret;
/* Variable set by optional break and continue command arguments */
if ((ret=create_variable("$break",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=create_variable("$cont",NULL,NULL,READONLY,1))!=OK) return ret;
/* Network vars */
if ((ret=create_variable("$site",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=set_variable("$site",NULL,current_pcs->site,1))!=OK) return ret;
sprintf(port,"%d",current_pcs->local_port);
if ((ret=create_variable("$lport",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=set_variable("$lport",NULL,port,1))!=OK) return ret;
sprintf(port,"%d",current_pcs->remote_port);
if ((ret=create_variable("$rport",NULL,NULL,READONLY,1))!=OK) return ret;
if ((ret=set_variable("$rport",NULL,port,1))!=OK) return ret;
/* Setup standard IO stuff. Default to unix terminal stdin & out. */
if ((ret=create_stream("STDIN",NULL,0,-1,READ,current_pcs))!=OK) return ret;
if ((ret=create_stream("STDOUT",NULL,1,-1,WRITE,current_pcs))!=OK) return ret;
/* Create message queue stream. The dummy stream name MESG_Q will be
mapped onto the processes pid named stream by get_stream() when a process
uses it */
if ((ret=create_stream(pid,NULL,-1,MESG_Q,READWRITE,current_pcs))!=OK) return ret;
/* Set default input and output */
set_iostreams(INPT,"STDIN");
set_iostreams(OUTPT,"STDOUT");
return OK;
}
/*** Go through words and set aliases. If the alias command is in a proc then
only set them _within_ the procedure ***/
set_aliases(pc)
int pc;
{
char *ops[]={
"<",">","!","=","<=",">=","!="
};
char *wto,*wfrom;
int pc2,i;
pc2=prog_word[pc].end_pos+1;
if (pc2-pc!=3) return ERR_SYNTAX;
wto=prog_word[pc+1].word;
wfrom=prog_word[pc+2].word;
for(;pc2<num_words;++pc2) {
if (current_proc && prog_word[pc2].com_num==ENDPROC) return OK;
if (!strcmp(prog_word[pc2].word,wfrom)) {
set_string(&prog_word[pc2].word,wto);
/* See if 'to' word is a command */
if ((prog_word[pc2].com_num=get_command_number(wto))!=-1) {
for(i=pc2+1;i<num_words;++i) {
if (prog_word[i].word[0]==']' ||
prog_word[i].prog_line!=prog_word[pc2].prog_line) break;
}
prog_word[pc2].end_pos=i-1;
continue;
}
/* See if its an operator (except for square brackets) */
for(i=0;i<7;++i) {
if (!strcmp(wto,ops[i])) {
prog_word[pc2].op_num=i+2; break;
}
}
}
}
return OK;
}
/*** Create an entry in the loops linked list ***/
create_loop_entry(type,pos)
int type,pos;
{
struct loops_choose *new;
int p,loop_cnt,len;
int end_word,com_num;
real_line=prog_word[pos].real_line;
/* Check syntax */
len=prog_word[pos].end_pos - pos;
switch(type) {
case DO:
if (len>0) return ERR_SYNTAX;
break;
case CHOOSE:
case WHILE :
if (len<1) return ERR_SYNTAX;
break;
default:
if (len<3) return ERR_SYNTAX;
}
if ((new=(struct loops_choose *)malloc(sizeof(struct loops_choose)))==NULL)
return ERR_MALLOC;
if (first_loop==NULL) first_loop=new;
else last_loop->next=new;
last_loop=new;
new->type=type;
new->for_to=0;
new->foreach_pos=-1;
new->foreach_var=NULL;
new->start_pos=pos;
new->proc=current_proc;
new->next=NULL;
new->copy=NULL;
/* find end of this loop */
switch(type) {
case WHILE : end_word=WEND; break;
case FOR : end_word=NEXT; break;
case FOREACH: end_word=NEXTEACH; break;
case DO : end_word=UNTIL; break;
case CHOOSE : end_word=CHOSEN;
}
loop_cnt=0;
/* Find end of loop */
for(p=pos+1;p<num_words;++p) {
com_num=prog_word[p].com_num;
if (com_num==ENDPROC) break;
if (com_num==type) ++loop_cnt;
if (!loop_cnt && com_num==end_word) {
/* Make sure no crap follows loop terminator */
if (end_word!=UNTIL && prog_word[p].end_pos - p >0) {
real_line=prog_word[p].real_line;
return ERR_SYNTAX;
}
new->end_pos=p;
return OK;
}
if (com_num==end_word) --loop_cnt;
}
real_line=prog_word[pos].real_line;
return ERR_UNTERMINATED_LOOP;
}
/*** Create an entry in the labels linked list ***/
create_label_entry(pos)
int pos;
{
struct labels *label;
char *w;
/* Check syntax */
if (prog_word[pos].end_pos - pos!=1) return ERR_SYNTAX;
w=prog_word[pos+1].word;
if (*w=='"') push_rstack_qstr(w);
else {
if (isinteger(w,0)) push_rstack(w);
else return ERR_SYNTAX;
}
/* see if label already used */
for(label=first_label;label!=NULL;label=label->next) {
if (!strcmp(label->name,rstack_ptr->value)) return ERR_DUPLICATE_LABEL;
}
if ((label=(struct labels *)malloc(sizeof(struct labels)))==NULL)
return ERR_MALLOC;
if (first_label==NULL) first_label=label;
else last_label->next=label;
last_label=label;
label->next=NULL;
label->pos=pos;
label->proc=current_proc;
label->name=NULL;
return set_string(&label->name,rstack_ptr->value);
}
/*** Create an entry in the procedure linked list ***/
create_procedure_entry(pos)
int pos;
{
struct procedures *proc;
char *name;
if (prog_word[pos].end_pos - pos<1) return ERR_SYNTAX;
name=prog_word[pos+1].word;
if (!isalnumstr(name)) return ERR_INVALID_PROCNAME;
/* See if name already used */
for(proc=first_proc;proc!=NULL;proc=proc->next) {
if (!strcmp(name,proc->name)) return ERR_DUPLICATE_PROCNAME;
}
if ((proc=(struct procedures *)malloc(sizeof(struct procedures)))==NULL)
return ERR_MALLOC;
if (first_proc==NULL) first_proc=proc;
else last_proc->next=proc;
last_proc=proc;
current_proc=proc;
proc->copy=NULL; /* Only used during process spawning */
proc->next=NULL;
proc->start_pos=pos;
proc->ei_di_int=0;
proc->old_int=0;
/* Set proc name */
proc->name=NULL;
return set_string(&proc->name,name);
}
/*****************************************************************************
CREATE, DESTROY, SET AND GET VARIABLES FUNCTIONS
*****************************************************************************/
/*** Create an entry in the variables linked list. No values are set. Proc
is only needed for when we destroy it but we can't have a global and
local with the same name anyway. ***/
create_variable(name,proc,refvar,flags,sys)
char *name;
struct procedures *proc;
struct vars *refvar;
int flags,sys;
{
struct vars *var;
/* Check its a valid name unless its a SYS variable */
if (!*name || isinteger(name,1) || (!sys && !isalnumstr(name)))
return ERR_INVALID_VAR;
/* See if var already exists. If its a static it may well do in which case
we just ok it. */
for(var=first_var;var!=NULL;var=var->next) {
if (!strcmp(var->name,name) && (var->proc==proc || var->proc==NULL)) {
if ((var->flags & STATIC) && (flags & STATIC)) return OK;
return ERR_VAR_ALREADY_EXISTS;
}
}
if ((var=(struct vars *)malloc(sizeof(struct vars)))==NULL)
return ERR_MALLOC;
if (first_var==NULL) {
first_var=var; var->prev=NULL;
}
else {
last_var->next=var; var->prev=last_var;
}
last_var=var;
current_var=var;
var->copy=NULL; /* Only used during process spawning */
var->proc=proc;
var->refvar=refvar;
var->flags=flags;
var->value=NULL;
var->arr=NULL;
var->next=NULL;
var->name=NULL;
return set_string(&var->name,name);
}
/*** Destroy all non-static variables and formal parameters in the given
procedure when we exit it. I don't need to do this , I could just set
the non-static ones to NULL but this'll save a lot of memory in a multi-
process enviroment. ***/
destroy_proc_variables(proc)
struct procedures *proc;
{
struct vars *var,*varnext;
struct array *arr,*arr2;
for(var=first_var;var!=NULL;var=varnext) {
varnext=var->next;
if (var->proc==proc && !(var->flags & STATIC)) {
if (var->arr!=NULL) {
/* Clear out the array */
for(arr=var->arr;arr!=NULL;arr=arr2) {
arr2=arr->next;
free(arr->subscript);
FREE(arr->value);
free(arr);
}
}
free(var->name);
FREE(var->value);
if (var->prev!=NULL) var->prev->next=var->next;
if (var->next!=NULL) var->next->prev=var->prev;
if (var==first_var) first_var=var->next;
if (var==last_var) last_var=var->prev;
free(var);
}
}
return OK;
}
/*** Set variable value, decoding array subscript if necessary ***/
set_variable(name,proc,value,force)
char *name,*value;
struct procedures *proc;
int force; /* Force it to write to a read only var */
{
struct process *pcs,*old;
struct vars *var;
char *subscript,*tmp,*c,*start;
int ret,name_len,sub_type,i,shared;
sub_type=0;
subscript=NULL;
name_len=strlen(name);
/* See if we're accessing remote shared variable */
shared=0;
c=name;
while(*c) {
if (*c==':' || *c=='#' || *c=='?') break;
if (*c=='.') { shared=1; break; }
++c;
}
if (shared) {
*c='\0';
if (!strlen(name)) {
*c='.'; return ERR_SYNTAX;
}
if (isinteger(name,0)) {
if ((pcs=get_process(atoi(name)))==NULL) {
*c='.'; return ERR_NO_SUCH_PROCESS;
}
}
else {
if ((ret=get_variable(name,proc))!=OK) {
*c='.'; return ret;
}
if ((pcs=get_process(atoi(rstack_ptr->value)))==NULL) {
*c='.'; return ERR_NO_SUCH_PROCESS;
}
}
*c='.';
start=name;
name=c+1;
if (!strlen(name)) return ERR_SYNTAX;
name_len=strlen(name);
old=current_pcs;
save_process_state(old,0);
load_process_state(pcs);
}
/* Find the beginning of the subscript after ':' */
if ((subscript=(char *)strchr(name,':'))!=NULL) {
name_len=(int)(subscript-name); subscript++;
}
if ((tmp=(char *)strchr(name,'#'))!=NULL) {
if (subscript==NULL || tmp<subscript) {
name_len=(int)(tmp-name);
subscript=++tmp;
sub_type=1;
}
}
if ((tmp=(char *)strchr(name,'?'))!=NULL) {
if (subscript==NULL || tmp<subscript) {
name_len=(int)(tmp-name);
subscript=++tmp;
sub_type=2;
}
}
/* Go through backwards so we encounter local vars first. If no local
variable found try system variable. */
for(i=0;i<2;++i) {
for(var=last_var;var!=NULL;var=var->prev) {
if (!strncmp(var->name,name,name_len) &&
strlen(var->name)==name_len &&
(var->proc==proc || var->proc==NULL)) goto FOUND;
}
if (shared) break;
if (!i) {
old=current_pcs;
save_process_state(old,0);
load_process_state(first_pcs);
}
}
load_process_state(old);
return ERR_UNDEF_VAR;
FOUND:
/* Load old process back , "var" will be unaffected */
if (i) load_process_state(old);
if (shared) {
name=start;
load_process_state(old);
if (!(var->flags & SHARED)) return ERR_VAR_NOT_SHARED;
}
current_var=var;
/* If variable is reference var go back until we find variable pointed to.
We loop here as a pass by reference could be referencing another pass by
reference and so on */
while(var->refvar!=NULL) var=var->refvar;
if ((var->flags & READONLY) && !force) return ERR_VAR_IS_READONLY;
if (subscript==NULL) {
if (var->flags & ARRAY) return set_array_by_list(var,proc,value);
else return set_string(&var->value,value);
}
if (!(var->flags & ARRAY)) return ERR_VAR_IS_NOT_ARRAY;
return set_array(var,subscript,sub_type,proc,value);
}
/*** Set an array using an input list eg "hello cruel world". "hello" would
become element 1 , "cruel" element 2 and so on. Any subscripts already
in the array will be preserved *if* their slot is needed. If no slot
already exists a number subscript is given to it. ***/
set_array_by_list(var,proc,value)
struct vars *var;
struct procedures *proc;
char *value;
{
struct array *arr,*arrnext,*arrlast;
char *s,*s2,c;
int i,ret,arrind;
s=value;
arr=var->arr;
arrind=1;
/* Repopulate array */
while(value && 1) {
/* Find beginning of element in list */
while(*s<33 && *s) ++s;
if (!*s) break;
/* Find end of element */
s2=s;
while(*s2>32) ++s2;
c=*s2; *s2='\0';
/* Find current array struct */
arr=var->arr;
for(i=1;i<arrind && arr;++i) arr=arr->next;
/* Set array element. */
if (arr) sprintf(text2,"\"%s\"",arr->subscript);
else sprintf(text2,"\"%d\"",arrind);
if ((ret=set_array(var,text2,0,proc,s))!=OK) return ret;
/* Set for next loop */
arrind++;
*s2=c; s=s2;
}
if (arr==NULL) return OK;
/* Delete anything we don't need */
i=0;
arrlast=NULL;
for(arr=var->arr;arr!=NULL;arr=arrnext) {
arrnext=arr->next;
if (++i<arrind) { arrlast=arr; continue; }
if (i==arrind && arrlast) arrlast->next=NULL;
free(arr->subscript);
FREE(arr->value);
free(arr);
}
if (arrind==1) var->arr=NULL;
return OK;
}
/*** Set array entry value.
Sub_type: 0 = lookup array subscript
1 = lookup by index number (indexes start at _1_ not 0)
2 = reverse lookup by value ***/
set_array(var,subscript,sub_type,proc,value)
struct vars *var;
struct procedures *proc;
char *subscript,*value;
int sub_type;
{
struct array *arr,*arr2;
int subint,cnt,len,ret;
/* Get subscript value */
ret=-1;
len=0;
subint=-1;
if (isinteger(subscript,0)) {
if (sub_type!=1) return ERR_SYNTAX;
subint=atoi(subscript);
}
else {
/* Subscript is a quoted string */
if (*subscript=='"') {
if (sub_type==1) return ERR_INVALID_ARGUMENT;
subscript++;
len=strlen(subscript);
if (subscript[len-1]!='"' || len<2) return ERR_SYNTAX;
len--;
}
else {
/* Subscript is a variable itself */
if ((ret=get_variable(subscript,proc))!=OK) return ret;
if (rstack_ptr->value==NULL) return ERR_INVALID_SUBSCRIPT;
if (sub_type==1) {
if (!isinteger(rstack_ptr->value,0) ||
!(subint=atoi(rstack_ptr->value)))
return ERR_INVALID_ARGUMENT;
}
else {
subscript=rstack_ptr->value;
len=strlen(subscript);
}
}
}
/* Go through array elements */
cnt=1;
arr2=NULL;
for(arr=var->arr;arr!=NULL;arr=arr->next) {
switch(sub_type) {
case 0: /* Normal lookup */
if (!strncmp(arr->subscript,subscript,len) &&
strlen(arr->subscript)==len) goto FOUND;
break;
case 1: /* Integer lookup */
if (cnt==subint) goto FOUND;
break;
case 2: /* Reverse lookup */
if (!strncmp(arr->value,subscript,len) &&
strlen(arr->value)==len) goto FOUND;
}
arr2=arr;
cnt++;
}
/* If we've not found it then either give error if doing a number lookup
or reverse lookup or drop through and create new entry */
if (sub_type) {
if (sub_type==1) return ERR_UNDEF_SUBSCRIPT;
else return ERR_ELEMENT_NOT_FOUND; /* if reverse lookup */
}
FOUND:
if (arr!=NULL) return set_string(&arr->value,value);
if ((arr=(struct array *)malloc(sizeof(struct array)))==NULL) return ERR_MALLOC;
arr->subscript=NULL;
arr->value=NULL;
arr->next=NULL;
set_string(&arr->subscript,subscript);
len=strlen(subscript)-1;
if (subscript[len]=='"') arr->subscript[len]='\0';
if (var->arr==NULL) var->arr=arr;
else arr2->next=arr;
return set_string(&arr->value,value);
}
/*** Copy the contents and subscripts of v1 into v2 ***/
copy_array(v1,v2)
struct vars *v1,*v2;
{
struct array *a1,*a2,*aprev;
aprev=NULL;
a2=v2->arr;
for(a1=v1->arr;a1!=NULL;a1=a1->next) {
if (a2==NULL) {
if ((a2=(struct array *)malloc(sizeof(struct array)))==NULL)
return ERR_MALLOC;
a2->subscript=NULL;
a2->value=NULL;
a2->next=NULL;
if (aprev!=NULL) aprev->next=a2;
if (v2->arr==NULL) v2->arr=a2;
}
set_string(&a2->subscript,a1->subscript);
set_string(&a2->value,a1->value);
aprev=a2;
a2=a2->next;
}
return OK;
}
/*** Get variable value. Result is placed on top of the stack which calling
function must clear itself. ***/
get_variable(name,proc)
char *name;
struct procedures *proc;
{
struct process *pcs,*old;
struct vars *var;
char *subscript,*tmp,*c,*start;
int ret,name_len,sub_type,i,shared,neg;
sub_type=0;
subscript=NULL;
/* See if we're wanting to negate return value (if number) */
if (*name=='-') { neg=1; ++name; } else neg=0;
name_len=strlen(name);
/* See if we're accessing remote shared variable (make sure the dot is not
part of the subscript) */
shared=0;
c=name;
while(*c) {
if (*c==':' || *c=='#' || *c=='?') break;
if (*c=='.') { shared=1; break; }
++c;
}
if (shared) {
*c='\0';
if (!strlen(name)) {
*c='.'; return ERR_SYNTAX;
}
if (isinteger(name,0)) {
if ((pcs=get_process(atoi(name)))==NULL) {
*c='.'; return ERR_NO_SUCH_PROCESS;
}
}
else {
if ((ret=get_variable(name,proc))!=OK) {
*c='.'; return ret;
}
if ((pcs=get_process(atoi(rstack_ptr->value)))==NULL) {
*c='.'; return ERR_NO_SUCH_PROCESS;
}
}
*c='.';
start=nShowing the first 100 KB of 214.3 KB. Download the archive for the full file.