File: main.c

package info (click to toggle)
osh 1.7-13sarge1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 712 kB
  • ctags: 1,086
  • sloc: ansic: 14,984; makefile: 115; sh: 20
file content (1099 lines) | stat: -rw-r--r-- 26,019 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
/* This is main.c (osh)

Copyright (c) 1993 The Regents of the University of California
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that: (1) source code distributions
retain the above copyright notice and this paragraph in its entirety, (2)
distributions including binary code include the above copyright notice and
this paragraph in its entirety in the documentation or other materials
provided with the distribution, and (3) all advertising materials mentioning
features or use of this software display the following acknowledgement:
``This product includes software developed by the University of California,
Los Alamos National Laboratory and its contributors.'' Neither the name of
the University nore the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

/* static char *rcsid="@(#) $Id: main.c,v 1.11 1996/01/21 00:19:23 mcn Exp $"; */

#ifdef HAVE_CONFIG_H
#include <defs.h>
#endif

#include <stdio.h>
#include <errno.h>
#if STDC_HEADERS
# include <string.h>
#else
# ifndef HAVE_STRCHR
#  define strchr index
#  define strrchr rindex
# endif
char *strchr (), *strrchr ();
# ifndef HAVE_MEMCPY
#  define memcpy(d, s, n) bcopy ((s), (d), (n))
#  define memmove(d, s, n) bcopy ((s), (d), (n))
# endif
#endif
#ifdef HAVE_MALLOC_H
# include <malloc.h>
#endif
#include <stdlib.h>
#include <sys/types.h>
#if HAVE_SYS_WAIT_H
# include <sys/wait.h>
#endif
#ifndef WEXITSTATUS
# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
#endif
#ifndef WIFEXITED
# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
#endif
#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <signal.h>
#ifdef HAVE_DIRENT_H
# include <dirent.h>
#else
# define dirent direct
# if HAVE_SYS_NDIR_H
#  include <sys/ndir.h>
# endif
# if HAVE_SYS_DIR_H
#  include <sys/dir.h>
# endif
# if HAVE_NDIR_H
#  include <ndir.h>
# endif
#endif
#ifdef HAVE_SYS_UTSNAME_H
# include <sys/utsname.h>
#endif
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/param.h>
#include <curses.h>
#include <pwd.h>
#include <grp.h>
#if TM_IN_SYS_TIME
# include <sys/time.h>
#else
# include <time.h>
#endif

#ifdef HAVE_LIMITS_H
# include <limits.h>
# ifndef NGROUPS_MAX
#  define NGROUPS 16 /* Copied from includes */
# else
#  ifndef NGROUPS
#   define NGROUPS NGROUPS_MAX
#  endif
# endif /* ngroups_max */
#endif

#if defined(HAVE_STRCHR) && defined(strchr)
# undef strchr   /* STUPID SOLARIS *@&(*&@(*@&$(*@&$*@$&(*&@$(*&!!!! */
#endif
#if defined(HAVE_STRCHR) && defined(strrchr)
# undef strrchr  /* ditto */
#endif

#ifndef HAVE_GETWD
#define getwd(x) getcwd(x, MAXPATHLEN)
#endif

#define OSH
# include "struct.h"
#undef OSH

#if defined(LOGGING) && !defined(SYSLOG)
FILE *lg;
#endif

#ifndef COMPILE_TABLE
struct entry Table[MAXTABLESIZE];
char *FileList[100];
int NUMENTRY;
#endif

struct alias AliasList[100];
int AliasCounter;

struct passwd *pw, pwh;

FILE *inputfp=NULL;
char host[17];

/* read the next token from the command line and copy it to iword
 * return the type of the token
 * if the token is longer than the size of iword, copy as much as possible,
 * discard the rest of the token and return TTOOLONG
 */
