home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / ckc095.zip / ckifio.c < prev    next >
C/C++ Source or Header  |  1989-12-05  |  28KB  |  918 lines

  1. char *ckzv = "Amiga file support, 4F(005) 15 Oct 89";
  2.  
  3. /* C K I F I O  --  Kermit file system support for the Amiga */
  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.  Modified for Amiga by Jack J. Rouse, The Software Distillery
  14.  
  15.  Further modified for C Kermit version 4F(095) by Stephen Walton,
  16.  California State University, Northridge, ecphssrw@afws.csun.edu
  17. */
  18.  
  19. /* Includes */
  20.  
  21. #include "ckcker.h"        /* Kermit definitions */
  22. #include "ckcdeb.h"        /* Typedefs, formats for debug() */
  23. #include <stdio.h>        /* Unix Standard i/o */
  24. #include <ctype.h>
  25. #define MAXNAMLEN 30
  26.  
  27. char *ckzsys = " Amiga";
  28.  
  29. /* Definitions of some Amiga system commands */
  30.  
  31. char *DIRCMD = "list ";        /* For directory listing */
  32. char *DELCMD = "delete ";        /* For file deletion */
  33. char *TYPCMD = "type ";            /* For typing a file */
  34. char *PWDCMD = "cd ";            /* For saying where I am */
  35.  
  36. char *SPACMD = "info ";
  37.  
  38. char *SPACM2 = "info ";            /* should be space in specified directory */
  39.  
  40. char *WHOCMD = "status ";        /* Check process status */
  41.  
  42. #define MAXWLD 300
  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 (simply exits)
  68.  */
  69.  
  70. /* Declarations */
  71.  
  72. FILE *fp[ZNFILS] = {             /* File pointers */
  73.     NULL, NULL, NULL, NULL, NULL, NULL, NULL };
  74.  
  75. /* (PWP) external def. of things used in buffered file input and output */
  76. extern CHAR zinbuffer[], zoutbuffer[];
  77. extern CHAR *zinptr, *zoutptr;
  78. extern int zincnt, zoutcnt;
  79.  
  80. static long iflen = -1;            /* Input file length. */
  81. static long oflen = -1;            /* Output file length. */
  82.  
  83. static int fcount;            /* Number of files in wild group */
  84. static char  nambuf[MAXNAMLEN+2];    /* Buffer for a filename */
  85. char *malloc(), *strcpy();        /* System functions */
  86. char *strrchr();
  87.  
  88. static char *mtchs[MAXWLD],        /* Matches found for filename */
  89.      **mtchptr;                /* Pointer to current match */
  90.  
  91. /* utility functions from ckiutl.c */
  92. extern int existobj();
  93. struct DirHandle    /* fake structure definition */
  94. {
  95.     int _foo_;
  96. };
  97. extern struct DirHandle *opendir();
  98. extern char *readdir();
  99. extern closedir();
  100.  
  101. /*  Z K S E L F  --  Kill Self: log out own job, if possible.  */
  102.  
  103. zkself() {                /* For "bye", but no guarantee! */
  104.     doexit(GOOD_EXIT);
  105. }
  106.  
  107. /*  Z O P E N I  --  Open an existing file for input. */
  108.  
  109. zopeni(n,name) int n; char *name; {
  110.     debug(F111," zopeni",name,n);
  111.     debug(F101,"  fp","",(int) fp[n]);
  112.     if (chkfn(n) != 0) return(0);
  113.     if (n == ZSYSFN) {            /* Input from a system function? */
  114.         debug(F110," invoking zxcmd",name,0);
  115.         *nambuf = '\0';            /* Invalidate file name */
  116.     return(zxcmd(name));        /* Try to fork the command */
  117.     }
  118.     if (n == ZSTDIO) {            /* Standard input? */
  119.     if (isatty(0)) {
  120.         ermsg("Terminal input not allowed");
  121.         debug(F110,"zopeni: attempts input from unredirected stdin","",0);
  122.         return(0);
  123.     }
  124.     fp[ZIFILE] = stdin;
  125.     return(1);
  126.     }
  127.     fp[n] = fopen(name,"r");        /* Real file. */
  128.     debug(F111," zopeni", name, (int) fp[n]);
  129.     if (fp[n] == NULL) perror("zopeni");
  130.     return((fp[n] != NULL) ? 1 : 0);
  131. }
  132.  
  133. /*  Z O P E N O  --  Open a new file for output.  */
  134.  
  135. zopeno(n,name) int n; char *name; {
  136.     debug(F111," zopeno",name,n);
  137.     if (chkfn(n) != 0) return(0);
  138.     if ((n == ZCTERM) || (n == ZSTDIO)) {   /* Terminal or standard output */
  139.     fp[ZOFILE] = stdout;
  140.     debug(F101," fp[]=stdout", "", (int) fp[n]);
  141.     return(1);
  142.     }
  143.     fp[n] = fopen(name,"w");        /* A real file, try to open */
  144.     if (fp[n] == NULL) {
  145.         perror("zopeno can't open");
  146.     } else {
  147.         if (n == ZDFILE) setbuf(fp[n],NULL); /* Debugging file unbuffered */
  148.     }
  149.     zoutcnt = 0;        /* (PWP) reset output buffer */
  150.     zoutptr = zoutbuffer;
  151.     if (n != ZDFILE)
  152.       debug(F101, " fp[n]", "", (int) fp[n]);
  153.     return((fp[n] != NULL) ? 1 : 0);
  154. }
  155.  
  156. /*  Z C L O S E  --  Close the given file.  */
  157.  
  158. /*  Returns 0 if arg out of range, 1 if successful, -1 if close failed.  */
  159.  
  160. zclose(n) int n; {
  161.     int x, x2;
  162.  
  163.     if (chkfn(n) < 1) return(0);    /* Check range of n */
  164.  
  165.     if ((n == ZOFILE) && (zoutcnt > 0))    /* (PWP) output leftovers */
  166.       x2 = zoutdump();
  167.     else
  168.       x2 = 0;
  169.  
  170.     if ((n == ZIFILE) && fp[ZSYSFN]) {    /* If system function */
  171.         x = zclosf();            /* do it specially */
  172.     } else {
  173.         if ((fp[n] != stdout) && (fp[n] != stdin)) x = fclose(fp[n]);
  174.     fp[n] = NULL;
  175.     }
  176.     iflen = -1;                /* Invalidate file length */
  177.     if (x == EOF)            /* if we got a close error */
  178.     return (-1);
  179.     else if (x2 < 0)        /* or an error flushing the last buffer */
  180.     return (-1);        /* then return an error */
  181.     else
  182.     return (1);
  183. }
  184.  
  185. /*  Z C H I N  --  Get a character from the input file.  */
  186.  
  187. /*  Returns -1 if EOF, 0 otherwise with character returned in argument  */
  188.  
  189. zchin(n,c) int n; char *c; {
  190.     int a;
  191.  
  192.     /* (PWP) Just in case this gets called when it shoudn't */
  193.     if (n == ZIFILE)
  194.     return (zminchar());
  195.  
  196.     /* if (chkfn(n) < 1) return(-1); */
  197.     a = getc(fp[n]);
  198.     if (a == EOF) return(-1);
  199.     *c = a & 0377;
  200.     return(0);
  201. }
  202.  
  203. /*
  204.  * (PWP) (re)fill the buffered input buffer with data.  All file input
  205.  * should go through this routine, usually by calling the zminchar()
  206.  * macro (in ckcker.h).
  207.  */
  208.  
  209. zinfill() {
  210.     zincnt = fread(zinbuffer, sizeof (char), INBUFSIZE, fp[ZIFILE]);
  211.     if (zincnt == 0) return (-1); /* end of file */
  212.     zinptr = zinbuffer;       /* set pointer to beginning, (== &zinbuffer[0]) */
  213.     zincnt--;            /* one less char in buffer */
  214.     return((int)(*zinptr++) & 0377); /* because we return the first */
  215. }
  216.  
  217. /*  Z S O U T  --  Write a string to the given file, buffered.  */
  218.  
  219. zsout(n,s) int n; char *s; {
  220.     if (chkfn(n) < 1) return(-1);
  221.     fputs(s,fp[n]);
  222.     return(0);
  223. }
  224.  
  225. /*  Z S O U T L  --  Write string to file, with line terminator, buffered  */
  226.  
  227. zsoutl(n,s) int n; char *s; {
  228.     if (chkfn(n) < 1) return(-1);
  229.     fputs(s,fp[n]);
  230.     fputs("\n",fp[n]);
  231.     return(0);
  232. }
  233.  
  234. /*  Z S O U T X  --  Write x characters to file, unbuffered.  */
  235.  
  236. zsoutx(n,s,x) int n, x; char *s; {
  237.     if (chkfn(n) < 1) return(-1);
  238.     return(write(fileno(fp[n]),s,x));
  239. }
  240.  
  241.  
  242. /*  Z C H O U T  --  Add a character to the given file.  */
  243.  
  244. /*  Should return 0 or greater on success, -1 on failure (e.g. disk full)  */
  245.  
  246. zchout(n,c) int n; CHAR c; {
  247.     if (chkfn(n) < 1) return(-1);
  248.     if (n == ZSFILE)
  249.         return(write(fileno(fp[n]),&c,1)); /* Use unbuffered for session log */
  250.     else {                /* Buffered for everything else */
  251.     if (putc(c,fp[n]) == EOF)    /* If true, maybe there was an error */
  252.         return(ferror(fp[n])?-1:0);    /* Check to make sure */
  253.     else                /* Otherwise... */
  254.         return(0);            /* There was no error. */
  255.     }
  256. }
  257.  
  258. /* (PWP) buffered character output routine to speed up file IO */
  259.  
  260. zoutdump() {
  261.     int x;
  262.     zoutptr = zoutbuffer;        /* reset buffer pointer in all cases */
  263.     debug(F101,"zoutdump chars","",zoutcnt);
  264.     if (zoutcnt == 0) {            /* nothing to output */
  265.     return(0);
  266.     } else if (zoutcnt < 0) {        /* unexpected negative value */
  267.     zoutcnt = 0;            /* reset output buffer count */
  268.     return(-1);            /* and fail. */
  269.     }
  270.     if (x = fwrite(zoutbuffer, 1, zoutcnt, fp[ZOFILE])) {
  271.     debug(F101,"zoutdump fwrite wrote","",x);
  272.     zoutcnt = 0;            /* reset output buffer count */
  273.     return(0);            /* things worked OK */
  274.     } else {
  275.     zoutcnt = 0;            /* reset output buffer count */
  276.     x = ferror(fp[ZOFILE]);        /* get error code */
  277.     debug(F101,"zoutdump fwrite error","",x);
  278.     return(x ? -1 : 0);        /* return failure if error */
  279.     }
  280. }
  281.  
  282. /*  C H K F N  --  Internal function to verify file number is ok  */
  283.  
  284. /*
  285.  Returns:
  286.   -1: File number n is out of range
  287.    0: n is in range, but file is not open
  288.    1: n in range and file is open
  289. */
  290. chkfn(n) int n; {
  291.     switch (n) {
  292.     case ZCTERM:
  293.     case ZSTDIO:
  294.     case ZIFILE:
  295.     case ZOFILE:
  296.     case ZDFILE:
  297.     case ZTFILE:
  298.     case ZPFILE:
  299.     case ZSFILE:
  300.     case ZSYSFN: break;
  301.     default:
  302.         debug(F101,"chkfn: file number out of range","",n);
  303.         fprintf(stderr,"?File number out of range - %d\n",n);
  304.         return(-1);
  305.     }
  306.     return( (fp[n] == NULL) ? 0 : 1 );
  307. }
  308.  
  309. /*  Z C H K I  --  Check if input file exists and is readable  */
  310.  
  311. /*
  312.   Returns:
  313.    >= 0 if the file can be read (returns the size).
  314.      -1 if file doesn't exist or can't be accessed,
  315.      -2 if file exists but is not readable (e.g. a directory file).
  316.      -3 if file exists but protected against read access.
  317. */
  318. long
  319. zchki(name) char *name; {
  320.     long size, readstat();
  321.  
  322.     size = readstat(name);
  323.     debug(F111,"zchki file size",name,(int)size);
  324.     iflen = size;
  325.     strcpy(nambuf, name);        /* Remember file name globally. */
  326.     return(size);
  327. }
  328.  
  329. /*  Z C H K O  --  Check if output file can be created  */
  330.  
  331. /*
  332.  Returns -1 if write permission for the file would be denied, 0 otherwise.
  333. */
  334. zchko(name) char *name; {
  335.     int rc = writestat(name);
  336.  
  337. #ifdef DEBUG
  338.     if (rc < 0)
  339.     debug(F111,"zchko access failed:",name,NULL);
  340.     else
  341.     debug(F111,"zchko access ok:",name,NULL);
  342. #endif
  343.     return(rc);
  344. }
  345.  
  346. /*  Z D E L E T  --  Delete the named file.  */
  347.  
  348. zdelet(name) char *name; {
  349.     unlink(name);
  350. }
  351.  
  352.  
  353. /*  Z R T O L  --  Convert remote filename into local form  */
  354.  
  355. /*  For AMIGA, this means changing uppercase letters to lowercase.  */
  356.  
  357. zrtol(name,name2) char *name, *name2; {
  358.     for ( ; *name != '\0'; name++) {
  359.         *name2++ = isupper(*name) ? tolower(*name) : *name;
  360.     }
  361.     *name2 = '\0';
  362.     debug(F110,"zrtol:",name2,0);
  363. }
  364.  
  365.  
  366. /*  Z L T O R  --  Local TO Remote */
  367.  
  368. /*  Convert filename from local format to common (remote) form.  */
  369.  
  370. zltor(name,name2) char *name, *name2; {
  371.     char work[100], *cp, *pp;
  372.     int dc = 0;
  373.  
  374.     debug(F110,"zltor",name,0);
  375.     pp = work;
  376.     if ((cp = strrchr(name, ':')) == NULL)
  377.         cp = name;
  378.     else
  379.         ++cp;
  380.  
  381.     for (; *cp != '\0'; cp++) {    /* strip path name */
  382.         if (*cp == '/') {
  383.         dc = 0;
  384.         pp = work;
  385.     }
  386.     else if (islower(*cp)) *pp++ = toupper(*cp); /* Uppercase letters */
  387.     else if (*cp == '~') *pp++ = 'X';    /* Change tilde to 'X' */
  388.     else if (*cp == '#') *pp++ = 'X';    /* Change number sign to 'X' */
  389.     else if ((*cp == '.') && (++dc > 1)) *pp++ = 'X'; /* & extra dots */
  390.     else *pp++ = *cp;
  391.     }
  392.     *pp = '\0';                /* Tie it off. */
  393.     cp = name2;                /* If nothing before dot, */
  394.     if (*work == '.') *cp++ = 'X';    /* insert 'X' */
  395.     strcpy(cp,work);
  396.     debug(F110," name2",name2,0);
  397. }    
  398.  
  399. /*  Z H O M E  --  Return pointer to user's home directory  */
  400.  
  401. /* we return "s:", which is where startup scripts are found */
  402. char *
  403. zhome() {
  404.     return("s:");        /* very approximately */
  405. }
  406.  
  407. /*  Z C H D I R  --  Change directory  */
  408.  
  409. zchdir(dirnam) char *dirnam; {
  410.     return((chdir(dirnam) == 0) ? 1 : 0);
  411. }
  412.  
  413. /*  Z G T D I R  --  Return pointer to user's current directory  */
  414.  
  415. char *
  416. zgtdir() {
  417.     return("");
  418. }
  419.  
  420. /*  Z X C M D -- Run a system command so its output can be read like a file */
  421. zxcmd(comand) char *comand; {
  422.     FILE *f, *pipeopen();
  423.  
  424.     if ((f = pipeopen(comand)) == NULL) return(0);
  425.     fp[ZIFILE] = f;            /* open a stream for it */
  426.     fp[ZSYSFN] = fp[ZIFILE];    /* Remember. */
  427.     return(1);
  428. }
  429.  
  430. /*  Z C L O S F  - wait for the child fork to terminate and close the pipe. */
  431.  
  432. zclosf() {
  433.     pipeclose(fp[ZIFILE]);
  434.     fp[ZIFILE] = fp[ZSYSFN] = NULL;
  435.     return(1);
  436. }
  437.  
  438. /*  Z X P A N D  --  Expand a wildcard string into an array of strings  */
  439. /*
  440.   Returns the number of files that match fn1, with data structures set up
  441.   so that first file (if any) will be returned by the next znext() call.
  442. */
  443. zxpand(fn) char *fn; {
  444.     fcount = fgen(fn,mtchs,MAXWLD);    /* Look up the file. */
  445.     if (fcount > 0) {
  446.     mtchptr = mtchs;        /* Save pointer for next. */
  447.     }
  448.     debug(F111,"zxpand",mtchs[0],fcount);
  449.     return(fcount);
  450. }
  451.  
  452.  
  453. /*  Z N E X T  --  Get name of next file from list created by zxpand(). */
  454. /*
  455.  Returns >0 if there's another file, with its name copied into the arg string,
  456.  or 0 if no more files in list.
  457. */
  458. znext(fn) char *fn; {
  459.     if (fcount-- > 0) strcpy(fn,*mtchptr++);
  460.     else *fn = '\0';
  461.     debug(F111,"znext",fn,fcount+1);
  462.     return(fcount+1);
  463. }
  464.  
  465.  
  466. /*  Z N E W N  --  Make a new name for the given file  */
  467.  
  468. znewn(fn,s) char *fn, **s; {
  469.     static char buf[100];
  470.     char *bp;
  471.     int len = 0, d;
  472. #ifdef MAXNAMLEN
  473.     int maxlen = MAXNAMLEN;
  474. #else
  475.     int maxlen = 14;
  476. #endif
  477.  
  478.     bp = buf;
  479.     while (*fn) {            /* Copy name into buf */
  480.     *bp++ = *fn++;
  481.     len++;
  482.     }
  483.     if (len > maxlen-3) bp -= 3;    /* Don't let it get too long */
  484.  
  485.     /* 
  486.      * On the Amiga, it takes much less time to determine
  487.      * if a given file exists than to read all the file names in
  488.      * a directory (or even just names with a certain prefix).
  489.      */
  490.     d = 0;
  491.     do {
  492.     sprintf(bp, "~%d", ++d);
  493.     } while (zchki(buf) != -1 && d < 100);
  494.  
  495.     *s = buf;
  496. }
  497. /*  Z S A T T R */
  498. /*
  499.  Fills in a Kermit file attribute structure for the file which is to be sent.
  500.  Returns 0 on success with the structure filled in, or -1 on failure.
  501.  If any string member is null, then it should be ignored.
  502.  If any numeric member is -1, then it should be ignored.
  503. */
  504. zsattr(xx) struct zattr *xx; {
  505.     long k;
  506.     char *zfcdat();
  507.  
  508.     k = iflen % 1024L;            /* File length in K */
  509.     if (k != 0L) k = 1L;
  510.     xx->lengthk = (iflen / 1024L) + k;
  511.     xx->type.len = 0;            /* File type can't be filled in here */
  512.     xx->type.val = "";
  513.     if (*nambuf) {
  514.     xx->date.val = zfcdat(nambuf);    /* File creation date */
  515.     xx->date.len = strlen(xx->date.val);
  516.     } else {
  517.     xx->date.len = 0;
  518.     xx->date.val = "";
  519.     }
  520.     xx->creator.len = 0;        /* File creator */
  521.     xx->creator.val = "";
  522.     xx->account.len = 0;        /* File account */
  523.     xx->account.val = "";
  524.     xx->area.len = 0;            /* File area */
  525.     xx->area.val = "";
  526.     xx->passwd.len = 0;            /* Area password */
  527.     xx->passwd.val = "";
  528.     xx->blksize = -1L;            /* File blocksize */
  529.     xx->access.len = 0;            /* File access */
  530.     xx->access.val = "";
  531.     xx->encoding.len = 0;        /* Transfer syntax */
  532.     xx->encoding.val = 0;
  533.     xx->disp.len = 0;            /* Disposition upon arrival */
  534.     xx->disp.val = "";
  535.     xx->lprotect.len = 0;        /* Local protection */
  536.     xx->lprotect.val = "";
  537.     xx->gprotect.len = 0;        /* Generic protection */
  538.     xx->gprotect.val = "";
  539.     xx->systemid.len = 2;        /* System ID length */
  540.     xx->systemid.val = "L3";        /* Amiga system ID code */
  541.     xx->recfm.len = 0;            /* Record format */
  542.     xx->recfm.val = "";
  543.     xx->sysparam.len = 0;        /* System-dependent parameters */
  544.     xx->sysparam.val = "";
  545.     xx->length = iflen;            /* Length */
  546.     return(0);
  547. }
  548.  
  549. /* Z F C D A T -- Return a string containing the time stamp for a file */
  550.  
  551. char *
  552. zfcdat(name) char *name; {
  553.  
  554. #ifdef TIMESTAMP
  555.  
  556.     struct stat buffer;
  557.     struct tm *time_stamp, *localtime();
  558.     static char datbuf[20];
  559.  
  560.     datbuf[0] = '\0';
  561.     if(stat(name,&buffer) != 0) {
  562.     debug(F110,"zcfdat stat failed",name,0);
  563.     return("");
  564.     }
  565.     time_stamp = localtime(&(buffer.st_mtime));
  566.     if (time_stamp->tm_year < 1900) time_stamp->tm_year += 1900;
  567.     sprintf(datbuf,"%-4.4d%02.2d%02.2d %002.2d:%002.2d:%002.2d",
  568.         time_stamp->tm_year,
  569.         time_stamp->tm_mon + 1,
  570.         time_stamp->tm_mday,
  571.         time_stamp->tm_hour,
  572.         time_stamp->tm_min,
  573.         time_stamp->tm_sec);
  574.     debug(F111,"zcfdat",datbuf,strlen(datbuf));
  575.     return(datbuf);
  576. #else
  577.     return("");
  578. #endif /* TIMESTAMP */
  579. }
  580.  
  581. /*
  582.  * Dummy functions for the Amiga.  Sending mail cannot be done;  I haven't
  583.  * decided how to handle print requests yet.
  584.  */
  585.  
  586. zmail(p,f) char *p; char *f; {        /* Send file f as mail to address p */
  587.     return(0);
  588. }
  589.  
  590. zprint(p,f) char *p; char *f; {        /* Print file f with flags p */
  591.     return(0);
  592. }
  593.  
  594.  
  595. /* Directory Functions for Unix, written by Jeff Damens, CUCCA, 1984. */
  596.  
  597. /*
  598.  * The path structure is used to represent the name to match.
  599.  * Each slash-separated segment of the name is kept in one
  600.  * such structure, and they are linked together, to make
  601.  * traversing the name easier.
  602.  */
  603.  
  604. struct path {
  605.               char npart[MAXNAMLEN];    /* name part of path segment */
  606.               struct path *fwd;        /* forward ptr */
  607.             };
  608.  
  609. #define SSPACE 4000            /* size of string-generating buffer */
  610.  
  611. static char sspace[SSPACE];             /* buffer to generate names in */
  612. static char *freeptr,**resptr;             /* copies of caller's arguments */
  613. static int remlen;                      /* remaining length in caller's array*/
  614. static int numfnd;                      /* number of matches found */
  615.  
  616. /*
  617.  * splitpath:
  618.  *  takes a string and splits the slash-separated portions into
  619.  *  a list of path structures.  Returns the head of the list.  The
  620.  *  structures are allocated by malloc, so they must be freed.
  621.  *  Splitpath is used internally by the filename generator.
  622.  *
  623.  * Input: A string.
  624.  * Returns: A linked list of the slash-separated segments of the input.
  625.  */
  626.  
  627. struct path *
  628. splitpath(p)
  629. char *p;
  630. {
  631.  struct path *head,*cur,*prv;
  632.  int i;
  633.  head = prv = NULL;
  634.  if (*p == '/') p++;            /* skip leading slash */
  635.  while (*p != '\0')
  636.  {
  637.    cur = (struct path *) malloc(sizeof (struct path));
  638.    debug(F101,"splitpath malloc","",cur);
  639.    if (cur == NULL) fatal("malloc fails in splitpath()");
  640.    cur -> fwd = NULL;
  641.    if (head == NULL) head = cur;
  642.    else prv -> fwd = cur;       /* link into chain */
  643.    prv = cur;
  644.    for (i=0; i < MAXNAMLEN && *p != '/' && *p != '\0'; i++)
  645.      cur -> npart[i] = *p++;
  646.    cur -> npart[i] = '\0';      /* end this segment */
  647.    if (i >= MAXNAMLEN) while (*p != '/' && *p != '\0') p++;
  648.    if (*p == '/') p++;
  649.  }
  650.  return(head);
  651. }
  652.  
  653. /*
  654.  * fgen:
  655.  *  This is the actual name generator.  It is passed a string,
  656.  *  possibly containing wildcards, and an array of character pointers.
  657.  *  It finds all the matching filenames and stores them into the array.
  658.  *  The returned strings are allocated from a static buffer local to
  659.  *  this module (so the caller doesn't have to worry about deallocating
  660.  *  them); this means that successive calls to fgen will wipe out
  661.  *  the results of previous calls.  This isn't a problem here
  662.  *  because we process one wildcard string at a time.
  663.  *
  664.  * Input: a wildcard string, an array to write names to, the
  665.  *        length of the array.
  666.  * Returns: the number of matches.  The array is filled with filenames
  667.  *          that matched the pattern.  If there wasn't enough room in the
  668.  *        array, -1 is returned.
  669.  * By: Jeff Damens, CUCCA, 1984.
  670.  */
  671.  
  672. fgen(pat,resarry,len)
  673. char *pat,*resarry[];
  674. int len;
  675. {
  676.  struct path *head;
  677.  char scratch[100],*sptr;
  678.  char *tail;
  679.  
  680.  if ((tail = strrchr(pat, ':')) == NULL) /* locate unit name */
  681.   tail = pat;                /* no unit name */
  682.  else
  683.   ++tail;                /* eat ':' */
  684.  while (*tail == '/')            /* eat parent path slashes */
  685.   ++tail;
  686.  sptr = scratch;            /* init buffer correctly */
  687.  while (pat < tail)
  688.   *sptr++ = *pat++;
  689.  head = splitpath(pat);
  690.  numfnd = 0;                            /* none found yet */
  691.  freeptr = sspace;            /* this is where matches are copied */
  692.  resptr = resarry;            /* static copies of these so*/
  693.  remlen = len;                /* recursive calls can alter them */
  694.  traverse(head,scratch,sptr);        /* go walk the directory tree */
  695.  for (; head != NULL; head = head -> fwd)
  696.    free(head);                /* return the path segments */
  697.  return(numfnd);            /* and return the number of matches */
  698. }
  699.  
  700. /* traverse:
  701.  *  Walks the directory tree looking for matches to its arguments.
  702.  *  The algorithm is, briefly:
  703.  *   If the current pattern segment contains no wildcards, that
  704.  *   segment is added to what we already have.  If the name so far
  705.  *   exists, we call ourselves recursively with the next segment
  706.  *   in the pattern string; otherwise, we just return.
  707.  *
  708.  *   If the current pattern segment contains wildcards, we open the name
  709.  *   we've accumulated so far (assuming it is really a directory), then read 
  710.  *   each filename in it, and, if it matches the wildcard pattern segment, add
  711.  *   that filename to what we have so far and call ourselves recursively on the
  712.  *   next segment.
  713.  *
  714.  *   Finally, when no more pattern segments remain, we add what's accumulated
  715.  *   so far to the result array and increment the number of matches.
  716.  *
  717.  * Input: a pattern path list (as generated by splitpath), a string
  718.  *      pointer that points to what we've traversed so far (this
  719.  *      can be initialized to "/" to start the search at the root
  720.  *      directory, or to "./" to start the search at the current
  721.  *      directory), and a string pointer to the end of the string
  722.  *      in the previous argument.
  723.  * Returns: nothing.
  724.  */
  725. traverse(pl,sofar,endcur)
  726. struct path *pl;
  727. char *sofar,*endcur;
  728. {
  729.  struct DirHandle *fd;
  730.  char *fname;
  731.  
  732.  if (pl == NULL)
  733.  {
  734.   *--endcur = '\0';                    /* end string, overwrite trailing / */
  735.   addresult(sofar);
  736.   return;
  737.  }
  738.  if (!iswild(pl -> npart))
  739.  {
  740.   strcpy(endcur,pl -> npart);
  741.   endcur += strlen(pl -> npart);
  742.   *endcur = '\0';                         /* end current string */
  743.   if (existobj(sofar))            /* if current piece exists */
  744.   {
  745.       *endcur++ = '/';            /* add slash to end */
  746.       *endcur = '\0';            /* and end the string */
  747.       traverse(pl -> fwd,sofar,endcur);
  748.   }
  749.   return;
  750.  }
  751. /* cont'd... */
  752.  
  753. /*...traverse, cont'd */
  754.  
  755. /* segment contains wildcards, have to search directory */
  756.  *endcur = '\0';                            /* end current string */
  757.  if ((fd = opendir(sofar)) == NULL) return;      /* can't open, forget it */
  758.  while (fname = readdir(fd))
  759. {
  760.   if (match(pl -> npart,fname)) {
  761.     char *eos;
  762.     strcpy(endcur,fname);
  763.     eos = endcur + strlen(fname);
  764.     *eos = '/';                    /* end this segment */
  765.     traverse(pl -> fwd,sofar,eos+1);
  766.   }
  767. }
  768.  closedir(fd);
  769. }
  770.  
  771. /*
  772.  * addresult:
  773.  *  Adds a result string to the result array.  Increments the number
  774.  *  of matches found, copies the found string into our string
  775.  *  buffer, and puts a pointer to the buffer into the caller's result
  776.  *  array.  Our free buffer pointer is updated.  If there is no
  777.  *  more room in the caller's array, the number of matches is set to -1.
  778.  * Input: a result string.
  779.  * Returns: nothing.
  780.  */
  781.  
  782. addresult(str)
  783. char *str;
  784. {
  785.  int l;
  786.  if (--remlen < 0) {
  787.   numfnd = -1;
  788.   return;
  789.  }
  790.  l = strlen(str) + 1;            /* size this will take up */
  791.  if ((freeptr + l) > &sspace[SSPACE]) {
  792.     numfnd = -1;            /* do not record if not enough space */
  793.     return;
  794.   }
  795.  strcpy(freeptr,str);
  796.  *resptr++ = freeptr;
  797.  freeptr += l;
  798.  numfnd++;
  799. }
  800.  
  801. iswild(str)
  802. char *str;
  803. {
  804.  char c;
  805.  while ((c = *str++) != '\0')
  806.    if (c == '*' || c == '?') return(1);
  807.  return(0);
  808. }
  809.  
  810. #ifdef OLDMATCH
  811. /*
  812.  * match:
  813.  *  pattern matcher.  Takes a string and a pattern possibly containing
  814.  *  the wildcard characters '*' and '?'.  Returns true if the pattern
  815.  *  matches the string, false otherwise.
  816.  * by: Jeff Damens, CUCCA
  817.  *
  818.  * Input: a string and a wildcard pattern.
  819.  * Returns: 1 if match, 0 if no match.
  820.  */
  821.  
  822. match(pattern,string)
  823. register char *pattern,*string;
  824. {
  825.     char *psave,*ssave;            /* back up pointers for failure */
  826.     psave = ssave = NULL;
  827.     while (1) {
  828.     for (;
  829.          tolower(*pattern) == tolower(*string);
  830.          pattern++,string++)  /* skip first */
  831.         if (*string == '\0') return(1);    /* end of strings, succeed */
  832.     if (*string != '\0' && *pattern == '?') {
  833.         pattern++;            /* '?', let it match */
  834.         string++;
  835.     } else if (*pattern == '*') {    /* '*' ... */
  836.         psave = ++pattern;        /* remember where we saw it */
  837.         ssave = string;        /* let it match 0 chars */
  838.     } else if (ssave != NULL && *ssave != '\0') {    /* if not at end  */
  839.                       /* ...have seen a star */
  840.         string = ++ssave;        /* skip 1 char from string */
  841.         pattern = psave;        /* and back up pattern */
  842.     } else return(0);        /* otherwise just fail */
  843.     }
  844. }
  845. #else
  846. /*
  847.  * match -- match wildcard pattern to string
  848.  *    allows multiple '*'s and works without backtracking
  849.  *    upper and lower case considered equivalent
  850.  *    written by Jack Rouse
  851.  *    working without backtracking is cute, but is this usually going
  852.  *       to be the most efficient method?
  853.  */
  854. match(pattern, target)
  855. register char *pattern, *target;
  856. {
  857.     int link[MAXNAMLEN];        /* list of matches to try in pattern */
  858.     register int first, last;    /* first and last items in list */
  859.     register int here, next;    /* current and next list items */
  860.     char lowch;            /* current target character */
  861.  
  862.     /* start out trying to match at first position */
  863.     first = last = 0;
  864.     link[0] = -1;
  865.  
  866.     /* go through the target */
  867.     for (; *target; ++target)
  868.     {
  869.         /* get lowercase target character */
  870.         lowch = tolower(*target);
  871.  
  872.         /* go through all positions this round and build next round */
  873.         last = -1;
  874.         for (here = first; here >= 0; here = next)
  875.         {
  876.             next = link[here];
  877.             switch (pattern[here])
  878.             {
  879.             case '*':
  880.                 /* try match at here+1 this round */
  881.                 /*!!!check needed only if "**" allowed? */
  882.                 if (next != here + 1)
  883.                 {
  884.                     link[here + 1] = next;
  885.                     next = here + 1;
  886.                 }
  887.                 /* retry match at here next round */
  888.                 break;
  889.             default:
  890.                 if (tolower(pattern[here]) != lowch)
  891.                     continue;
  892.                 /* matched, fall through */
  893.             case '?':
  894.                 /* try match at here+1 next round */
  895.                 ++here;
  896.                 break;
  897.             }
  898.             /* try match at here value next round */
  899.             if (last < 0)
  900.                 first = here;
  901.             else
  902.                 link[last] = here;
  903.             last = here;
  904.         }
  905.         /* if no positions left, match failed */
  906.         if (last == -1) return(0);
  907.         /* terminate list */
  908.         link[last] = -1;
  909.     }
  910.  
  911.     /* at end of target, skip empty matches */
  912.     while (pattern[last] == '*')
  913.         ++last;
  914.  
  915.     return(pattern[last] == '\0');
  916. }
  917. #endif
  918.