home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / ckc072.zip / ck9fio.c < prev    next >
C/C++ Source or Header  |  1991-10-03  |  24KB  |  806 lines

  1. char *ckzv = "OS-9 file support, V4c(004) 30 Apr 87";
  2. char *ckzsys = " OS-9/68000";
  3.  
  4. /* c k 9 F I O  --  Kermit file system support for OS-9/68k systems */
  5.  
  6. /*
  7.  Author: Peter Scholz,
  8.  Ruhr University Bochum, Department for Analytical Chemistry,
  9.  Federal Republic of Germany,   February 1987
  10.  
  11.  04/30/87 Robert Larson        Cleanup, merge with standard C-kermit
  12.  
  13.  adapted from Unix C-Kermit
  14.  Author: Frank da Cruz (SY.FDC@CU20B),
  15.  Columbia University Center for Computing Activities, January 1985.
  16.  Copyright (C) 1985, Trustees of Columbia University in the City of New York.
  17.  
  18.  Permission is granted to any individual or institution to use, copy, or
  19.  redistribute this software so long as it is not sold for profit, provided this
  20.  copyright notice is retained.
  21. */
  22. /* Includes */
  23.  
  24. #include "ckcker.h"        /* Kermit definitions */
  25. #include "ckcdeb.h"        /* Typedefs, debug formats, etc */
  26. #include <ctype.h>        /* Character types */
  27. #include <stdio.h>        /* Standard i/o */
  28. #include <dir.h>        /* Directory structure */
  29. #include <direct.h>
  30. #include <modes.h>
  31.  
  32. /* Definitions of some system commands */
  33.  
  34. char *DIRCMD = "dir ";        /* For directory listing */
  35. char *DELCMD = "del ";        /* For file deletion */
  36. char *TYPCMD = "list ";        /* For typing a file */
  37. char *PWDCMD = "pd ";        /* For saying where I am */
  38.  
  39. char *SPACMD = "free ";
  40. char *SPACM2 = "free ";        /* For space in specified directory */
  41.  
  42. char *WHOCMD = "procs ";    /* we have no who yet*/
  43.  
  44. /*
  45.   Functions (n is one of the predefined file numbers from ckermi.h):
  46.  
  47.    zopeni(n,name)   -- Opens an existing file for input.
  48.    zopeno(n,name)   -- Opens a new file for output.
  49.    zclose(n)        -- Closes a file.
  50.    zchin(n,&c)      -- Gets the next character from an input file.
  51.    zsout(n,s)       -- Write a null-terminated string to output file, buffered.
  52.    zsoutl(n,s)      -- Like zsout, but appends a line terminator.
  53.    zsoutx(n,s,x)    -- Write x characters to output file, unbuffered.
  54.    zchout(n,c)      -- Add a character to an output file, unbuffered.
  55.    zchki(name)      -- Check if named file exists and is readable, return size.
  56.    zchko(name)      -- Check if named file can be created.
  57.    znewn(name,s)    -- Make a new unique file name based on the given name.
  58.    zdelet(name)     -- Delete the named file.
  59.    zxpand(string)   -- Expands the given wildcard string into a list of files.
  60.    znext(string)    -- Returns the next file from the list in "string".
  61.    zxcmd(cmd)       -- Execute the command in a lower fork.
  62.    zclosf()         -- Close input file associated with zxcmd()'s lower fork.
  63.    zrtol(n1,n2)     -- Convert remote filename into local form.
  64.    zltor(n1,n2)     -- Convert local filename into remote form.
  65.    zchdir(dirnam)   -- Change working directory.
  66.    zhome()          -- Return pointer to home directory name string.
  67.    zkself()         -- Kill self, log out own job.
  68.  */
  69.  
  70.  
  71. /* Some systems define these in include files, others don't... */
  72. #define R_OK S_IREAD        /* For access */
  73. #define W_OK S_IWRITE
  74. #define O_RDONLY 000
  75.  
  76. #ifndef    MAXNAMLEN
  77. #define MAXNAMLEN 28        /* If still not defined... */
  78. #endif
  79.  
  80. #define MAXWLD 500
  81.  
  82. /* Declarations */
  83.  
  84. FILE *fp[ZNFILS] = {    /* File pointers */
  85.     NULL, NULL, NULL, NULL, NULL, NULL, NULL };
  86.  
  87. static int pid;                /* pid of child fork */
  88. static int fcount;            /* Number of files in wild group */
  89. char *malloc(), *getenv(), *strcpy();    /* System functions */
  90. extern errno;                /* System error code */
  91.  
  92. static char *mtchs[MAXWLD],        /* Matches found for filename */
  93.      **mtchptr;                /* Pointer to current match */
  94.  
  95. /*  Z K S E L F  --  Kill Self: log out own job, if possible.  */
  96.  
  97. zkself() {                /* For "bye", but no guarantee! */
  98.     return(kill(getpid(),0));
  99. }
  100.  
  101. #define MAXPATH 128
  102.  
  103. char *zgtdir() {
  104.     /* I'm sure this can be done better... */
  105.     static char cwd[MAXPATH];
  106.     char backpath[MAXPATH];
  107.     char *bpp = backpath, *path = cwd;
  108.     DIR *dirp;
  109.     struct direct *dp;
  110.     long inode, inode2;
  111.     char dots[MAXPATH];
  112.  
  113.     if((dirp = opendir(".")) == NULL || readdir(dirp) == NULL ||
  114.         (dp = readdir(dirp)) == NULL) {
  115.     closedir(dirp);
  116.     return (char *)NULL;
  117.     }
  118.     inode = dp->d_addr;
  119.     *path++ = '/';
  120.     _gs_devn(dirp->dd_fd, path);
  121.     path += strlen(path);
  122.     closedir(dirp);
  123.     strcpy(dots, "..");
  124.     for(;;) {
  125.     if((dirp = opendir(dots)) == NULL || readdir(dirp) == NULL ||
  126.             (dp = readdir(dirp)) == NULL) {
  127.         closedir(dirp);
  128.         return (char *)NULL;
  129.     }
  130.     inode2 = dp->d_addr;
  131.     if(inode == inode2) break;    /* .. and . are same, we are done */
  132.     do {
  133.         if((dp = readdir(dirp)) == NULL) {
  134.         closedir(dirp);
  135.         return (char *)NULL;
  136.         }
  137.     } while(dp->d_addr != inode);
  138.     *bpp++ = '/';
  139.     strcpy(bpp, dp->d_name);
  140.     bpp += strlen(bpp);
  141.     closedir(dirp);
  142.     inode = inode2;
  143.     strcat(dots, "/..");
  144.     }
  145.     while(bpp > backpath) {
  146.     *bpp = '\0';
  147.     while(*--bpp != '/') {}
  148.     strcpy(path, bpp);
  149.     path += strlen(path);
  150.     }
  151.     return cwd;
  152. }
  153.  
  154.  
  155. /*  Z O P E N I  --  Open an existing file for input. */
  156.  
  157. zopeni(n,name) int n; char *name; {
  158.     debug(F111," zopeni",name,n);
  159.     debug(F101,"  fp","",(int) fp[n]);
  160.     if (chkfn(n) != 0) return(0);
  161.     if (n == ZSYSFN) {   /* Input from a system function? */
  162.         debug(F110," invoking zxcmd",name,0);
  163.     return(zxcmd(name));  /* Try to fork the command */
  164.     }
  165.     if (n == ZSTDIO) {   /* Standard input? */
  166.     if (isatty(0)) {
  167.         ermsg("Terminal input not allowed");
  168.         debug(F110,"zopeni: attempts input from unredirected stdin","",0);
  169.         return(0);
  170.     }
  171.     fp[ZIFILE] = stdin;
  172.     return(1);
  173.     }
  174.     fp[n] = fopen(name,"r");  /* Real file. */
  175.     debug(F111," zopeni", name, (int) fp[n]);
  176.     if (fp[n] == NULL) perror("zopeni");
  177.     return((fp[n] != NULL) ? 1 : 0);
  178. }
  179.  
  180. /*  Z O P E N O  --  Open a new file for output.  */
  181.  
  182. zopeno(n,name) int n; char *name; {
  183.     debug(F111," zopeno",name,n);
  184.     if (chkfn(n) != 0) return(0);
  185.     if ((n == ZCTERM) || (n == ZSTDIO)) {   /* Terminal or standard output */
  186.     fp[ZOFILE] = stdout;
  187.     debug(F101," fp[]=stdout", "", (int) fp[n]);
  188.     return(1);
  189.     }
  190.     fp[n] = fopen(name,"w");  /* A real file, try to open */
  191.     if (fp[n] == NULL) {
  192.         perror("zopeno can't open");
  193.     } else {
  194.     /* chown(name, getuid(), getgid());     In case set[gu]id */
  195.         if (n == ZDFILE) setbuf(fp[n],NULL); /* Debugging file unbuffered */
  196.     }
  197.     debug(F101, " fp[n]", "", (int) fp[n]);
  198.     return((fp[n] != NULL) ? 1 : 0);
  199. }
  200.  
  201. /*  Z C L O S E  --  Close the given file.  */
  202.  
  203. /*  Returns 0 if arg out of range, 1 if successful, -1 if close failed.  */
  204.  
  205. zclose(n) int n; {
  206.     int x;
  207.     if (chkfn(n) < 1) return(0); /* Check range of n */
  208.     if ((n == ZIFILE) && fp[ZSYSFN]) { /* If system function */
  209.     x = zclosf();   /* do it specially */
  210.     } else {
  211.     if ((fp[n] != stdout) && (fp[n] != stdin)) x = fclose(fp[n]);
  212.     fp[n] = NULL;
  213.     }
  214.     return((x == EOF) ? -1 : 1);
  215. }
  216.  
  217. /*  Z C H I N  --  Get a character from the input file.  */
  218.  
  219. /*  Returns -1 if EOF, 0 otherwise with character returned in argument  */
  220.  
  221. zchin(n,c) int n; char *c; {
  222.     int a;
  223.     if (chkfn(n) < 1) return(-1);
  224.     a = getc(fp[n]);
  225.     if (a == EOF) return(-1);
  226.     *c = a & 0377;
  227.     return(0);
  228. }
  229.  
  230. /*  Z S O U T  --  Write a string to the given file, buffered.  */
  231.  
  232. zsout(n,s) int n; char *s; {
  233.     if (chkfn(n) < 1) return(-1);
  234.     fputs(s,fp[n]);
  235.     return(0);
  236. }
  237.  
  238. /*  Z S O U T L  --  Write string to file, with line terminator, buffered  */
  239.  
  240. zsoutl(n,s) int n; char *s; {
  241.     if (chkfn(n) < 1) return(-1);
  242.     fputs(s,fp[n]);
  243.     fputs("\n",fp[n]);
  244.     return(0);
  245. }
  246.  
  247. /*  Z S O U T X  --  Write x characters to file, unbuffered.  */
  248.  
  249. zsoutx(n,s,x) int n, x; char *s; {
  250.     if (chkfn(n) < 1) return(-1);
  251.     return(write(fileno(fp[n]),s,x));
  252. }
  253.  
  254.  
  255. /*  Z C H O U T  --  Add a character to the given file.  */
  256.  
  257. /*  Should return 0 or greater on success, -1 on failure (e.g. disk full)  */
  258.  
  259. zchout(n,c) int n; char c; {
  260.     if (chkfn(n) < 1) return(-1);
  261.     if (n == ZSFILE)
  262.     return(write(fileno(fp[n]),&c,1)); /* Use unbuffered for session log */
  263.     else {    /* Buffered for everything else */
  264.     if (putc(c,fp[n]) == EOF) /* If true, maybe there was an error */
  265.         return(ferror(fp[n])); /* Check to make sure */
  266.     else return(0);   /* There was no error. */
  267.     }
  268. }
  269.  
  270. /*  C H K F N  --  Internal function to verify file number is ok  */
  271.  
  272. /*
  273.  Returns:
  274.   -1: File number n is out of range
  275.    0: n is in range, but file is not open
  276.    1: n in range and file is open
  277. */
  278. chkfn(n) int n; {
  279.     switch (n) {
  280.     case ZCTERM:
  281.     case ZSTDIO:
  282.     case ZIFILE:
  283.     case ZOFILE:
  284.     case ZDFILE:
  285.     case ZTFILE:
  286.     case ZPFILE:
  287.     case ZSFILE:
  288.     case ZSYSFN: break;
  289.  
  290.     default:
  291.         debug(F101,"chkfn: file number out of range","",n);
  292.         fprintf(stderr,"?File number out of range - %d\n",n);
  293.         return(-1);
  294.     }
  295.     return( (fp[n] == NULL) ? 0 : 1 );
  296. }
  297.  
  298. /*  Z C H K I  --  Check if input file exists and is readable  */
  299.  
  300. /*
  301.   Returns:
  302.    >= 0 if the file can be read (returns the size).
  303.      -1 if file doesn't exist or can't be accessed,
  304.      -2 if file exists but is not readable (e.g. a directory file).
  305.      -3 if file exists but protected against read access.
  306. */
  307. long
  308. zchki(name) char *name; {
  309.     struct fildes buf;
  310.     int x; long y;   
  311.  
  312.     if (access(name,0) < 0) {
  313.     if(access(name,S_IFDIR)>=0) {
  314.         debug(F111,"zchki skipping:",name,errno);
  315.         return(-2);
  316.     }
  317.     debug(F111,"zchki can't access",name,errno);
  318.     return(-1);
  319.     }
  320.     debug(F111,"zchki stat ok:",name,x);
  321.  
  322.     if ((x = access(name,R_OK)) < 0) {  /* Is the file accessible? */
  323.     debug(F111," access failed:",name,x); /* No */
  324.     return(-3);   
  325.     }
  326.     if((x = open(name,S_IREAD)) < 0) {
  327.     debug(F111,"zchki can't open:",name,errno);
  328.     return(-2);
  329.     }
  330.     y = _gs_size(x);
  331.     close(x);
  332.     debug(F111," access ok:",name,(int) y); /* Yes */
  333.     return( (y > -1) ? y : 0 );
  334. }
  335.  
  336. /*  Z C H K O  --  Check if output file can be created  */
  337.  
  338. /*
  339.  Returns -1 if write permission for the file would be denied, 0 otherwise.
  340. */
  341. zchko(name) char *name; {
  342.     int i, x;
  343.     char s[50], *sp; 
  344.  
  345.     if(access(name,S_IFDIR)>=0) return -1;    /* it's a directory */
  346.     sp = s;    /* Make a copy, get length */
  347.     x = 0;
  348.     while ((*sp++ = *name++) != '\0')
  349.     x++;
  350.     if (x == 0) return(-1);        /* If no filename, fail. */
  351.  
  352.     debug(F101," length","",x);
  353.     for (i = x; i > 0; i--) {        /* Strip filename. */
  354.     if(!isalnum(s[i-1])) {
  355.         switch(s[i-1]) {
  356.             case '.':
  357.         case '$':
  358.         case '_': continue;
  359.            case '/': break;
  360.             default: return -1;    /* bad character */
  361.         }
  362.         break;
  363.     }
  364.     }
  365.     debug(F101," i","",i);
  366.     if (i == 0)                /* If no path, use current directory */
  367.     strcpy(s,".");   
  368.     else {                /* Otherwise, use given one. */
  369.         if(i==x) return -1;        /* no filename! */
  370.         s[--i] = '\0';
  371.     }
  372.     x = access(s,S_IFDIR|S_IWRITE);    /* Check access of path. */
  373.     if (x < 0) {
  374.     fprintf(stderr,"access failed %s   errno:%d\n",s,errno);
  375.     debug(F111,"zchko access failed:",s,errno);
  376.     return(-1);
  377.     } else {
  378.     debug(F111,"zchko access ok:",s,x);
  379.     return(0);
  380.     }
  381. }
  382.  
  383. /*  Z D E L E T  --  Delete the named file.  */
  384.  
  385. zdelet(name) char *name; {
  386.     unlink(name);
  387. }
  388.  
  389.  
  390. /*  Z R T O L  --  Convert remote filename into local form  */
  391.  
  392. /*  For OS9, this means changing uppercase letters to lowercase.  */
  393.  
  394. zrtol(name,name2) char *name, *name2; {
  395.     for ( ; *name != '\0'; name++) {
  396.     *name2++ = isupper(*name) ? tolower(*name) : *name;
  397.     }
  398.     *name2 = '\0';
  399.     debug(F110,"zrtol:",name2,0);
  400. }
  401.  
  402.  
  403. /*  Z L T O R  --  Local TO Remote */
  404.  
  405. /*  Convert filename from local format to common (remote) form.  */
  406.  
  407. zltor(name,name2) char *name, *name2; {
  408.     char work[100], *cp, *pp;
  409.     int dc = 0;
  410.  
  411.     debug(F110,"zltor",name,0);
  412.     pp = work;
  413.     for (cp = name; *cp != '\0'; cp++) { /* strip path name */
  414.     if (*cp == '/') {
  415.         dc = 0;
  416.         pp = work;
  417.     }
  418.     else if (islower(*cp)) *pp++ = toupper(*cp); /* Uppercase letters */
  419.     else if ((*cp == '.') && (++dc > 1)) *pp++ = 'X'; /* & extra dots */
  420.     else *pp++ = *cp;
  421.     }
  422.     *pp = '\0';    /* Tie it off. */
  423.     cp = name2;    /* If nothing before dot, */
  424.     if (*work == '.') *cp++ = 'X'; /* insert 'X' */
  425.     strcpy(cp,work);
  426.     debug(F110," name2",name2,0);
  427. }
  428.  
  429.  
  430. /*  Z C H D I R  --  Change directory  */
  431.  
  432. zchdir(dirnam) char *dirnam; {
  433.     char *hd;
  434.     if (*dirnam == '\0') hd = getenv("HOME");
  435.     else hd = dirnam;
  436.     return((chdir(hd) == 0) ? 1 : 0);
  437. }
  438.  
  439.  
  440. /*  Z H O M E  --  Return pointer to user's home directory  */
  441.  
  442. char *
  443. zhome() {
  444.     return(getenv("HOME"));
  445. }
  446.  
  447. /*  Z X C M D -- Run a system command so its output can be read like a file */
  448.  
  449. zxcmd(comand) char *comand; {
  450.     int pipes[2];
  451.     int i,stdio[3],os9fork();
  452.     if ((pipes[0]=open("/pipe",_READ))<0) return(0);
  453.     if((pipes[1]=dup(pipes[0]))<0) {
  454.     close(pipes[0]);
  455.         return(0);
  456.     }
  457.     for(i=0;i<3;i++)
  458.     stdio[i] = dup(i);
  459.     close(0);   /* close stdin */
  460.     if (open("/nil",_READ) < 0) return(0); /* replace input by null */
  461.  
  462.     close(1);   /* simulate dup2 */
  463.     if (dup(pipes[1]) != 1 )
  464.     conol("trouble duping stdout in routine zxcmd\n");
  465.     close(2);   /* simulate dup2 */
  466.     if (dup(pipes[1]) != 2 )
  467.     conol("trouble duping stderr in routine zxcmd\n");
  468.  
  469.     pid = os9fork("shell",strlen(comand),comand,0,0,0,0);
  470.  
  471.     fp[ZIFILE] = fdopen(pipes[0],"r"); /* open a stream for it */
  472.     close(pipes[1]);   /* don't need the output side */
  473.     for(i=0;i<3;i++) {
  474.     close(i);
  475.     dup(stdio[i]);
  476.     }
  477.     fp[ZSYSFN] = fp[ZIFILE];  /* Remember. */
  478.     return(1);
  479. }
  480.  
  481. /*  Z C L O S F  - wait for the child fork to terminate and close the pipe. */
  482.  
  483. zclosf() {
  484.     int wstat;
  485.     fclose(fp[ZIFILE]);
  486.     fp[ZIFILE] = fp[ZSYSFN] = NULL;
  487.     while ((wstat = wait(0)) != pid && wstat != -1) ;
  488.     return(1);
  489. }
  490.  
  491. /*  Z X P A N D  --  Expand a wildcard string into an array of strings  */
  492. /*
  493.   Returns the number of files that match fn1, with data structures set up
  494.   so that first file (if any) will be returned by the next znext() call.
  495. */
  496. zxpand(fn) char *fn; {
  497.     fcount = fgen(fn,mtchs,MAXWLD); /* Look up the file. */
  498.     if (fcount > 0) {
  499.     mtchptr = mtchs;  /* Save pointer for next. */
  500.     }
  501.     debug(F111,"zxpand",mtchs[0],fcount);
  502.     return(fcount);
  503. }
  504.  
  505.  
  506. /*  Z N E X T  --  Get name of next file from list created by zxpand(). */
  507. /*
  508.  Returns >0 if there's another file, with its name copied into the arg string,
  509.  or 0 if no more files in list.
  510. */
  511. znext(fn) char *fn; {
  512.     if (fcount-- > 0) strcpy(fn,*mtchptr++);
  513.     else *fn = '\0';
  514.     debug(F111,"znext",fn,fcount+1);
  515.     return(fcount+1);
  516. }
  517.  
  518.  
  519. /*  Z N E W N  --  Make a new name for the given file  */
  520.  
  521. znewn(fn,s) char *fn, **s; {
  522.     static char buf[256];
  523.     char *bp, *xp;
  524.     int len = 0, n = 0, d = 0, t, i, power = 1;
  525. #ifdef MAXNAMLEN
  526.     int max = MAXNAMLEN;
  527. #else
  528.     int max = 14;
  529. #endif
  530.     bp = buf;
  531.     while (*fn) {   /* Copy name into buf */
  532.     *bp++ = *fn++;
  533.     len++;
  534.     }
  535.     if (len > max-2) {    /* Don't let it get too long */
  536.     bp = buf + max-2;
  537.     len = max - 2;
  538.     }
  539.  
  540.     for (i = 1; i < 4; i++) {  /* Try up to 999 times */
  541.     power *= 10;
  542.     *bp++ = '*';   /* Put a star on the end */
  543.     *bp-- = '\0';
  544.  
  545.     n = zxpand(buf);  /* Expand the resulting wild name */
  546.  
  547.     while (n-- > 0) {  /* Find any existing name_d files */
  548.         xp = *mtchptr++;
  549.         xp += len;
  550.         if (*xp == '_') {
  551.         t = atoi(xp+1);
  552.         if (t > d) d = t; /* Get maximum d */
  553.         }
  554.     }
  555.     if (d < power-1) {
  556.         sprintf(bp,"_%d",d+1); /* Make name_(d+1) */
  557.         *s = buf;
  558.         return;
  559.     }
  560.     bp--; len--;
  561.     }
  562. /* If we ever get here, we'll overwrite the xxx~100 file... */
  563. }
  564.  
  565. /* Directory Functions for Unix, written by Jeff Damens, CUCCA, 1984. */
  566.  
  567. /*
  568.  * The path structure is used to represent the name to match.
  569.  * Each slash-separated segment of the name is kept in one
  570.  * such structure, and they are linked together, to make
  571.  * traversing the name easier.
  572.  */
  573.  
  574. struct path {
  575.               char npart[MAXNAMLEN]; /* name part of path segment */
  576.               struct path *fwd;  /* forward ptr */
  577.             };
  578.  
  579. #define SSPACE 2000   /* size of string-generating buffer */
  580. static char sspace[SSPACE];             /* buffer to generate names in */
  581. static char *freeptr,**resptr;          /* copies of caller's arguments */
  582. static int remlen;                      /* remaining length in caller's array*/
  583. static int numfnd;                      /* number of matches found */
  584.  
  585. /*
  586.  * splitpath:
  587.  *  takes a string and splits the slash-separated portions into
  588.  *  a list of path structures.  Returns the head of the list.  The
  589.  *  structures are allocated by malloc, so they must be freed.
  590.  *  Splitpath is used internally by the filename generator.
  591.  *
  592.  * Input: A string.
  593.  * Returns: A linked list of the slash-separated segments of the input.
  594.  */
  595.  
  596. struct path *
  597. splitpath(p)
  598. char *p;
  599. {
  600.     struct path *head,*cur,*prv;
  601.     int i;
  602.     head = prv = NULL;
  603.     if (*p == '/') p++;            /* skip leading slash */
  604.     while (*p != '\0') {
  605.     cur = (struct path *) malloc(sizeof (struct path));
  606.     debug(F101,"splitpath malloc","",cur);
  607.     if (cur == NULL) fatal("malloc fails in splitpath()");
  608.     cur -> fwd = NULL;
  609.     if (head == NULL) head = cur;
  610.     else prv -> fwd = cur;       /* link into chain */
  611.     prv = cur;
  612.     for (i=0; i < MAXNAMLEN && *p != '/' && *p != '\0'; i++)
  613.         cur -> npart[i] = *p++;
  614.     cur -> npart[i] = '\0';      /* end this segment */
  615.     if (i >= MAXNAMLEN) while (*p != '/' && *p != '\0') p++;
  616.     if (*p == '/') p++;
  617.     }
  618.     return(head);
  619. }
  620.  
  621. /*
  622.  * fgen:
  623.  *  This is the actual name generator.  It is passed a string,
  624.  *  possibly containing wildcards, and an array of character pointers.
  625.  *  It finds all the matching filenames and stores them into the array.
  626.  *  The returned strings are allocated from a static buffer local to
  627.  *  this module (so the caller doesn't have to worry about deallocating
  628.  *  them); this means that successive calls to fgen will wipe out
  629.  *  the results of previous calls.  This isn't a problem here
  630.  *  because we process one wildcard string at a time.
  631.  *
  632.  * Input: a wildcard string, an array to write names to, the
  633.  *        length of the array.
  634.  * Returns: the number of matches.  The array is filled with filenames
  635.  *          that matched the pattern.  If there wasn't enough room in the
  636.  *     array, -1 is returned.
  637.  * By: Jeff Damens, CUCCA, 1984.
  638.  */
  639.  
  640. fgen(pat,resarry,len)
  641. char *pat,*resarry[];
  642. int len;
  643. {
  644.     struct path *head;
  645.     char scratch[100+MAXNAMLEN],*sptr;
  646.     head = splitpath(pat);
  647.     if (*pat == '/') {
  648.     scratch[0] = '/';
  649.     sptr = scratch+1;
  650.     *sptr = '\0';
  651.     } else {
  652.     strcpy(scratch,"./");
  653.     sptr = scratch+2;
  654.     }     /* init buffer correctly */
  655.     numfnd = 0;                            /* none found yet */
  656.     freeptr = sspace;   /* this is where matches are copied */
  657.     resptr = resarry;   /* static copies of these so*/
  658.     remlen = len;    /* recursive calls can alter them */
  659.     traverse(head,scratch,sptr);  /* go walk the directory tree */
  660.     for (; head != NULL; head = head -> fwd)
  661.     free(head);    /* return the path segments */
  662.     return(numfnd);   /* and return the number of matches */
  663. }
  664.  
  665. /* traverse:
  666.  *  Walks the directory tree looking for matches to its arguments.
  667.  *  The algorithm is, briefly:
  668.  *   If the current pattern segment contains no wildcards, that
  669.  *   segment is added to what we already have.  If the name so far
  670.  *   exists, we call ourselves recursively with the next segment
  671.  *   in the pattern string; otherwise, we just return.
  672.  *
  673.  *   If the current pattern segment contains wildcards, we open the name
  674.  *   we've accumulated so far (assuming it is really a directory), then read
  675.  *   each filename in it, and, if it matches the wildcard pattern segment, add
  676.  *   that filename to what we have so far and call ourselves recursively on the
  677.  *   next segment.
  678.  *
  679.  *   Finally, when no more pattern segments remain, we add what's accumulated
  680.  *   so far to the result array and increment the number of matches.
  681.  *
  682.  * Input: a pattern path list (as generated by splitpath), a string
  683.  *   pointer that points to what we've traversed so far (this
  684.  *   can be initialized to "/" to start the search at the root
  685.  *   directory, or to "./" to start the search at the current
  686.  *   directory), and a string pointer to the end of the string
  687.  *   in the previous argument.
  688.  * Returns: nothing.
  689.  */
  690. traverse(pl,sofar,endcur)
  691. struct path *pl;
  692. register char *sofar,*endcur;
  693. {
  694.     DIR *fd, *opendir();
  695.     struct direct *dirbuf;
  696.     debug(F110,"traverse ",sofar,0);
  697.     if (pl == NULL) {
  698.     *--endcur = '\0';        /* end string, overwrite trailing / */
  699.     addresult(sofar);
  700.     return;
  701.     }
  702.     if (!iswild(pl -> npart)) {
  703.     strcpy(endcur,pl -> npart);
  704.     endcur += strlen(endcur);
  705.     if (access(sofar,S_IFDIR) == 0) { /* if current piece exists & dir */
  706.         *endcur++ = '/';        /* add slash to end */
  707.         *endcur = '\0';        /* and end the string */
  708.         traverse(pl -> fwd,sofar,endcur);
  709.     } else if(access(sofar,0) == 0 && pl->fwd==NULL) {
  710.         addresult(sofar);
  711.     }
  712.     return;
  713.     }
  714.  
  715. /* segment contains wildcards, have to search directory */
  716.     *--endcur = '\0';            /* end current string */
  717.     if (access(sofar,S_IFDIR) < 0) {
  718.         debug(F111,"traverse can't access directory",sofar,errno);
  719.     return;    /* doesn't exist, forget it */
  720.     }
  721.     if ((fd = opendir(sofar)) == NULL) {
  722.         debug(F111,"traverse can't open directory",sofar,errno);
  723.         return;    /* can't open, forget it */
  724.     }
  725.     *endcur++ = '/';
  726.     while (dirbuf = readdir(fd)) {
  727.     if (dirbuf->d_addr != 0) {
  728.         /* Get a null terminated copy!!! */
  729.         strncpy(endcur,dirbuf->d_name,MAXNAMLEN);
  730.         if(match(pl -> npart,endcur)) {
  731.             char *eos;
  732.             eos = endcur + strlen(endcur);
  733.             *eos++ = '/';            /* end this segment */
  734.             *eos = '\0';
  735.             traverse(pl -> fwd,sofar,eos);
  736.         }
  737.     }
  738.     }
  739.     closedir(fd);
  740. }
  741.  
  742. /*
  743.  * addresult:
  744.  *  Adds a result string to the result array.  Increments the number
  745.  *  of matches found, copies the found string into our string
  746.  *  buffer, and puts a pointer to the buffer into the caller's result
  747.  *  array.  Our free buffer pointer is updated.  If there is no
  748.  *  more room in the caller's array, the number of matches is set to -1.
  749.  * Input: a result string.
  750.  * Returns: nothing.
  751.  */
  752.  
  753. addresult(str)
  754. register char *str;
  755. {
  756.     register int l;
  757.     if (strncmp(str,"./",2) == 0) str += 2;
  758.     if (--remlen < 0) {
  759.     numfnd = -1;
  760.     return;
  761.     }
  762.     l = strlen(str) + 1;   /* size this will take up */
  763.     if ((freeptr + l) > &sspace[SSPACE]) {
  764.     numfnd = -1;   /* do not record if not enough space */
  765.     return;
  766.     }
  767.     strcpy(freeptr,str);
  768.     *resptr++ = freeptr;
  769.     freeptr += l;
  770.     numfnd++;
  771. }
  772.  
  773. iswild(str)
  774. register char *str;
  775. {
  776.     register char c;
  777.     while ((c = *str++) != '\0')
  778.     if (c == '*' || c == '?') return(1);
  779.     return(0);
  780. }
  781.  
  782. /*
  783.  * match:
  784.  *  pattern matcher.  Takes a string and a pattern possibly containing
  785.  *  the wildcard characters '*' and '?'.  Returns true if the pattern
  786.  *  matches the string, false otherwise.
  787.  * Input: a string and a wildcard pattern.
  788.  * Returns: 1 if match, 0 if no match.
  789.  */
  790.  
  791. match(pattern,string) char *pattern,*string; {
  792.     int i;
  793.     i = _cmpnam(string,pattern,strlen(pattern))==0;
  794.     debug(F111,"Match ",string,i);
  795.     return i;
  796. }
  797.  
  798. /* emulate unix perror function */
  799.  
  800. perror(string)
  801. char *string;
  802. {
  803.     extern int errno;
  804.     fprintf(stderr,"%s ERRNO: %d\n",string,errno);
  805. }
  806.