static TOKEN gettoken(iword, iword_length)
char *iword;
int iword_length;
{
  enum {NEUTRAL,GTGT,INQUOTE,INWORD} state=NEUTRAL;
  int c;
  char *w;
  int iword_length_used = 0;
  /* upstream, why do you declare functions in a function? */
  int pgetc();
  void pungetc();

  w=iword;

  if (iword_length <= 1)
  {
    *w = '\0';
    return TTOOLONG;
  }

  while ((c=pgetc())!=EOF) {
    switch(state) {
      case NEUTRAL:
	switch(c) {
	  case ';': return(TSEMI);
	  case '&': return(TAMP);
	  case '$': return(TDOLLAR);
	  case '|': return(TPIPE);
	  case '<': return(TLT);
	  case '\n': return(TNL);
	  case ' ':
	  case '\t': continue;
	  case '>': state=GTGT; continue;
	  case '"': state=INQUOTE; continue;
	  default:
            /* if we are here, w can hold at least 2 chars
             * (including the trailing \0) */
            state=INWORD; *w++=c; iword_length_used++; continue;
	  }
     case GTGT:
       if (c=='>') return(TGTGT);
       pungetc(c,inputfp);
       return(TGT);
     case INQUOTE:
       switch(c) {
	 case '\\':
           /* the last -1 is for the trailing \0 */
           if (iword_length_used < iword_length - 1)
           {
             /* what happens if this is EOF? */
             *w++=pgetc();
             iword_length_used++;
             continue;
           }
           else
           {
             *w = '\0';
             /* the next char is escaped, so we are in QUOTE
              * even if it is " */
             if (pgetc() == EOF)
               return TTOOLONG;
             c = pgetc();
             while ((c != EOF) && (c != '"'))
               c = pgetc();
             return TTOOLONG;
           }
           /* should not reach here */
           break;
	 case '"': *w='\0'; return(TWORD);
	 default:
           /* the last -1 is for the trailing \0 */
           if (iword_length_used < iword_length - 1)
           {
             *w++=c;
             iword_length_used++;
             continue;
           }
           else
           {
             *w = '\0';
             /* the next char is escaped, so we are in QUOTE
              * even if it is " */
             if (pgetc() == EOF)
               return TTOOLONG;
             c = pgetc();
             while ((c != EOF) && (c != '"'))
               c = pgetc();
             return TTOOLONG;
           }
           /* should not reach here */
           break;
	 }
     case INWORD:
       switch(c) {
	 case ';':
	 case '&':
	 case '|':
	 case '<':
	 case '>':
	 case '\n':
	 case ' ':
	 case '\t': pungetc(c,inputfp); *w='\0'; return(TWORD);
	 default:
           /* the last -1 is for the trailing \0 */
           if (iword_length_used < iword_length - 1)
           {
             *w++=c;
             iword_length_used++;
             continue;
           }
           else
           {
             *w = '\0';
             c = pgetc();
             while ((c != EOF) && (c != ';') && (c != '&') && (c != '|')
                    && (c != '<') && (c != '>') && (c != '\n') && (c != ' ')
                    && (c != '\t'))
               c = pgetc();
             if (c != EOF)
               pungetc(c,inputfp);
             return TTOOLONG;
           }
           /* should not reach here */
           break;
       }
     }
  }
  return(TEOF);
}

static char inputstring[1024];
int prompt=0;

/* moved from "struct.h" */
static struct hand Internal[] = {
   { "more",   i_more   },
   { "cd",     i_cd     },
   { "cp",     i_cp,    },
   { "help",   i_help   },
   { "rm",     i_rm     },
   { "alias",  i_alias  },
   { "vi",     i_vi     },
   { "ldcache",i_ldcache},
   { "mount",  i_mount  },
   { "test",   i_test   },
   { "logout", i_exit   }, /* No handler, immediately exit */
   { "exit"  , i_exit   }, /* ditto */
   { NULL,     NULL     }
};

