home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / minix1 / mxufio.c < prev    next >
C/C++ Source or Header  |  2020-01-01  |  26KB  |  949 lines

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