static void iopen(argc, argv)
int argc;
char *argv[];
{
  int i=(-1);
  int found=0;
  
  if (argc==1) { /* No arguments */
    inputfp=stdin;
    prompt=1; /* Turn on prompting */
  } else {
    while (i<NUMENTRY) /* Look through the table to find if it's a command */
      if (strcmp(Table[++i].prog_name,argv[1])==0) { found=1; break; }
    if (found) { /* It's a command, input is a string */
      inputfp=(FILE *)1;
      strncpy(inputstring, argv[1], sizeof(inputstring));
      inputstring[sizeof(inputstring) - 1] = '\0';
      for (i=3;i<=argc;i++) {
	strncat(inputstring, " ", sizeof(inputstring) - strlen(inputstring));
        inputstring[sizeof(inputstring) - 1] = '\0';
	strncat(inputstring, argv[i-1],
                sizeof(inputstring) - strlen(inputstring));
        inputstring[sizeof(inputstring) - 1] = '\0';
      }
      /* So it's a command */
      strncat(inputstring, "\n", sizeof(inputstring) - strlen(inputstring));
      inputstring[sizeof(inputstring) - 1] = '\0';
    } else { /* It's a file, input is that file */
      if (access(argv[1], R_OK)) {
	fprintf(stderr,"No access to shell script\n");
	exit(1);
      }
      inputfp=fopen(argv[1], "r");
      if (inputfp==NULL) {
	perror("Can't open shell script");
	exit(1);
      }
    }
  }
  return;
}

static char *pgetcptr=NULL;

void pungetc(value, fp)
int value;
FILE *fp;
{
  if (fp) {
    if (fp!=(FILE *)1) 
      ungetc(value, fp);
    else
      if (fp && pgetcptr) pgetcptr--;
  }
  return;
}

/* pgetc should eventually be made nicely buffered */ /* XXX */
int pgetc()
{
  register int i;
  static int column=0;
  int retval;
  
  if (inputfp==NULL) return(EOF);
  if (inputfp==(FILE *)1) {
    if (!pgetcptr) pgetcptr=inputstring;
    if (*pgetcptr==0) {
      inputfp=NULL;
      retval=EOF;
    } else {
      retval=*pgetcptr;
      pgetcptr++;
    }
    return(retval);
  }
  i=fgetc(inputfp);
  if (i==EOF) {
    inputfp=NULL;
  } else {
    if (column==0 && i=='#') {
      while ((i=fgetc(inputfp))!=EOF && i!='\n' && i!='\r') ;
      if (i != EOF)
        i=fgetc(inputfp);
      column++;
    } else {
      if (i=='\n' || i=='\r') 
	column=0;
      else 
	column++;
    }
  }
  return(i);
}

#define MAXENV 40

static TOKEN command(waitpid, makepipe, pipepfd)
int *waitpid, *pipepfd, makepipe;
{
  TOKEN token, term;
  int argc,srcfd,dstfd,pid,pfd[2],append = 0;
  char *argv[MAXARG+1],srcfile[MAXFNAME],dstfile[MAXFNAME];
  char word[MAXWORD],env[MAXENV]; /* Size of an environment variable */
  char *env2;
  char *x;

  argc=0;
  srcfd=0;
  dstfd=1;
  while(1) {
    switch(token=gettoken(word, MAXWORD)) {
      case TWORD:
	 if (argc==MAXARG) {
	   fprintf(stderr,"Too many args\n");
	   break;
	 }
	 if ((x=expand(argv,&argc,word))!=NULL) {
	   fprintf(stderr,"%s\n",x);
	   while (--argc>=0) free(argv[argc]);
	   return(0);
	 }
	 continue;
      case TLT:
	if (makepipe) {
	  fprintf(stderr,"Extra <\n");
	  break;
	}
	if (gettoken(srcfile, MAXFNAME)!=TWORD) {
	  fprintf(stderr,"Illegal < or too long file name\n");
	  break;
	}
	srcfd=BADFD;
	continue;
      case TGT:
      case TGTGT:
	if (dstfd!=1) {
	  fprintf(stderr,"Extra > or >>\n");
	  break;
	}
	if (gettoken(dstfile, MAXFNAME)!=TWORD) {
	  fprintf(stderr,"Illegal > or >>, or too long file name\n");
	  break;
	}
	dstfd=BADFD;
	append=(token==TGTGT);
	continue;
      case TDOLLAR:
	if (gettoken(env, MAXENV)!=TWORD) {
	  fprintf(stderr,"Illegal or too long environment variable\n");
	  break;
	}
        {
          char temp[255];
          /* temp2+1 is "" which is a valid string */
	  char *temp2 = "\0";

          if ((env2=getenv(env))==NULL) {
            strcpy(temp,env);
            if ((temp2=(char *)strrchr(temp,'/'))!=NULL) {
              if (temp2!=temp)
                *temp2='\0';
              else
                *(temp2+1)='\0';
              env2=getenv(temp);
            }
          }
          if (env2==NULL) {
            fprintf(stderr,"Nonexistent environment variable\n");
            break;
          }
          if ((argv[argc]=(char *)malloc(strlen(env2)+strlen(temp2+1)+1))==NULL) {
            fprintf(stderr,"Out of arg memory\n");
            break;
          }
          strcpy(argv[argc],env2);
          strcpy(argv[argc]+strlen(env2), temp2+1);
          *(argv[argc]+strlen(env2)+strlen(temp2+1)) = '\0';
        } /* of temp[] and *temp2 declaration */
	argc++;
	continue;
      case TPIPE:
      case TAMP:
      case TSEMI:
      case TNL:
	argv[argc]=NULL;
	if (token==TPIPE) {
	  if (dstfd!=1) {
	    fprintf(stderr,"> or >> conflicts with |\n");
	    break;
	  }
	  term=command(waitpid,TRUE,&dstfd);
	} else term=token;
	if ((token==TNL) || (token==TSEMI)) {
#ifdef LOGGING
	  if (argc>0) {
	    int kk=(-1);
# ifndef SYSLOG
	    time_t timer;
	    struct tm *dt;
	    
	    time(&timer);
	    dt=localtime(&timer);
	    if ((lg = fopen(LOGFILE,"a"))==NULL) 
	      perror("Open logfile for next command");
	    else {
	      fprintf(lg,"%s (%d/%d/%d %02d:%02d:%02d)",pw->pw_name,dt->tm_mon+1,
		      dt->tm_mday,dt->tm_year,dt->tm_hour,dt->tm_min,dt->tm_sec);
	      while (++kk<argc)
		fprintf(lg,"%s ",argv[kk]);
	      fclose(lg);
	    }
# else
	    sprintf(ebuf, "(%s)", pw->pw_name);
	    while (++kk<argc) {
	      strcat(ebuf, " ");
	      strcat(ebuf, argv[kk]);
	    }
	    syslog_entry(ebuf, 1);
# endif
	  }
#endif
#ifdef CHECK_ACCESS
	  if (!check_access(argc,argv)) {
	    /* One or more of the files is inaccessible */
	    while (--argc>=0) free(argv[argc]);
	    fprintf(stderr,"Consult permission not set\n");
#ifdef LOGGING
	    logit('-');
#endif
	    return (TNL);
	  }
#endif /* CHECK ACCESS */
	}
	if (makepipe) {
	  if (pipe(pfd)==-1)
	    perror("pipe");
	  *pipepfd=pfd[1];
	  srcfd=pfd[0];
	}
	pid=invoke(argc,argv,srcfd,srcfile,dstfd,dstfile,append,term==TAMP);
#ifdef LOGGING
	if (argc>0 && pid==0) /* Failed without a handler */
	  logit('-');
#endif
	if ((token!=TPIPE) && (pid!=-1)) *waitpid=pid;
	if (argc==0 && (token !=TNL || srcfd>1))
	  fprintf(stderr,"Missing command\n");
	while (--argc>=0) free(argv[argc]);
	return(term);
      case TEOF:
	logout();
	exit(0);
    case TTOOLONG:
      fprintf(stderr,"Too long command\n");
      break;
    default:
      /* should not reach here */
      fprintf(stderr,"Something strange happened\n");
      break;
    } /* of switch */
  } /* of while (1) */
  
} /* of command */

int logout()
{
  if (prompt) printf("Exit\n");
#ifdef LOGGING
# ifndef SYSLOG
  if ((lg=fopen(LOGFILE,"a"))==NULL)
    fprintf(stderr,"Can't open logfile\n");
  else {
    time_t timer;
    char *date_time;
    
    time(&timer);
    date_time=ctime(&timer); 
    fprintf(lg,"logout: %s left osh at %s",pw->pw_name,
	    date_time);
    fclose(lg);
  }
# else
  {
    char ebuf[80];
    
    sprintf(ebuf, "logout: %s left osh", pw->pw_name);
    syslog_entry(ebuf, 0);
  }
# endif
#endif
  return 0; /* dummy */
}

#ifndef HAVE_GETHOSTNAME
int gethostname(host, len)
char *host;
int len;
{
  struct utsname name;
  
  uname(&name);
  strncpy(host, name.nodename, len);
  return 0;
}
#endif

int do_prompt()
{
  char cwd[MAXPATHLEN];
  
  if (!prompt) return 0;
  getcwd(cwd, MAXPATHLEN);
  printf("%s.%s (%s) #> ",host,pw->pw_name,cwd);
  fflush(stdout);
  /* Prints a prompt like:
     beta,/u0/mcn #> 
     */
  return 0; /* dummy */
}

void pwdcopy(from, to)
struct passwd *from, *to;
{
  to->pw_name  = (char *)malloc(strlen(from->pw_name)+1);
  strcpy(to->pw_name, from->pw_name);
  to->pw_uid   = from->pw_uid;
  to->pw_gid   = from->pw_gid;
  to->pw_gecos = (char *)malloc(strlen(from->pw_gecos)+1);
  strcpy(to->pw_gecos, from->pw_gecos);
  to->pw_dir   = (char *)malloc(strlen(from->pw_dir)+1);
  strcpy(to->pw_dir, from->pw_dir);
  to->pw_shell = (char *)malloc(strlen(from->pw_shell)+1);
  strcpy(to->pw_shell, from->pw_shell);
  return;
}

void grpcopy(from, to)
struct group *from, *to;
{
  /* Only copy what we use */
  to->gr_name=(char *)malloc(strlen(from->gr_name));
  memcpy(to->gr_name, from->gr_name, strlen(from->gr_name));
}

int ingroup(what)
char *what;

{
  GETGROUPS_T groups[NGROUPS];
  struct group *gr;
  int ngroups,i;
  int found=0;
  
  ngroups=getgroups(NGROUPS,groups);
  for (i=0;i<ngroups;i++) {
    gr=getgrgid(groups[i]);
    if (gr!=NULL)
      if (!strcmp(gr->gr_name,what)) found=1;
  }
  return (1-found);
}

void get_table(name,group)
char *name;
char *group;

{
  FILE *table;
  char *who=(char *)malloc(16); /* Number of chars in the login name */
  char dummy[255];
  int  i,x;
  char *prog=(char *)malloc(MAXPATHLEN); 
  char *path=(char *)malloc(MAXPATHLEN);
  char work_table[MAXPATHLEN];
  int bp;
  
  strcpy(work_table, TABLE_NAME);
  bp=strlen(work_table)-2;
  if (!strncmp("{}", work_table+bp, 2)) {
    work_table[bp]='\0';
    strcat(work_table, host);
  }
  i=0;
  if ((table=fopen(work_table,"r"))==NULL) {
    fprintf(stderr,"TABLE_NAME=%s\n", work_table);
    perror("Can't open command Matrix! (FATAL)");
    exit(1);
  }
  while (!feof(table)) {
    do {
      if ((fgets(dummy,255,table)==NULL) && ferror(table)) {
	fprintf(stderr, "TABLE_NAME=%s, Read error.\n", work_table);
	perror("Osh terminated");
	exit(1);
      }
    } while (*dummy=='#'); /* Skip comments */
    sscanf(dummy,"%16s",who); /* fgets saves the \n */
    if ((strcmp(who,name)==0) || (ingroup(who)==0) ||
	(strcmp(who,"ALL")==0)) {
      do {
	fgets(dummy,255,table); /* This should get the { */
      } while (*dummy=='#');
      fgets(dummy,255,table);
      while (strncmp(dummy,"}",1)!=0 && !feof(table)) {
	if (*dummy=='#') continue;  /* Comment */
	if ((*dummy=='+') || (*dummy=='-')) { /* ACL Entry */
	  int temp=0;
	  
	  while (FileList[temp]!=NULL) temp++;
	  /* sscanf(dummy,"%s",prog); */ /* Get rid of the \n */
	  strncpy(prog, dummy, strlen(dummy));
	  prog[strlen(dummy) -1] = '\0';
	  FileList[temp]=(char *)malloc(strlen(prog)+1);
	  strcpy(FileList[temp],prog);
	  FileList[temp+1]=NULL;
	} else {
	  sscanf(dummy,"%s %s",prog,path);
	  if ((Table[i].prog_name=(char *)malloc(strlen(prog)+1))==NULL) {
	    perror("malloc");
	    exit(1);
	  }
	  if ((Table[i].path=(char *)malloc(strlen(path)+1))==NULL) {
	    perror("malloc2");
	    exit(1);
	  }
	  strcpy(Table[i].prog_name,prog);
	  strcpy(Table[i].path,path);
	  Table[i].handler=execute;
	  for (x=0;x<NUMINT;x++)
	    if (strcmp(Table[i].prog_name,Internal[x].prog_name)==0) {
	      Table[i].handler=Internal[x].handler;
	      break;
	    }
	  if (strcmp(Table[i].path,"NULL")==0) Table[i].path=NULL;
	  i++;
	} /* of if not an acl entry */
	fgets(dummy,255,table);
      } /* Of while reading the table */
    } /* Of if a match */
  } /* Of while */
  if (i==0) {
    fprintf(stderr,"Can't load user/group from matrix! (FATAL)\n");
    exit(1);
  }
  NUMENTRY=i-1;
  fclose(table);
}

int main(argc, argv) /* real shell */
int argc;
char *argv[];
{
  int pid;
  TOKEN term;
  extern void ignoresig();
  extern void waitfor();
  struct group *gp, gph;
  time_t timer;
  char *date_time;
  char *t;
  char buf[40];
  int i;
  char *x;
#ifdef HAVE_SYS_UTSNAME
  struct utsname un;
#endif

#ifndef HAVE_SYS_UTSNAME
  gethostname(host, 16);
  if ((x=strchr(host, '.'))!=NULL)
	*x=0; /* Kill FQDN */
#else
  uname(&un);
  strcpy(host, un.nodename);
#endif

  ignoresig();
  AliasCounter=0;
#ifndef COMPILE_TABLE
  FileList[0]=NULL;
#endif
  t=getenv("TERM");
  if (!strcmp(t,"network") && argc==1) {
	printf("Terminal Type (%s): ",t);
	fgets(buf,7,stdin);
	for (i=0;i<100;i++) 
	  if (!strncmp(environ[i],"TERM=",5)) {
		strncpy(environ[i]+5,buf,strlen(buf));
		*(environ[i]+5+strlen(buf)-1)='\0';
		break;
	  }
  }
  pwdcopy(getpwuid(getuid()), &pwh);
  pw = &pwh;
  grpcopy(getgrgid(pw->pw_gid), &gph);
  gp = &gph;
  if (argc==1) {
	printf("%s (%s)\n",pw->pw_gecos,pw->pw_name);
  	printf("Operator Shell version %s\n",VERSION);
  }
#ifdef LOGGING
# ifndef SYSLOG
  if ((lg=fopen(LOGFILE,"a"))==NULL) 
    perror("Can't open logfile");
  else {
	time(&timer);
	date_time=ctime(&timer);
	fprintf(lg,"LOGIN: %s ran osh at %s",pw->pw_name,date_time);
	fclose(lg);
  }
# else
  {
	char ebuf[80];

	sprintf(ebuf, "LOGIN: %s ran osh", pw->pw_name);
	syslog_entry(ebuf, 0);
  }
# endif
#endif

#ifndef COMPILE_TABLE
  if (gp==NULL)
	get_table(pw->pw_name, NULL);
  else
    get_table(pw->pw_name,gp->gr_name);
#endif
  iopen(argc,argv);
  do_prompt();
  while (1) {
    term=command(&pid,FALSE,NULL);
    if (term!=TAMP && pid!=0)
      waitfor(pid);
    if (term==TNL) do_prompt();
/*   for (fd=3;fd<20;fd++) (void)fclose(fd); */
  }

}

int invoke(argc,argv,srcfd,srcfile,dstfd,dstfile,append,bckgrnd)
int argc,srcfd,dstfd,append,bckgrnd;
char *argv[], *srcfile, *dstfile;

{
  int pid;

  if (argc==0) return(0);
  /* if pid is non-zero */
  if ((pid=builtin(argc,argv,srcfd,srcfile,dstfd,dstfile,append,bckgrnd)))
        return(pid);
  else 
  if (pid!=-2) {  /* -2 will be the code for any foreground command */
    fprintf(stderr,"Unknown/restricted command.\n");
    return(0);
  }
  return 0; /* dummy */
} /* of routine */

static int redirect(srcfd,srcfile,dstfd,dstfile,append,bckgrnd)
int srcfd,dstfd,append,bckgrnd;
char *srcfile,*dstfile;
{
  int flags,fd;
  char *test[1];

  if (srcfd==0 && bckgrnd) {
    strcpy(srcfile,"/dev/null");
    srcfd=BADFD;
  }
  if (srcfd!=0) {
    if (close(0)==-1)
      perror("close");
    if (srcfd>0) {
      if (dup(srcfd)!=0)
	 fatal("dup");
    } else {
#ifdef CHECK_ACCESS
      /* Setup dummy argv[] for check_access */
      test[0] = (char *)malloc(strlen(srcfile)+1);
      strcpy(test[0], srcfile);
      if (!check_access(1, test)) {
	fprintf(stderr, "Consult permission not set\n");
#ifdef LOGGING
	logit('-');
#endif
	return(0);
      }
      free(test[0]);
#endif /* CHECK_ACCESS */
      if (open(srcfile,O_RDONLY,0)==-1) {
	fprintf(stderr,"Can't open %s\n",srcfile);
	return(0);
      }
    }
  }
  if (dstfd!=1) {
    if (close(1)==-1) perror("close");
    if (dstfd>1) {
      if (dup(dstfd)!=1) fatal("dup");
    } else { 
      int dstfd;
      
      if (writeable(dstfile)) {
        flags=O_WRONLY|O_CREAT;
        if (!append) flags |= O_EXCL; /* This handles race condition problems */
        if ((dstfd=open(dstfile,flags,0666))==-1) {
	  if (errno==EEXIST) 
	    fprintf(stderr,"Will not clobber existing file %s\n",dstfile);
	  else
	    fprintf(stderr,"Can't create %s\n",dstfile);
	  return(0);
        }
	if (!append) {
	  char buf[80], *cptr;
	  
	  strcpy(buf,dstfile);
	  if ((cptr=(char *)strrchr(buf, '/'))!=NULL) {
	    if (cptr!=buf)
	      *cptr='\0';
	    else
	      *(cptr+1)='\0';
	    if (!access(buf,W_OK))
	      /* 
	       * if we can write to the parent normally, do
	       * the chown, otherwise, leave it as root 
	       */
#ifdef HAVE_FCHOWN
	      fchown(dstfd, getuid(), getgid());
#else
	    /*
	     * Cray is braindead and doesn't have an fchown.
	     */
	    chown(dstfile, getuid(), getgid());
#endif
	  } else {
	    /* otherwise we're in the current directory */
	    if (getcwd(buf, MAXPATHLEN)  && !access(buf,W_OK))
#ifdef HAVE_FCHOWN
	      fchown(dstfd, getuid(), getgid());
#else
	    chown(dstfile, getuid(), getgid());
#endif
	  }
	} else /* (if append) */
	  if (lseek(1,0L,2) == -1)
	    perror("lseek");
      } else {
	fprintf(stderr,"osh: redirect to %s: Permission denied\n",
	        dstfile);
	return(0);
      }
    }
  }
  for (fd=3;fd<20;fd++) (void)close(fd);
  return(1);
}


#ifndef MAXSIG
#define MAXSIG 19
#endif

void statusprt(pid,status)
int pid,status;
{

  int code;
  static char *sigmsg[]= {
    "",
    "Hangup",
    "Interrupt",
    "Quit",
    "Illegal Instruction",
    "Trace Trap",
    "IOT instruction",
    "EMT instruction",
    "Floating point exception",
    "Kill",
    "Bus error",
    "Segmentation violation",
    "Bad arg to system call",
    "Write on pipe",
    "Alarm clock",
    "Terminate signal",
    "User signal 1",
    "User signal 2",
    "Death of child",
    "Power fail"
  };

  if (status!=0 && pid!=0)
   printf("Process %d: ",pid);
  if (lowbyte(status)==0) {
    if ((code=highbyte(status))!=0) 
      /* printf("Exit code %d\n",code); */
      /* XXX - LOG THE EXIT CODE somehow? Pug suggests a new log entry */
      logit('-');
    else
      logit('+');
  } else {
    if ((code=status &0177) <=MAXSIG)
      printf("%s",sigmsg[code]);
    else
      printf("Signal #%d",code);
    if ((status & 0200) == 0200)
      printf("-core dumped");
    printf("\n");
  }
}

void ignoresig()
{
    if (signal(SIGINT,SIG_IGN)==SIG_ERR ||
	signal(SIGQUIT,SIG_IGN)==SIG_ERR)
	  perror("signal");
	signal(SIGHUP, exit);
	signal(SIGTERM, exit);
}

void entrysig()
{
  if (signal(SIGINT,SIG_DFL)==SIG_ERR ||
      signal(SIGQUIT,SIG_DFL)==SIG_ERR)
	perror("signal");
}


void waitfor(pid)
int pid;
{
  int wpid, status;

  while ((wpid=wait(&status))!=pid && wpid!=-1)
    statusprt(wpid,status);
  if (wpid==pid)
    statusprt(0,status);
}


    
int builtin(argc,argv,srcfd,srcfile,dstfd,dstfile,append,bckgrnd)
int argc,srcfd,dstfd,append,bckgrnd;
char *argv[],*srcfile,*dstfile;
{
  register int i=(-1);
  int pid;
  int found=0;
  
  while (i<NUMENTRY)
    if (strcmp(Table[++i].prog_name,argv[0])==0)
      { found=1; break; }
  if (!found) return(0); /* We couldn't find it */
  if (Table[i].path!=NULL) {
    free(argv[0]);
    argv[0]=(char *)malloc(strlen(Table[i].path)+1);
    strcpy(argv[0],Table[i].path);
    /* Put the path in */
  }
  if (strcmp(Table[i].prog_name,"cd")==0) { /* Can't put this in bg */
    (*(Table[i].handler))(argc,argv);
    return(-2);
  }
  else
  if (strcmp(Table[i].prog_name,"alias")==0) { /* Can't put in bg */
    (*(Table[i].handler))(argc,argv);
    return(-2);
  }
  else
  if (strcmp(Table[i].prog_name,"setenv")==0) { /* Can't put in bg */
    (*(Table[i].handler))(argc,argv);
    return(-2);
  }
  else
  if (strcmp(Table[i].prog_name,"test")==0) {  /* Can't put in bg */
    (*(Table[i].handler))(argc, argv);
    return(-2);
  }
  else
  if (strcmp(Table[i].prog_name, "exit")==0) {
    (*(Table[i].handler))(argc, argv);
    return(-2);
  }
  else
  if (strcmp(Table[i].prog_name, "logout")==0) {
    (*(Table[i].handler))(argc, argv);
    return(-2);
  }
  else
    switch(pid=fork()) {
      case -1:
	fprintf(stderr,"Can't create new process\n");
	return(0);
      case 0:
	if (!bckgrnd)
	  entrysig();
	if (Table[i].handler==execute) logit('?');
	if (redirect(srcfd,srcfile,dstfd,dstfile,append,bckgrnd))
	  (*(Table[i].handler))(argc,argv);
	_exit(0); /* Just in case it comes back */
      default:
	if (srcfd>0 && (close(srcfd)==-1)) perror("close src");
	if (dstfd>1 && (close(dstfd)==-1)) perror("close dst");
	if (bckgrnd)
	  printf("%d\n",pid);
	return(pid);
    }
}