home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / cku301.tar / ckufio.c < prev    next >
C/C++ Source or Header  |  2011-07-14  |  252KB  |  8,541 lines

  1. /* C K U F I O  --  Kermit file system support for UNIX, Aegis, and Plan 9 */
  2.  
  3. #define CK_NONBLOCK                     /* See zoutdump() */
  4.  
  5. #ifdef aegis
  6. char *ckzv = "Aegis File support, 9.0.215, 13 Jun 2011";
  7. #else
  8. #ifdef Plan9
  9. char *ckzv = "Plan 9 File support, 9.0.215, 13 Jun 2011";
  10. #else
  11. char *ckzv = "UNIX File support, 9.0.215, 13 Jun 2011";
  12. #endif /* Plan9 */
  13. #endif /* aegis */
  14. /*
  15.   Author: Frank da Cruz <fdc@columbia.edu>,
  16.   Columbia University Academic Information Systems, New York City,
  17.   and others noted in the comments below.  Note: CUCCA = Previous name of
  18.   Columbia University Academic Information Systems.  Note: AcIS = Previous
  19.   of Columbia University Information Technology.
  20.  
  21.   Copyright (C) 1985, 2011,
  22.     Trustees of Columbia University in the City of New York.
  23.     All rights reserved.  See the C-Kermit COPYING.TXT file or the
  24.     copyright text in the ckcmai.c module for disclaimer and permissions.
  25. */
  26.  
  27. /*
  28.   NOTE TO CONTRIBUTORS: This file, and all the other C-Kermit files, must be
  29.   compatible with C preprocessors that support only #ifdef, #else, #endif,
  30.   #define, and #undef.  Please do not use #if, logical operators, or other
  31.   preprocessor features in any of the portable C-Kermit modules.  You can,
  32.   of course, use these constructions in platform-specific modules where you
  33.   know they are supported.
  34. */
  35. /* Include Files */
  36.  
  37. #ifdef MINIX2
  38. #define _MINIX
  39. #endif /* MINIX2 */
  40.  
  41. #include "ckcsym.h"
  42. #include "ckcdeb.h"
  43. #include "ckcasc.h"
  44.  
  45. #ifndef NOCSETS
  46. #include "ckcxla.h"
  47. #endif /* NOCSETS */
  48.  
  49. /* To avoid pulling in all of ckuusr.h so we copy the few needed prototypes */
  50.  
  51. struct mtab {                /* Macro table, like keyword table */
  52.     char *kwd;                /* But with pointers for vals */
  53.     char *mval;                /* instead of ints. */
  54.     short flgs;
  55. };
  56. _PROTOTYP( int mlook, (struct mtab [], char *, int) );
  57. _PROTOTYP( int dodo, (int, char *, int) );
  58. _PROTOTYP( int parser, ( int ) );
  59.  
  60. #ifdef COMMENT
  61. /* This causes trouble in C-Kermit 8.0.  I don't remember the original */
  62. /* reason for this being here but it must have been needed at the time... */
  63. #ifdef OSF13
  64. #ifdef CK_ANSIC
  65. #ifdef _NO_PROTO
  66. #undef _NO_PROTO
  67. #endif /* _NO_PROTO */
  68. #endif /* CK_ANSIC */
  69. #endif /* OSF13 */
  70. #endif /* COMMENT */
  71.  
  72. #ifndef HPUXPRE65
  73. #include <errno.h>            /* Error number symbols */
  74. #else
  75. #ifndef ERRNO_INCLUDED
  76. #include <errno.h>            /* Error number symbols */
  77. #endif    /* ERRNO_INCLUDED */
  78. #endif    /* HPUXPRE65 */
  79.  
  80. #include <signal.h>
  81.  
  82. #ifdef MINIX2
  83. #undef MINIX
  84. #undef CKSYSLOG
  85. #include <limits.h>
  86. #include <time.h>
  87. #define NOFILEH
  88. #endif /* MINIX2 */
  89.  
  90. #ifdef MINIX
  91. #include <limits.h>
  92. #include <sys/types.h>
  93. #include <time.h>
  94. #else
  95. #ifdef POSIX
  96. #include <limits.h>
  97. #else
  98. #ifdef SVR3
  99. #include <limits.h>
  100. #endif /* SVR3 */
  101. #endif /* POSIX */
  102. #endif /* MINIX */
  103. /*
  104.   Directory Separator macros, to allow this module to work with both UNIX and
  105.   OS/2: Because of ambiguity with the command line editor escape \ character,
  106.   the directory separator is currently left as / for OS/2 too, because the
  107.   OS/2 kernel also accepts / as directory separator.  But this is subject to
  108.   change in future versions to conform to the normal OS/2 style.
  109. */
  110. #ifndef DIRSEP
  111. #define DIRSEP       '/'
  112. #endif /* DIRSEP */
  113. #ifndef ISDIRSEP
  114. #define ISDIRSEP(c)  ((c)=='/')
  115. #endif /* ISDIRSEP */
  116.  
  117. #ifdef SDIRENT
  118. #define DIRENT
  119. #endif /* SDIRENT */
  120.  
  121. #ifdef XNDIR
  122. #include <sys/ndir.h>
  123. #else /* !XNDIR */
  124. #ifdef NDIR
  125. #include <ndir.h>
  126. #else /* !NDIR, !XNDIR */
  127. #ifdef RTU
  128. #include "/usr/lib/ndir.h"
  129. #else /* !RTU, !NDIR, !XNDIR */
  130. #ifdef DIRENT
  131. #ifdef SDIRENT
  132. #include <sys/dirent.h>
  133. #else
  134. #include <dirent.h>
  135. #endif /* SDIRENT */
  136. #else
  137. #include <sys/dir.h>
  138. #endif /* DIRENT */
  139. #endif /* RTU */
  140. #endif /* NDIR */
  141. #endif /* XNDIR */
  142.  
  143. #ifdef UNIX                             /* Pointer arg to wait() allowed */
  144. #define CK_CHILD                        /* Assume this is safe in all UNIX */
  145. #endif /* UNIX */
  146.  
  147. extern int binary, recursive, stathack;
  148. #ifdef CK_CTRLZ
  149. extern int eofmethod;
  150. #endif /* CK_CTRLZ */
  151.  
  152. #include <pwd.h>                        /* Password file for shell name */
  153. #ifdef CK_SRP
  154. #include <t_pwd.h>                      /* SRP Password file */
  155. #endif /* CK_SRP */
  156.  
  157. #ifdef HPUX10_TRUSTED
  158. #include <hpsecurity.h>
  159. #include <prot.h>
  160. #endif /* HPUX10_TRUSTED */
  161.  
  162. #ifdef COMMENT
  163. /* Moved to ckcdeb.h */
  164. #ifdef POSIX
  165. #define UTIMEH
  166. #else
  167. #ifdef HPUX9
  168. #define UTIMEH
  169. #endif /* HPUX9 */
  170. #endif /* POSIX */
  171. #endif /* COMMENT */
  172.  
  173. #ifdef SYSUTIMEH                        /* <sys/utime.h> if requested,  */
  174. #include <sys/utime.h>                  /* for extra fields required by */
  175. #else                                   /* 88Open spec. */
  176. #ifdef UTIMEH                           /* or <utime.h> if requested */
  177. #include <utime.h>                      /* (SVR4, POSIX) */
  178. #ifndef BSD44
  179. #ifndef V7
  180. /* Not sure why this is here.  What it implies is that the code bracketed
  181.    by SYSUTIMEH is valid on all platforms on which we support time 
  182.    functionality.  But we know that is not true because the BSD44 and V7
  183.    platforms do not support sys/utime.h and the data structures which
  184.    are defined in them.  Now this worked before because prior to today's
  185.    changes the UTIMEH definition for BSD44 and V7 did not take place
  186.    until after SYSUTIMEH was defined.  It also would not have been a 
  187.    problem if the ordering of all the time blocks was consistent.  All but
  188.    one of the blocks were BSD44, V7, SYSUTIMEH, <OTHER>.  That one case
  189.    is where this problem was triggered.
  190. */
  191. #define SYSUTIMEH                       /* Use this for both cases. */
  192. #endif /* V7 */
  193. #endif /* BSD44 */
  194. #endif /* UTIMEH */
  195. #endif /* SYSUTIMEH */
  196.  
  197. #ifndef NOTIMESTAMP
  198. #ifdef POSIX
  199. #ifndef AS400
  200. #define TIMESTAMP
  201. #endif /* AS400 */
  202. #endif /* POSIX */
  203.  
  204. #ifdef BSD44                            /* BSD 4.4 */
  205. #ifndef TIMESTAMP
  206. #define TIMESTAMP                       /* Can do file dates */
  207. #endif /* TIMESTAMP */
  208. #include <sys/time.h>
  209. #include <sys/timeb.h>
  210.  
  211. #else  /* Not BSD44 */
  212.  
  213. #ifdef BSD4                             /* BSD 4.3 and below */
  214. #define TIMESTAMP                       /* Can do file dates */
  215. #include <time.h>                       /* Need this */
  216. #include <sys/timeb.h>                  /* Need this if really BSD */
  217.  
  218. #else  /* Not BSD 4.3 and below */
  219.  
  220. #ifdef SVORPOSIX                        /* System V or POSIX */
  221. #ifndef TIMESTAMP
  222. #define TIMESTAMP
  223. #endif /* TIMESTAMP */
  224. #include <time.h>
  225.  
  226. /* void tzset(); (the "void" type upsets some compilers) */
  227. #ifndef IRIX60
  228. #ifndef ultrix
  229. #ifndef CONVEX9
  230. /* ConvexOS 9.0, supposedly POSIX, has extern char *timezone(int,int) */
  231. #ifndef Plan9
  232. extern long timezone;
  233. #endif /* Plan9 */
  234. #endif /* CONVEX9 */
  235. #endif /* ultrix */
  236. #endif /* IRIX60 */
  237. #endif /* SVORPOSIX */
  238. #endif /* BSD4 */
  239. #endif /* BSD44 */
  240.  
  241. #ifdef COHERENT
  242. #include <time.h>
  243. #endif /* COHERENT */
  244.  
  245. /* Is `y' a leap year? */
  246. #define leap(y) (((y) % 4 == 0 && (y) % 100 != 0) || (y) % 400 == 0)
  247.  
  248. /* Number of leap years from 1970 to `y' (not including `y' itself). */
  249. #define nleap(y) (((y) - 1969) / 4 - ((y) - 1901) / 100 + ((y) - 1601) / 400)
  250.  
  251. #endif /* NOTIMESTAMP */
  252.  
  253. #ifdef CIE
  254. #include <stat.h>                       /* File status */
  255. #else
  256. #include <sys/stat.h>
  257. #endif /* CIE */
  258.  
  259.  
  260.  
  261. /* Macro to alleviate isdir() calls internal to this module */
  262.  
  263. static struct stat STATBUF;
  264. #define xisdir(a) ((stat(a,&STATBUF)==-1)?0:(S_ISDIR(STATBUF.st_mode)?1:0))
  265.  
  266. extern char uidbuf[];
  267. extern int xferlog;
  268. extern char * xferfile;
  269. int iklogopen = 0;
  270. static time_t timenow;
  271.  
  272. #define IKSDMSGLEN CKMAXPATH+512
  273.  
  274. static char iksdmsg[IKSDMSGLEN];
  275.  
  276. extern int local;
  277.  
  278. extern int server, en_mkd, en_cwd, en_del;
  279.  
  280. /*
  281.   Functions (n is one of the predefined file numbers from ckcker.h):
  282.  
  283.    zopeni(n,name)   -- Opens an existing file for input.
  284.    zopeno(n,name,attr,fcb) -- Opens a new file for output.
  285.    zclose(n)        -- Closes a file.
  286.    zchin(n,&c)      -- Gets the next character from an input file.
  287.    zsinl(n,&s,x)    -- Read a line from file n, max len x, into address s.
  288.    zsout(n,s)       -- Write a null-terminated string to output file, buffered.
  289.    zsoutl(n,s)      -- Like zsout, but appends a line terminator.
  290.    zsoutx(n,s,x)    -- Write x characters to output file, unbuffered.
  291.    zchout(n,c)      -- Add a character to an output file, unbuffered.
  292.    zchki(name)      -- Check if named file exists and is readable, return size.
  293.    zchko(name)      -- Check if named file can be created.
  294.    zchkspa(name,n)  -- Check if n bytes available to create new file, name.
  295.    znewn(name,s)    -- Make a new unique file name based on the given name.
  296.    zdelet(name)     -- Delete the named file.
  297.    zxpand(string)   -- Expands the given wildcard string into a list of files.
  298.    znext(string)    -- Returns the next file from the list in "string".
  299.    zxrewind()       -- Rewind zxpand list.
  300.    zxcmd(n,cmd)     -- Execute the command in a lower fork on file number n.
  301.    zclosf()         -- Close input file associated with zxcmd()'s lower fork.
  302.    zrtol(n1,n2)     -- Convert remote filename into local form.
  303.    zltor(n1,n2)     -- Convert local filename into remote form.
  304.    zchdir(dirnam)   -- Change working directory.
  305.    zhome()          -- Return pointer to home directory name string.
  306.    zkself()         -- Kill self, log out own job.
  307.    zsattr(struct zattr *) -- Return attributes for file which is being sent.
  308.    zstime(f, struct zattr *, x) - Set file creation date from attribute packet.
  309.    zrename(old, new) -- Rename a file.
  310.    zcopy(source,destination) -- Copy a file.
  311.    zmkdir(path)       -- Create the directory path if possible
  312.    zfnqfp(fname,len,fullpath) - Determine full path for file name.
  313.    zgetfs(name)     -- return file size regardless of accessibility
  314.    zchkpid(pid)     -- tell if PID is valid and active
  315. */
  316.  
  317. /* Kermit-specific includes */
  318. /*
  319.   Definitions here supersede those from system include files.
  320.   ckcdeb.h is included above.
  321. */
  322. #include "ckcker.h"                     /* Kermit definitions */
  323. #include "ckucmd.h"                     /* For keyword tables */
  324. #include "ckuver.h"                     /* Version herald */
  325.  
  326. char *ckzsys = HERALD;
  327.  
  328. /*
  329.   File access checking ...  There are two calls to access() in this module.
  330.   If this program is installed setuid or setgid on a Berkeley-based UNIX
  331.   system that does NOT incorporate the saved-original-effective-uid/gid
  332.   feature, then, when we have swapped the effective and original uid/gid,
  333.   access() fails because it uses what it thinks are the REAL ids, but we have
  334.   swapped them.  This occurs on systems where ANYBSD is defined, NOSETREU
  335.   is NOT defined, and SAVEDUID is NOT defined.  So, in theory, we should take
  336.   care of this situation like so:
  337.  
  338.     ifdef ANYBSD
  339.     ifndef NOSETREU
  340.     ifndef SAVEDUID
  341.     define SW_ACC_ID
  342.     endif
  343.     endif
  344.     endif
  345.  
  346.   But we can't test such a general scheme everywhere, so let's only do this
  347.   when we know we have to...
  348. */
  349. #ifdef NEXT                             /* NeXTSTEP 1.0-3.0 */
  350. #define SW_ACC_ID
  351. #endif /* NEXT */
  352.  
  353. /* Support for tilde-expansion in file and directory names */
  354.  
  355. #ifdef POSIX
  356. #define NAMEENV "LOGNAME"
  357. #else
  358. #ifdef BSD4
  359. #define NAMEENV "USER"
  360. #else
  361. #ifdef ATTSV
  362. #define NAMEENV "LOGNAME"
  363. #endif /* ATTSV */
  364. #endif /* BSD4 */
  365. #endif /* POSIX */
  366.  
  367. /* Berkeley Unix Version 4.x */
  368. /* 4.1bsd support from Charles E Brooks, EDN-VAX */
  369.  
  370. #ifdef BSD4
  371. #ifdef MAXNAMLEN
  372. #define BSD42
  373. #endif /* MAXNAMLEN */
  374. #endif /* BSD4 */
  375.  
  376. /* Definitions of some system commands */
  377.  
  378. char *DELCMD = "rm -f ";                /* For file deletion */
  379. char *CPYCMD = "cp ";                   /* For file copy */
  380. char *RENCMD = "mv ";                   /* For file rename */
  381. char *PWDCMD = "pwd ";                  /* For saying where I am */
  382.  
  383. #ifdef COMMENT
  384. #ifdef HPUX10
  385. char *DIRCMD = "/usr/bin/ls -l ";       /* For directory listing */
  386. char *DIRCM2 = "/usr/bin/ls -l ";       /* For directory listing, no args */
  387. #else
  388. char *DIRCMD = "/bin/ls -l ";           /* For directory listing */
  389. char *DIRCM2 = "/bin/ls -l ";           /* For directory listing, no args */
  390. #endif /* HPUX10 */
  391. #else
  392. char *DIRCMD = "ls -l ";                /* For directory listing */
  393. char *DIRCM2 = "ls -l ";                /* For directory listing, no args */
  394. #endif /* COMMENT */
  395.  
  396. char *TYPCMD = "cat ";                  /* For typing a file */
  397.  
  398. #ifdef HPUX
  399. char *MAILCMD = "mailx";                /* For sending mail */
  400. #else
  401. #ifdef DGUX540
  402. char *MAILCMD = "mailx";
  403. #else
  404. #ifdef UNIX
  405. #ifdef CK_MAILCMD
  406. char *MAILCMD = CK_MAILCMD;        /* CFLAGS override */
  407. #else
  408. char *MAILCMD = "Mail";            /* Default */
  409. #endif /* CK_MAILCMD */
  410. #else
  411. char *MAILCMD = "";
  412. #endif /* UNIX */
  413. #endif /* HPUX */
  414. #endif /* DGUX40 */
  415.  
  416. #ifdef UNIX
  417. #ifdef ANYBSD                           /* BSD uses lpr to spool */
  418. #ifdef DGUX540                          /* And DG/UX */
  419. char * PRINTCMD = "lp";
  420. #else
  421. char * PRINTCMD = "lpr";
  422. #endif /* DGUX540 */
  423. #else                                   /* Sys V uses lp */
  424. #ifdef TRS16                            /* except for Tandy-16/6000... */
  425. char * PRINTCMD = "lpr";
  426. #else
  427. char * PRINTCMD = "lp";
  428. #endif /* TRS16 */
  429. #endif /* ANYBSD */
  430. #else  /* Not UNIX */
  431. #define PRINTCMD ""
  432. #endif /* UNIX */
  433.  
  434. #ifdef FT18                             /* Fortune For:Pro 1.8 */
  435. #undef BSD4
  436. #endif /* FT18 */
  437.  
  438. #ifdef BSD4
  439. char *SPACMD = "pwd ; df .";            /* Space in current directory */
  440. #else
  441. #ifdef FT18
  442. char *SPACMD = "pwd ; du ; df .";
  443. #else
  444. char *SPACMD = "df ";
  445. #endif /* FT18 */
  446. #endif /* BSD4 */
  447.  
  448. char *SPACM2 = "df ";                   /* For space in specified directory */
  449.  
  450. #ifdef FT18
  451. #define BSD4
  452. #endif /* FT18 */
  453.  
  454. #ifdef BSD4
  455. char *WHOCMD = "finger ";
  456. #else
  457. char *WHOCMD = "who ";
  458. #endif /* BSD4 */
  459.  
  460. /* More system-dependent includes, which depend on symbols defined */
  461. /* in the Kermit-specific includes.  Oh what a tangled web we weave... */
  462.  
  463. #ifdef COHERENT                         /* <sys/file.h> */
  464. #define NOFILEH
  465. #endif /* COHERENT */
  466.  
  467. #ifdef MINIX
  468. #define NOFILEH
  469. #endif /* MINIX */
  470.  
  471. #ifdef aegis
  472. #define NOFILEH
  473. #endif /* aegis */
  474.  
  475. #ifdef unos
  476. #define NOFILEH
  477. #endif /* unos */
  478.  
  479. #ifndef NOFILEH
  480. #include <sys/file.h>
  481. #endif /* NOFILEH */
  482.  
  483. #ifndef is68k                           /* Whether to include <fcntl.h> */
  484. #ifndef BSD41                           /* All but a couple UNIXes have it. */
  485. #ifndef FT18
  486. #ifndef COHERENT
  487. #include <fcntl.h>
  488. #endif /* COHERENT */
  489. #endif /* FT18  */
  490. #endif /* BSD41 */
  491. #endif /* is68k */
  492.  
  493. #ifdef COHERENT
  494. #ifdef _I386
  495. #include <fcntl.h>
  496. #else
  497. #include <sys/fcntl.h>
  498. #endif /* _I386 */
  499. #endif /* COHERENT */
  500.  
  501. extern int inserver;            /* I am IKSD */
  502. int guest = 0;                          /* Anonymous user */
  503.  
  504. #ifdef IKSD
  505. extern int isguest;
  506. extern char * anonroot;
  507. #endif /* IKSD */
  508.  
  509. #ifdef CK_LOGIN
  510. #define GUESTPASS 256
  511. static char guestpass[GUESTPASS] = { NUL, NUL }; /* Anonymous "password" */
  512. static int logged_in = 0;               /* Set when user is logged in */
  513. static int askpasswd = 0;               /* Have OK user, must ask for passwd */
  514. #ifdef CK_PAM
  515. extern int gotemptypasswd;
  516. #endif /* CK_PAM */
  517. #endif /* CK_LOGIN */
  518.  
  519. #ifdef CKROOT
  520. static char ckroot[CKMAXPATH+1] = { NUL, NUL };
  521. static int ckrootset = 0;
  522. int ckrooterr = 0;
  523. #endif /* CKROOT */
  524.  
  525. _PROTOTYP( VOID ignorsigs, (void) );
  526. _PROTOTYP( VOID restorsigs, (void) );
  527. #ifdef SELECT
  528. _PROTOTYP( int ttwait, (int, int) );    /* ckutio.c */
  529. #endif    /* SELECT */
  530.  
  531. /*
  532.   Change argument to "(const char *)" if this causes trouble.
  533.   Or... if it causes trouble, then maybe it was already declared
  534.   in a header file after all, so you can remove this prototype.
  535. */
  536. #ifndef NDGPWNAM /* If not defined No Declare getpwnam... */
  537. #ifndef _POSIX_SOURCE
  538. #ifndef NEXT
  539. #ifndef SVR4
  540. /* POSIX <pwd.h> already gave prototypes for these. */
  541. #ifdef IRIX40
  542. _PROTOTYP( struct passwd * getpwnam, (const char *) );
  543. #else
  544. #ifdef IRIX51
  545. _PROTOTYP( struct passwd * getpwnam, (const char *) );
  546. #else
  547. #ifdef M_UNIX
  548. _PROTOTYP( struct passwd * getpwnam, (const char *) );
  549. #else
  550. #ifdef HPUX9
  551. _PROTOTYP( struct passwd * getpwnam, (const char *) );
  552. #else
  553. #ifdef HPUX10
  554. _PROTOTYP( struct passwd * getpwnam, (const char *) );
  555. #else
  556. #ifdef DCGPWNAM
  557. _PROTOTYP( struct passwd * getpwnam, (const char *) );
  558. #else
  559. _PROTOTYP( struct passwd * getpwnam, (char *) );
  560. #endif /* DCGPWNAM */
  561. #endif /* HPUX10 */
  562. #endif /* HPUX9 */
  563. #endif /* M_UNIX */
  564. #endif /* IRIX51 */
  565. #endif /* IRIX40 */
  566. #ifndef SUNOS4
  567. #ifndef HPUX9
  568. #ifndef HPUX10
  569. #ifndef _SCO_DS
  570. _PROTOTYP( struct passwd * getpwuid, (PWID_T) );
  571. #endif /* _SCO_DS */
  572. #endif /* HPUX10 */
  573. #endif /* HPUX9 */
  574. #endif /* SUNOS4 */
  575. _PROTOTYP( struct passwd * getpwent, (void) );
  576. #endif /* SVR4 */
  577. #endif /* NEXT */
  578. #endif /* _POSIX_SOURCE */
  579. #endif /* NDGPWNAM */
  580.  
  581. #ifdef CK_SHADOW                        /* Shadow Passwords... */
  582. #include <shadow.h>
  583. #endif /* CK_SHADOW */
  584. #ifdef CK_PAM                           /* PAM... */
  585. #ifdef MACOSX
  586. #include <pam/pam_appl.h>
  587. #else /* MACOSX */
  588. #include <security/pam_appl.h>
  589. #endif /* MACOSX */
  590. #ifndef PAM_SERVICE_TYPE                /* Defines which PAM service we are */
  591. #define PAM_SERVICE_TYPE "kermit"
  592. #endif /* PAM_SERVICE_TYPE */
  593.  
  594. #ifdef SOLARIS
  595. #define PAM_CONST 
  596. #else /* SOLARIS */
  597. #define PAM_CONST CONST
  598. #endif 
  599.  
  600. static char * pam_pw = NULL;
  601.  
  602. int
  603. #ifdef CK_ANSIC
  604. pam_cb(int num_msg,
  605.        PAM_CONST struct pam_message **msg,
  606.        struct pam_response **resp,
  607.        void *appdata_ptr
  608.        )
  609. #else /* CK_ANSIC */
  610. pam_cb(num_msg, msg, resp, appdata_ptr)
  611.     int num_msg;
  612.     PAM_CONST struct pam_message **msg;
  613.     struct pam_response **resp;
  614.     void *appdata_ptr;
  615. #endif /* CK_ANSIC */
  616. {
  617.     int i;
  618.  
  619.     debug(F111,"pam_cb","num_msg",num_msg);
  620.  
  621.     for (i = 0; i < num_msg; i++) {
  622.         char message[PAM_MAX_MSG_SIZE];
  623.  
  624.         /* Issue prompt and get response */
  625.         debug(F111,"pam_cb","Message",i);
  626.         debug(F111,"pam_cb",msg[i]->msg,msg[i]->msg_style);
  627.         if (msg[i]->msg_style == PAM_ERROR_MSG) {
  628.             debug(F111,"pam_cb","PAM ERROR",0);
  629.             fprintf(stdout,"%s\n", msg[i]->msg);
  630.             return(0);
  631.         } else if (msg[i]->msg_style == PAM_TEXT_INFO) {
  632.             debug(F111,"pam_cb","PAM TEXT INFO",0);
  633.             fprintf(stdout,"%s\n", msg[i]->msg);
  634.             return(0);
  635.         } else if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF) {
  636.             debug(F111,"pam_cb","Reading response, no echo",0);
  637.             /* Ugly hack.  We check to see if a password has been pushed */
  638.             /* into zvpasswd().  This would be true if the password was  */
  639.             /* received by REMOTE LOGIN.                                 */
  640.             if (pam_pw) {
  641.                 ckstrncpy(message,pam_pw,PAM_MAX_MSG_SIZE);
  642.             } else
  643.                 readpass((char *)msg[i]->msg,message,PAM_MAX_MSG_SIZE);
  644.         } else if (msg[i]->msg_style == PAM_PROMPT_ECHO_ON) {
  645.             debug(F111,"pam_cb","Reading response, with echo",0);
  646.             readtext((char *)msg[i]->msg,message,PAM_MAX_MSG_SIZE);
  647.         } else {
  648.             debug(F111,"pam_cb","unknown style",0);
  649.             return(0);
  650.         }
  651.  
  652.         /* Allocate space for this message's response structure */
  653.         resp[i] = (struct pam_response *) malloc(sizeof (struct pam_response));
  654.         if (!resp[i]) {
  655.             int j;
  656.             debug(F110,"pam_cb","malloc failure",0);
  657.             for (j = 0; j < i; j++) {
  658.                 free(resp[j]->resp);
  659.                 free(resp[j]);
  660.             }
  661.             return(0);
  662.         }
  663.  
  664.         /* Allocate a buffer for the response */
  665.         resp[i]->resp = (char *) malloc((int)strlen(message) + 1);
  666.         if (!resp[i]->resp) {
  667.             int j;
  668.             debug(F110,"pam_cb","malloc failure",0);
  669.             for (j = 0; j < i; j++) {
  670.                 free(resp[j]->resp);
  671.                 free(resp[j]);
  672.             }
  673.             free(resp[i]);
  674.             return(0);
  675.         }
  676.         /* Return the results back to PAM */
  677.         strcpy(resp[i]->resp, message);    /* safe (prechecked) */
  678.         resp[i]->resp_retcode = 0;
  679.     }
  680.     debug(F110,"pam_cb","Exiting",0);
  681.     return(0);
  682. }
  683. #endif /* CK_PAM */
  684.  
  685. /* Define macros for getting file type */
  686.  
  687. #ifdef OXOS
  688. /*
  689.   Olivetti X/OS 2.3 has S_ISREG and S_ISDIR defined
  690.   incorrectly, so we force their redefinition.
  691. */
  692. #undef S_ISREG
  693. #undef S_ISDIR
  694. #endif /* OXOS */
  695.  
  696. #ifdef UTSV                             /* Same deal for Amdahl UTSV */
  697. #undef S_ISREG
  698. #undef S_ISDIR
  699. #endif /* UTSV */
  700.  
  701. #ifdef UNISYS52                         /* And for UNISYS UTS V 5.2 */
  702. #undef S_ISREG
  703. #undef S_ISDIR
  704. #endif /* UNISYS52 */
  705.  
  706. #ifdef ICLSVR3                          /* And for old ICL versions */
  707. #undef S_ISREG
  708. #undef S_ISDIR
  709. #endif /* ICLSVR3 */
  710.  
  711. #ifdef ISDIRBUG                         /* Also allow this from command line */
  712. #ifdef S_ISREG
  713. #undef S_ISREG
  714. #endif /* S_ISREG */
  715. #ifdef S_ISDIR
  716. #undef S_ISDIR
  717. #endif /*  S_ISDIR */
  718. #endif /* ISDIRBUG */
  719.  
  720. #ifndef _IFMT
  721. #ifdef S_IFMT
  722. #define _IFMT S_IFMT
  723. #else
  724. #define _IFMT 0170000
  725. #endif /* S_IFMT */
  726. #endif /* _IFMT */
  727.  
  728. #ifndef S_ISREG
  729. #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
  730. #endif /* S_ISREG */
  731. #ifndef S_ISDIR
  732. #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
  733. #endif /* S_ISDIR */
  734.  
  735. /* The following mainly for NeXTSTEP... */
  736.  
  737. #ifndef S_IWUSR
  738. #define S_IWUSR 0000200
  739. #endif /* S_IWUSR */
  740.  
  741. #ifndef S_IRGRP
  742. #define S_IRGRP 0000040
  743. #endif /* S_IRGRP */
  744.  
  745. #ifndef S_IWGRP
  746. #define S_IWGRP 0000020
  747. #endif /* S_IWGRP */
  748.  
  749. #ifndef S_IXGRP
  750. #define S_IXGRP 0000010
  751. #endif /* S_IXGRP */
  752.  
  753. #ifndef S_IROTH
  754. #define S_IROTH 0000004
  755. #endif /* S_IROTH */
  756.  
  757. #ifndef S_IWOTH
  758. #define S_IWOTH 0000002
  759. #endif /* S_IWOTH */
  760.  
  761. #ifndef S_IXOTH
  762. #define S_IXOTH 0000001
  763. #endif /* S_IXOTH */
  764. /*
  765.   Define maximum length for a file name if not already defined.
  766.   NOTE: This applies to a path segment (directory or file name),
  767.   not the entire path string, which can be CKMAXPATH bytes long.
  768. */
  769. #ifdef QNX
  770. #ifdef _MAX_FNAME
  771. #define MAXNAMLEN _MAX_FNAME
  772. #else
  773. #define MAXNAMLEN 48
  774. #endif /* _MAX_FNAME */
  775. #else
  776. #ifndef MAXNAMLEN
  777. #ifdef sun
  778. #define MAXNAMLEN 255
  779. #else
  780. #ifdef FILENAME_MAX
  781. #define MAXNAMLEN FILENAME_MAX
  782. #else
  783. #ifdef NAME_MAX
  784. #define MAXNAMLEN NAME_MAX
  785. #else
  786. #ifdef _POSIX_NAME_MAX
  787. #define MAXNAMLEN _POSIX_NAME_MAX
  788. #else
  789. #ifdef _D_NAME_MAX
  790. #define MAXNAMLEN _D_NAME_MAX
  791. #else
  792. #ifdef DIRSIZ
  793. #define MAXNAMLEN DIRSIZ
  794. #else
  795. #define MAXNAMLEN 14
  796. #endif /* DIRSIZ */
  797. #endif /* _D_NAME_MAX */
  798. #endif /* _POSIX_NAME_MAX */
  799. #endif /* NAME_MAX */
  800. #endif /* FILENAME_MAX */
  801. #endif /* sun */
  802. #endif /* MAXNAMLEN */
  803. #endif /* QNX */
  804.  
  805. #ifdef COMMENT
  806. /* As of 2001-11-03 this is handled in ckcdeb.h */
  807. /* Longest pathname ... */
  808. /*
  809.   Beware: MAXPATHLEN is one of UNIX's dirty little secrets.  Where is it
  810.   defined?  Who knows...  <param.h>, <mod.h>, <unistd.h>, <limits.h>, ...
  811.   There is not necessarily even a definition for it anywhere, or it might have
  812.   another name.  If you get it wrong, bad things happen with getcwd() and/or
  813.   getwd().  If you allocate a buffer that is too short, getwd() might write
  814.   over memory and getcwd() will fail with ERANGE.  The definitions of these
  815.   functions (e.g. in SVID or POSIX.1) do not tell you how to determine the
  816.   maximum path length in order to allocate a buffer that is the right size.
  817. */
  818. #ifdef BSD44
  819. #include <sys/param.h>                  /* For MAXPATHLEN */
  820. #endif /* BSD44 */
  821. #ifdef COHERENT
  822. #include <sys/param.h>  /* for MAXPATHLEN, needed for -DDIRENT */
  823. #endif /* COHERENT */
  824. #endif /* COMMENT */
  825.  
  826. #ifdef MAXPATHLEN
  827. #ifdef MAXPATH
  828. #undef MAXPATH
  829. #endif /* MAXPATH */
  830. #define MAXPATH MAXPATHLEN
  831. #else
  832. #ifdef PATH_MAX
  833. #define MAXPATH PATH_MAX
  834. #else
  835. #ifdef _POSIX_PATH_MAX
  836. #define MAXPATH _POSIX_PATH_MAX
  837. #else
  838. #ifdef BSD42
  839. #define MAXPATH 1024
  840. #else
  841. #ifdef SVR4
  842. #define MAXPATH 1024
  843. #else
  844. #define MAXPATH 255
  845. #endif /* SVR4 */
  846. #endif /* BSD42 */
  847. #endif /* _POSIX_PATH_MAX */
  848. #endif /* PATH_MAX */
  849. #endif /* MAXPATHLEN */
  850.  
  851. /* Maximum number of filenames for wildcard expansion */
  852.  
  853. #ifndef MAXWLD
  854. /* Already defined in ckcdeb.h so the following is superfluous. */
  855. /* Don't expect changing them to have any effect. */
  856. #ifdef CK_SMALL
  857. #define MAXWLD 50
  858. #else
  859. #ifdef BIGBUFOK
  860. #define MAXWLD 102400
  861. #else
  862. #define MAXWLD 8192
  863. #endif /* BIGBUFOK */
  864. #endif /* CK_SMALL */
  865. #endif /* MAXWLD */
  866.  
  867. static int maxnames = MAXWLD;
  868.  
  869. /* Define the size of the string space for filename expansion. */
  870.  
  871. #ifndef DYNAMIC
  872. #ifdef PROVX1
  873. #define SSPACE 500
  874. #else
  875. #ifdef BSD29
  876. #define SSPACE 500
  877. #else
  878. #ifdef pdp11
  879. #define SSPACE 500
  880. #else
  881. #ifdef aegis
  882. #define SSPACE 10000                    /* Size of string-generating buffer */
  883. #else                                   /* Default static buffer size */
  884. #ifdef BIGBUFOK
  885. #define SSPACE 65000                    /* Size of string-generating buffer */
  886. #else
  887. #define SSPACE 2000                     /* size of string-generating buffer */
  888. #endif /* BIGBUFOK */
  889. #endif /* aegis */
  890. #endif /* pdp11 */
  891. #endif /* BSD29 */
  892. #endif /* PROVX1 */
  893. static char sspace[SSPACE];             /* Buffer for generating filenames */
  894. #else /* is DYNAMIC */
  895. #ifdef CK_64BIT
  896. #define SSPACE 2000000000        /* Two billion bytes */
  897. #else
  898. #ifdef BIGBUFOK
  899. #define SSPACE 10000000            /* Ten million */
  900. #else
  901. #define SSPACE 10000            /* Ten thousand */
  902. #endif /* BIGBUFOK */
  903. #endif    /* CK_64BIT */
  904. char *sspace = (char *)0;
  905. #endif /* DYNAMIC */
  906. static int ssplen = SSPACE;        /* Length of string space buffer */
  907.  
  908. #ifdef DCLFDOPEN
  909. /* fdopen() needs declaring because it's not declared in <stdio.h> */
  910. _PROTOTYP( FILE * fdopen, (int, char *) );
  911. #endif /* DCLFDOPEN */
  912.  
  913. #ifdef DCLPOPEN
  914. /* popen() needs declaring because it's not declared in <stdio.h> */
  915. _PROTOTYP( FILE * popen, (char *, char *) );
  916. #endif /* DCLPOPEN */
  917.  
  918. extern int nopush;
  919.  
  920. /* More internal function prototypes */
  921. /*
  922.  * The path structure is used to represent the name to match.
  923.  * Each slash-separated segment of the name is kept in one
  924.  * such structure, and they are linked together, to make
  925.  * traversing the name easier.
  926.  */
  927. struct path {
  928.     char npart[MAXNAMLEN+4];            /* name part of path segment */
  929.     struct path *fwd;                   /* forward ptr */
  930. };
  931. #ifndef NOPUSH
  932. _PROTOTYP( int shxpand, (char *, char *[], int ) );
  933. #endif /* NOPUSH */
  934. _PROTOTYP( static int fgen, (char *, char *[], int ) );
  935. _PROTOTYP( static VOID traverse, (struct path *, char *, char *) );
  936. _PROTOTYP( static VOID addresult, (char *, int) );
  937. #ifdef COMMENT
  938. /* Replaced by ckmatch() */
  939. _PROTOTYP( static int match, (char *, char *) );
  940. #endif /* COMMENT */
  941. _PROTOTYP( char * whoami, (void) );
  942. _PROTOTYP( UID_T real_uid, (void) );
  943. _PROTOTYP( static struct path *splitpath, (char *p) );
  944. _PROTOTYP( char * zdtstr, (time_t) );
  945. _PROTOTYP( time_t zstrdt, (char *, int) );
  946.  
  947. /* Some systems define these symbols in include files, others don't... */
  948.  
  949. #ifndef R_OK
  950. #define R_OK 4                          /* For access */
  951. #endif /* R_OK */
  952.  
  953. #ifndef W_OK
  954. #define W_OK 2
  955. #endif /* W_OK */
  956.  
  957. #ifndef X_OK
  958. #define X_OK 1
  959. #endif /* X_OK */
  960.  
  961. #ifndef O_RDONLY
  962. #define O_RDONLY 000
  963. #endif /* O_RDONLY */
  964.  
  965. /* syslog and wtmp items for Internet Kermit Service */
  966.  
  967. extern char * clienthost;               /* From ckcmai.c. */
  968.  
  969. static char fullname[CKMAXPATH+1];
  970. static char tmp2[CKMAXPATH+1];
  971.  
  972. extern int ckxlogging;
  973.  
  974. #ifdef CKXPRINTF                        /* Our printf macro conflicts with */
  975. #undef printf                           /* use of "printf" in syslog.h */
  976. #endif /* CKXPRINTF */
  977. #ifdef CKSYSLOG
  978. #ifdef RTAIX
  979. #include <sys/syslog.h>
  980. #else  /* RTAIX */
  981. #include <syslog.h>
  982. #endif /* RTAIX */
  983. #endif /* CKSYSLOG */
  984. #ifdef CKXPRINTF
  985. #define printf ckxprintf
  986. #endif /* CKXPRINTF */
  987.  
  988. int ckxanon = 1;                        /* Anonymous login ok */
  989. int ckxperms = 0040;                    /* Anonymous file permissions */
  990. int ckxpriv = 1;            /* Priv'd login ok */
  991.  
  992. #ifndef XFERFILE
  993. #define XFERFILE "/var/log/iksd.log"
  994. #endif /* XFERFILE */
  995.  
  996. /* wtmp logging for IKSD... */
  997.  
  998. #ifndef CKWTMP                          /* wtmp logging not selected */
  999. int ckxwtmp = 0;                        /* Know this at runtime */
  1000. #else                                   /* wtmp file details */
  1001. int ckxwtmp = 1;
  1002. #ifdef UTMPBUG                          /* Unfortunately... */
  1003. /*
  1004.   Some versions of Linux have a <utmp.h> file that contains
  1005.   "enum utlogin { local, telnet, rlogin, screen, ... };"  This clobbers
  1006.   any program that uses any of these words as variable names, function
  1007.   names, macro names, etc.  (Other versions of Linux have this declaration
  1008.   within #if 0 ... #endif.)  There is nothing we can do about this other
  1009.   than to not include the stupid file.  But we need stuff from it, so...
  1010. */
  1011. #include <features.h>
  1012. #include <sys/types.h>
  1013. #define UT_LINESIZE     32
  1014. #define UT_NAMESIZE     32
  1015. #define UT_HOSTSIZE     256
  1016.  
  1017. struct timeval {
  1018.   time_t tv_sec;
  1019.   time_t tv_usec;
  1020. };
  1021.  
  1022. struct exit_status {
  1023.   short int e_termination;      /* Process termination status.  */
  1024.   short int e_exit;             /* Process exit status.  */
  1025. };
  1026.  
  1027. struct utmp {
  1028.   short int ut_type;                    /* Type of login */
  1029.   pid_t ut_pid;                         /* Pid of login process */
  1030.   char ut_line[UT_LINESIZE];            /* NUL-terminated devicename of tty */
  1031.   char ut_id[4];                        /* Inittab id */
  1032.   char ut_user[UT_NAMESIZE];            /* Username (not NUL terminated) */
  1033.  
  1034.   char ut_host[UT_HOSTSIZE];            /* Hostname for remote login */
  1035.   struct exit_status ut_exit;           /* Exit status */
  1036.   long ut_session;                      /* Session ID, used for windowing */
  1037.   struct timeval ut_tv;                 /* Time entry was made */
  1038.   int32_t ut_addr_v6[4];                /* Internet address of remote host */
  1039.   char pad[20];                         /* Reserved */
  1040. };
  1041.  
  1042. #define ut_time ut_tv.tv_sec    /* Why should Linux be like anything else? */
  1043. #define ut_name ut_user         /* ... */
  1044.  
  1045. extern void
  1046. logwtmp __P ((__const char *__ut_line, __const char *__ut_name,
  1047.                           __const char *__ut_host));
  1048.  
  1049. #else  /* Not UTMPBUG */
  1050.  
  1051. #ifndef HAVEUTMPX                       /* Who has <utmpx.h> */
  1052. #ifdef SOLARIS
  1053. #define HAVEUTMPX
  1054. #else
  1055. #ifdef IRIX60
  1056. #define HAVEUTMPX
  1057. #else
  1058. #ifdef CK_SCOV5
  1059. #define HAVEUTMPX
  1060. #else
  1061. #ifdef HPUX100
  1062. #define HAVEUTMPX
  1063. #else
  1064. #ifdef UNIXWARE
  1065. #define HAVEUTMPX
  1066. #endif /* UNIXWARE */
  1067. #endif /* HPUX100 */
  1068. #endif /* CK_SCOV5 */
  1069. #endif /* IRIX60 */
  1070. #endif /* SOLARIS */
  1071. #endif /* HAVEUTMPX */
  1072. #ifdef HAVEUTMPX
  1073. #include <utmpx.h>
  1074. #else
  1075. #ifdef OSF50
  1076. /* Because the time_t in the utmp struct is 64 bits but time() wants 32 */
  1077. #define __V40_OBJ_COMPAT 1
  1078. #endif /* OSF50 */
  1079. #include <utmp.h>
  1080. #ifdef OSF50
  1081. #undef __V40_OBJ_COMPAT
  1082. #endif /* OSF50 */
  1083. #endif /* HAVEUTMPX */
  1084. #endif /* UTMPBUG */
  1085.  
  1086. #ifdef HAVEUTMPX
  1087. #define UTMPSTRUCT utmpx
  1088. #else
  1089. #define UTMPSTRUCT utmp
  1090. #endif    /* HAVEUTMPX */
  1091.  
  1092. #ifndef WTMPFILE
  1093. #ifdef QNX
  1094. #define WTMPFILE "/usr/adm/wtmp.1"
  1095. #else
  1096. #ifdef LINUX
  1097. #define WTMPFILE "/var/log/wtmp"
  1098. #else
  1099. #define WTMPFILE "/usr/adm/wtmp"
  1100. #endif /* QNX */
  1101. #endif /* LINUX */
  1102. #endif /* WTMPFILE */
  1103. char * wtmpfile = NULL;
  1104.  
  1105. static int wtmpfd = 0;
  1106. static char cksysline[32] = { NUL, NUL };
  1107.  
  1108. #ifndef HAVEUTHOST                      /* Does utmp include ut_host[]? */
  1109. #ifdef HAVEUTMPX                        /* utmpx always does */
  1110. #define HAVEUTHOST
  1111. #else
  1112. #ifdef LINUX                            /* Linux does */
  1113. #define HAVEUTHOST
  1114. #else
  1115. #ifdef SUNOS4                           /* SunOS does */
  1116. #define HAVEUTHOST
  1117. #else
  1118. #ifdef AIX41                            /* AIX 4.1 and later do */
  1119. #define HAVEUTHOST
  1120. #endif /* AIX41 */
  1121. #endif /* SUNOS4 */
  1122. #endif /* LINUX */
  1123. #endif /* HAVEUTMPX */
  1124. #endif /* HAVEUTHOST */
  1125.  
  1126. #ifdef UW200
  1127. PID_T _vfork() {                        /* To satisfy a library foulup */
  1128.     return(fork());                     /* in Unixware 2.0.x */
  1129. }
  1130. #endif /* UW200 */
  1131.  
  1132. VOID
  1133. #ifdef CK_ANSIC
  1134. logwtmp(const char * line, const char * name, const char * host)
  1135. #else
  1136. logwtmp(line, name, host) char *line, *name, *host;
  1137. #endif /* CK_ANSIC */
  1138. /* logwtmp */ {
  1139.     struct UTMPSTRUCT ut;
  1140.     struct stat buf;
  1141.     /* time_t time(); */
  1142.  
  1143.     if (!ckxwtmp)
  1144.       return;
  1145.  
  1146.     if (!wtmpfile)
  1147.       makestr(&wtmpfile,WTMPFILE);
  1148.  
  1149.     if (!line) line = "";
  1150.     if (!name) name = "";
  1151.     if (!host) host = "";
  1152.  
  1153.     if (!wtmpfd && (wtmpfd = open(wtmpfile, O_WRONLY|O_APPEND, 0)) < 0) {
  1154.         ckxwtmp = 0;
  1155.         debug(F110,"WTMP open failed",line,0);
  1156.         return;
  1157.     }
  1158.     if (!fstat(wtmpfd, &buf)) {
  1159.         ckstrncpy(ut.ut_line, line, sizeof(ut.ut_line));
  1160.         ckstrncpy(ut.ut_name, name, sizeof(ut.ut_name));
  1161. #ifdef HAVEUTHOST
  1162.         /* Not portable */
  1163.         ckstrncpy(ut.ut_host, host, sizeof(ut.ut_host));
  1164. #endif /* HAVEUTHOST */
  1165. #ifdef HAVEUTMPX
  1166.         time(&ut.ut_tv.tv_sec);
  1167. #else
  1168. #ifdef LINUX
  1169. /* In light of the following comment perhaps the previous line should */
  1170. /* be "#ifndef COMMENT". */
  1171.         {
  1172.             /*
  1173.              * On 64-bit platforms sizeof(time_t) and sizeof(ut.ut_time)
  1174.              * are not the same and attempt to use an address of
  1175.              * ut.ut_time as an argument to time() call may cause
  1176.              * "unaligned access" trap.
  1177.              */
  1178.             time_t zz;
  1179.             time(&zz);
  1180.             ut.ut_time = zz;
  1181.         }
  1182. #else
  1183. #ifdef CK_64BIT
  1184.         {
  1185.         /* Now (Jan 2006) we can do this for any 64-bit build */
  1186.             time_t zz;
  1187.             time(&zz);
  1188.             ut.ut_time = zz;
  1189.         }
  1190. #else
  1191.         time(&ut.ut_time);
  1192. #endif    /* CK_64BIT */
  1193. #endif /* LINUX */
  1194. #endif /* HAVEUTMPX */
  1195.         if (write(wtmpfd, (char *)&ut, sizeof(struct UTMPSTRUCT)) !=
  1196.             sizeof(struct UTMPSTRUCT)) {
  1197. #ifndef NOFTRUNCATE
  1198. #ifndef COHERENT
  1199.             ftruncate(wtmpfd, buf.st_size); /* Error, undo any partial write */
  1200. #else
  1201.             chsize(wtmpfd, buf.st_size); /* Error, undo any partial write */
  1202. #endif /* COHERENT */
  1203. #endif /* NOFTRUNCATE */
  1204.             debug(F110,"WTMP write error",line,0);
  1205.         } else {
  1206.             debug(F110,"WTMP record OK",line,0);
  1207.             return;
  1208.         }
  1209.     }
  1210. }
  1211. #endif /* CKWTMP */
  1212.  
  1213. #ifdef CKSYSLOG
  1214. /*
  1215.   C K S Y S L O G  --  C-Kermit system logging function,
  1216.  
  1217.   For use by other modules.
  1218.   This module can, but doesn't have to, use it.
  1219.   Call with:
  1220.     n = SYSLG_xx values defined in ckcdeb.h
  1221.     s1, s2, s3: strings.
  1222. */
  1223. VOID
  1224. cksyslog(n, m, s1, s2, s3) int n, m; char * s1, * s2, * s3; {
  1225.     int level;
  1226.  
  1227.     if (!ckxlogging)                    /* syslogging */
  1228.       return;
  1229.     if (!s1) s1 = "";                   /* Fix null args */
  1230.     if (!s2) s2 = "";
  1231.     if (!s3) s3 = "";
  1232.     switch (n) {                        /* Translate Kermit level */
  1233.       case SYSLG_DB:                    /* to syslog level */
  1234.         level = LOG_DEBUG;
  1235.         break;
  1236.       default:
  1237.         level = m ? LOG_INFO : LOG_ERR;
  1238.     }
  1239.     debug(F110,"cksyslog s1",s1,0);
  1240.     debug(F110,"cksyslog s2",s2,0);
  1241.     debug(F110,"cksyslog s3",s3,0);
  1242.     errno = 0;
  1243.     syslog(level, "%s: %s %s", s1, s2, s3); /* Write syslog record */
  1244.     debug(F101,"cksyslog errno","",errno);
  1245. }
  1246. #endif /* CKSYSLOG */
  1247.  
  1248.  
  1249. /* Declarations */
  1250.  
  1251. int maxnam = MAXNAMLEN;                 /* Available to the outside */
  1252. int maxpath = MAXPATH;
  1253. int ck_znewn = -1;
  1254.  
  1255. #ifdef UNIX
  1256. char startupdir[MAXPATH+1];
  1257. #endif /* UNIX */
  1258.  
  1259. int pexitstat = -2;                     /* Process exit status */
  1260.  
  1261. FILE *fp[ZNFILS] = {                    /* File pointers */
  1262.    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
  1263. };
  1264.  
  1265. /* Flags for each file indicating whether it was opened with popen() */
  1266. int ispipe[ZNFILS] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  1267.  
  1268. /* Buffers and pointers used in buffered file input and output. */
  1269. #ifdef DYNAMIC
  1270. extern char *zinbuffer, *zoutbuffer;
  1271. #else
  1272. extern char zinbuffer[], zoutbuffer[];
  1273. #endif /* DYNAMIC */
  1274. extern char *zinptr, *zoutptr;
  1275. extern int zincnt, zoutcnt;
  1276. extern int wildxpand, wildena;        /* Wildcard handling */
  1277.  
  1278. static CK_OFF_T iflen = (CK_OFF_T)-1;    /* Input file length */
  1279.  
  1280. static PID_T pid = 0;                   /* pid of child fork */
  1281. static int fcount = 0;                  /* Number of files in wild group */
  1282. static int nxpand = 0;                  /* Copy of fcount */
  1283. static char nambuf[CKMAXPATH+4];        /* Buffer for a pathname */
  1284.  
  1285. #ifndef NOFRILLS
  1286. #define ZMBUFLEN 200
  1287. static char zmbuf[ZMBUFLEN];        /* For mail, remote print strings */
  1288. #endif /* NOFRILLS */
  1289.  
  1290. char **mtchs = NULL;                    /* Matches found for filename */
  1291. char **mtchptr = NULL;                  /* Pointer to current match */
  1292.  
  1293. /*  Z K S E L F  --  Kill Self: log out own job, if possible.  */
  1294.  
  1295. /* Note, should get current pid, but if your system doesn't have */
  1296. /* getppid(), then just kill(0,9)...  */
  1297.  
  1298. #ifndef SVR3
  1299. #ifndef POSIX
  1300. #ifndef OSFPC
  1301. /* Already declared in unistd.h for SVR3 and POSIX */
  1302. #ifdef CK_ANSIC
  1303. extern PID_T getppid(void);
  1304. #else
  1305. #ifndef PS2AIX10
  1306. #ifndef COHERENT
  1307. extern PID_T getppid();
  1308. #endif /* COHERENT */
  1309. #endif /* PS2AIX10 */
  1310. #endif /* CK_ANSIC */
  1311. #endif /* OSFPC */
  1312. #endif /* POSIX */
  1313. #endif /* SVR3 */
  1314.  
  1315. int
  1316. zkself() {                              /* For "bye", but no guarantee! */
  1317. #ifdef PROVX1
  1318.     return(kill(0,9));
  1319. #else
  1320. #ifdef V7
  1321.     return(kill(0,9));
  1322. #else
  1323. #ifdef TOWER1
  1324.     return(kill(0,9));
  1325. #else
  1326. #ifdef FT18
  1327.     return(kill(0,9));
  1328. #else
  1329. #ifdef aegis
  1330.     return(kill(0,9));
  1331. #else
  1332. #ifdef COHERENT
  1333.     return(kill((PID_T)getpid(),1));
  1334. #else
  1335. #ifdef PID_T
  1336.     exit(kill((PID_T)getppid(),1));
  1337.     return(0);
  1338. #else
  1339.     exit(kill(getppid(),1));
  1340.     return(0);
  1341. #endif
  1342. #endif
  1343. #endif
  1344. #endif
  1345. #endif
  1346. #endif
  1347. #endif
  1348. }
  1349.  
  1350. static VOID
  1351. getfullname(name) char * name; {
  1352.     char *p = (char *)fullname;
  1353.     int len = 0;
  1354.     fullname[0] = '\0';
  1355.     /* If necessary we could also chase down symlinks here... */
  1356. #ifdef COMMENT
  1357.     /* This works but is incompatible with wuftpd */
  1358.     if (isguest && anonroot) {
  1359.         ckstrncpy(fullname,anonroot,CKMAXPATH);
  1360.         len = strlen(fullname);
  1361.         if (len > 0)
  1362.           if (fullname[len-1] == '/')
  1363.             len--;
  1364.     }
  1365.     p += len;
  1366. #endif /* COMMENT */
  1367.     zfnqfp(name, CKMAXPATH - len, p);
  1368.     while (*p) {
  1369.         if (*p < '!') *p = '_';
  1370.         p++;
  1371.     }
  1372. }
  1373.  
  1374. /*  D O I K L O G  --  Open Kermit-specific ftp-like transfer log. */
  1375.  
  1376. VOID                                    /* Called in ckcmai.c */
  1377. doiklog() {
  1378.     if (iklogopen)                      /* Already open? */
  1379.       return;
  1380.     if (xferlog) {                      /* Open iksd log if requested */
  1381.         if (!xferfile)                  /* If no pathname given */
  1382.           makestr(&xferfile,XFERFILE);    /* use this default */
  1383.         if (*xferfile) {
  1384.             xferlog = open(xferfile, O_WRONLY | O_APPEND | O_CREAT, 0660);
  1385.             debug(F101,"doiklog open","",xferlog);
  1386.             if (xferlog < 0) {
  1387. #ifdef CKSYSLOG
  1388.                 syslog(LOG_ERR, "xferlog open failure %s: %m", xferfile);
  1389. #endif /* CKSYSLOG */
  1390.                 debug(F101,"doiklog open errno","",errno);
  1391.                 xferlog = 0;
  1392.             } else
  1393.               iklogopen = 1;
  1394.         } else
  1395.           xferlog = 0;
  1396. #ifdef CKSYSLOG
  1397.         if (xferlog && ckxlogging)
  1398.           syslog(LOG_INFO, "xferlog: %s open ok", xferfile);
  1399. #endif /* CKSYSLOG */
  1400.     }
  1401. }
  1402.  
  1403. /*  Z O P E N I  --  Open an existing file for input. */
  1404.  
  1405. /* Returns 1 on success, 0 on failure */
  1406.  
  1407. int
  1408. zopeni(n,name) int n; char *name; {
  1409.     int x;
  1410.  
  1411.     debug(F111,"zopeni",name,n);
  1412.     if ((x = chkfn(n)) != 0) {
  1413.     debug(F111,"zopeni chkfn",ckitoa(n),x);
  1414.     return(0);
  1415.     }
  1416.     zincnt = 0;                         /* Reset input buffer */
  1417.     if (n == ZSYSFN) {                  /* Input from a system function? */
  1418. #ifdef COMMENT
  1419. /*** Note, this function should not be called with ZSYSFN ***/
  1420. /*** Always call zxcmd() directly, and give it the real file number ***/
  1421. /*** you want to use.  ***/
  1422.         return(zxcmd(n,name));          /* Try to fork the command */
  1423. #else
  1424.         debug(F110,"zopeni called with ZSYSFN, failing!",name,0);
  1425.         *nambuf = '\0';                 /* No filename. */
  1426.         return(0);                      /* fail. */
  1427. #endif /* COMMENT */
  1428.     }
  1429.     if (n == ZSTDIO) {                  /* Standard input? */
  1430.         if (is_a_tty(0)) {
  1431.             fprintf(stderr,"Terminal input not allowed");
  1432.             debug(F110,"zopeni: attempts input from unredirected stdin","",0);
  1433.             return(0);
  1434.         }
  1435.         fp[ZIFILE] = stdin;
  1436.         ispipe[ZIFILE] = 0;
  1437.         return(1);
  1438.     }
  1439. #ifdef CKROOT
  1440.     debug(F111,"zopeni setroot",ckroot,ckrootset);
  1441.     if (ckrootset) if (!zinroot(name)) {
  1442.     debug(F110,"zopeni setroot violation",name,0);
  1443.     return(0);
  1444.     }
  1445. #endif /* CKROOT */
  1446.     fp[n] = fopen(name,"r");            /* Real file, open it. */
  1447.     /* debug(F111,"zopeni fopen", name, fp[n]); */
  1448. #ifdef ZDEBUG
  1449.     /* printf("ZOPENI fp[%d]=%ld\n",n,fp[n]); */
  1450. #endif /* ZDEBUG */
  1451.     ispipe[n] = 0;
  1452.  
  1453.     if (xferlog
  1454. #ifdef CKSYSLOG
  1455.         || ((ckxsyslog >= SYSLG_FA) && ckxlogging)
  1456. #endif /* CKSYSLOG */
  1457.         ) {
  1458.         getfullname(name);
  1459.         debug(F110,"zopeni fullname",fullname,0);
  1460.     }
  1461.     if (fp[n] == NULL) {
  1462. #ifdef CKSYSLOG
  1463.         if (ckxsyslog >= SYSLG_FA && ckxlogging) {
  1464.         syslog(LOG_INFO, "file[%d] %s: open failed (%m)", n, fullname);
  1465.         perror(fullname);
  1466.     } else
  1467. #endif /* CKSYSLOG */
  1468.       perror(name);
  1469.         return(0);
  1470.     } else {
  1471. #ifdef CKSYSLOG
  1472.         if (ckxsyslog >= SYSLG_FA && ckxlogging)
  1473.           syslog(LOG_INFO, "file[%d] %s: open read ok", n, fullname);
  1474. #endif /* CKSYSLOG */
  1475.         clearerr(fp[n]);
  1476.         return(1);
  1477.     }
  1478. }
  1479.  
  1480. #ifdef QNX
  1481. #define DONDELAY
  1482. #else
  1483. #ifdef O_NDELAY
  1484. #define DONDELAY
  1485. #endif /* O_NDELAY */
  1486. #endif /* QNX */
  1487.  
  1488. /*  Z O P E N O  --  Open a new file for output.  */
  1489.  
  1490. /*ARGSUSED*/    /* zz not used */
  1491. int
  1492. zopeno(n,name,zz,fcb)
  1493. /* zopeno */  int n; char *name; struct zattr *zz; struct filinfo *fcb; {
  1494.  
  1495.     char p[8];
  1496.     int append = 0;
  1497.     int istty = 0, filefd = 0;
  1498.  
  1499. /* As of Version 5A, the attribute structure and the file information */
  1500. /* structure are included in the arglist. */
  1501.  
  1502. #ifdef DEBUG
  1503.     debug(F111,"zopeno",name,n);
  1504.     if (fcb) {
  1505.         debug(F101,"zopeno fcb disp","",fcb->dsp);
  1506.         debug(F101,"zopeno fcb type","",fcb->typ);
  1507.         debug(F101,"zopeno fcb char","",fcb->cs);
  1508.     } else {
  1509.         debug(F100,"zopeno fcb is NULL","",0);
  1510.     }
  1511. #endif /* DEBUG */
  1512.  
  1513.     if (chkfn(n) != 0)                  /* Already open? */
  1514.       return(0);                        /* Nothing to do. */
  1515.  
  1516.     if ((n == ZCTERM) || (n == ZSTDIO)) { /* Terminal or standard output */
  1517.         fp[ZOFILE] = stdout;
  1518.         ispipe[ZOFILE] = 0;
  1519. #ifdef COMMENT
  1520.     /* This seems right but it breaks client server ops */
  1521.     fp[n] = stdout;
  1522.         ispipe[n] = 0;
  1523. #endif /* COMMENT */
  1524. #ifdef COMMENT
  1525. #ifdef DEBUG
  1526.         if (n != ZDFILE)
  1527.           debug(F101,"zopeno fp[n]=stdout","",fp[n]);
  1528. #endif /* DEBUG */
  1529. #endif    /* COMMENT */
  1530.         zoutcnt = 0;
  1531.         zoutptr = zoutbuffer;
  1532.         return(1);
  1533.     }
  1534.  
  1535. /* A real file.  Open it in desired mode (create or append). */
  1536.  
  1537. #ifdef CKROOT
  1538.     debug(F111,"zopeno setroot",ckroot,ckrootset);
  1539.     if (ckrootset) if (!zinroot(name)) {
  1540.     debug(F110,"zopeno setroot violation",name,0);
  1541.     return(0);
  1542.     }
  1543. #endif /* CKROOT */
  1544.  
  1545.     ckstrncpy(p,"w",8);            /* Assume write/create mode */
  1546.     if (fcb) {                          /* If called with an FCB... */
  1547.         if (fcb->dsp == XYFZ_A) {       /* Does it say Append? */
  1548.             ckstrncpy(p,"a",8);        /* Yes. */
  1549.             debug(F100,"zopeno append","",0);
  1550.             append = 1;
  1551.         }
  1552.     }
  1553.     if (xferlog
  1554. #ifdef CKSYSLOG
  1555.         || ((ckxsyslog >= SYSLG_FC) && ckxlogging)
  1556. #endif /* CKSYSLOG */
  1557.         ) {
  1558.         getfullname(name);
  1559.         debug(F110,"zopeno fullname",fullname,0);
  1560.     }
  1561.     {
  1562.     /* Allow tty devices to opened as output files 2009/10/20 */
  1563.     int fd, mode = 0;
  1564.     debug(F110,"zopeno attempting to open",name,0);
  1565. #ifdef O_NONBLOCK
  1566.     mode = O_NONBLOCK;
  1567. #else
  1568. #ifdef O_NDELAY
  1569.     mode = O_NDELAY;
  1570. #else
  1571. #ifdef FNDELAY
  1572.     mode = FNDELAY;
  1573. #endif /* FNDELAY */
  1574. #endif    /* O_NDELAY */
  1575. #endif    /* O_NONBLOCK */
  1576.     debug(F111,"zopeno open mode",name,mode);
  1577.     fd = open(name,O_WRONLY,mode);
  1578.     debug(F111,"zopeno open",name,fd); 
  1579.     if (fd > -1) {
  1580.         if (isatty(fd)) {
  1581.         filefd = fd;
  1582.         istty++;
  1583.         }
  1584.     }
  1585.     }
  1586.     debug(F111,"zopeno istty",name,istty);
  1587.     debug(F110,"zopeno fopen arg",p,0);
  1588.     if (istty)
  1589.       fp[n] = fdopen(filefd,p);
  1590.     else
  1591.       fp[n] = fopen(name,p);        /* Try to open the file */
  1592.     ispipe[ZIFILE] = 0;
  1593.  
  1594. #ifdef ZDEBUG
  1595.     printf("ZOPENO fp[%d]=%ld\n",n,fp[n]);
  1596. #endif /* ZDEBUG */
  1597.  
  1598.     if (fp[n] == NULL) {                /* Failed */
  1599.         debug(F101,"zopeno failed errno","",errno);
  1600.     if (istty) close(filefd);
  1601. #ifdef CKSYSLOG
  1602.         if (ckxsyslog >= SYSLG_FC && ckxlogging)
  1603.           syslog(LOG_INFO, "file[%d] %s: %s failed (%m)",
  1604.                  n,
  1605.                  fullname,
  1606.                  append ? "append" : "create"
  1607.                  );
  1608. #endif /* CKSYSLOG */
  1609. #ifdef COMMENT                          /* Let upper levels print message. */
  1610.         perror("Can't open output file");
  1611. #endif /* COMMENT */
  1612.     } else {                            /* Succeeded */
  1613.         extern int zofbuffer, zofblock, zobufsize;
  1614.         debug(F101, "zopeno zobufsize", "", zobufsize);
  1615.         if (n == ZDFILE || n == ZTFILE) { /* If debug or transaction log */
  1616.             setbuf(fp[n],NULL);           /* make it unbuffered. */
  1617. #ifdef DONDELAY
  1618.         } else if (n == ZOFILE && !zofblock) { /* blocking or nonblocking */
  1619.             int flags;
  1620.             if ((flags = fcntl(fileno(fp[n]),F_GETFL,0)) > -1)
  1621.               fcntl(fileno(fp[n]),F_SETFL, flags |
  1622. #ifdef QNX
  1623.                     O_NONBLOCK
  1624. #else
  1625.                     O_NDELAY
  1626. #endif /* QNX */
  1627.                     );
  1628.             debug(F100,"zopeno ZOFILE nonblocking","",0);
  1629. #endif /* DONDELAY */
  1630.         } else if (n == ZOFILE && !zofbuffer) { /* buffered or unbuffered */
  1631.             setbuf(fp[n],NULL);
  1632.             debug(F100,"zopeno ZOFILE unbuffered","",0);
  1633.         }
  1634.  
  1635. #ifdef CK_LOGIN
  1636.         /* Enforce anonymous file-creation permission */
  1637.         if (isguest)
  1638.           if (n == ZWFILE || n == ZMFILE ||
  1639.               n == ZOFILE || n == ZDFILE ||
  1640.               n == ZTFILE || n == ZPFILE ||
  1641.               n == ZSFILE)
  1642.             chmod(name,ckxperms);
  1643. #endif /* CK_LOGIN */
  1644. #ifdef CKSYSLOG
  1645.         if (ckxsyslog >= SYSLG_FC && ckxlogging)
  1646.           syslog(LOG_INFO, "file[%d] %s: %s ok",
  1647.                  n,
  1648.                  fullname,
  1649.                  append ? "append" : "create"
  1650.                  );
  1651. #endif /* CKSYSLOG */
  1652.         debug(F100, "zopeno ok", "", 0);
  1653.     }
  1654.     zoutcnt = 0;                        /* (PWP) reset output buffer */
  1655.     zoutptr = zoutbuffer;
  1656.     return((fp[n] != NULL) ? 1 : 0);
  1657. }
  1658.  
  1659. /*  Z C L O S E  --  Close the given file.  */
  1660.  
  1661. /*  Returns 0 if arg out of range, 1 if successful, -1 if close failed.  */
  1662.  
  1663. int
  1664. zclose(n) int n; {
  1665.     int x = 0, x2 = 0;
  1666.     extern CK_OFF_T ffc;
  1667.  
  1668.     debug(F101,"zclose file number","",n);
  1669.     if (chkfn(n) < 1) return(0);        /* Check range of n */
  1670.     if ((n == ZOFILE) && (zoutcnt > 0)) /* (PWP) output leftovers */
  1671.       x2 = zoutdump();
  1672.  
  1673.     if (fp[ZSYSFN] || ispipe[n]) {      /* If file is really pipe */
  1674. #ifndef NOPUSH
  1675.         x = zclosf(n);                  /* do it specially */
  1676. #else
  1677.         x = EOF;
  1678. #endif /* NOPUSH */
  1679.         debug(F101,"zclose zclosf","",x);
  1680.         /* debug(F101,"zclose zclosf fp[n]","",fp[n]); */
  1681.     } else {
  1682.         if ((fp[n] != stdout) && (fp[n] != stdin))
  1683.           x = fclose(fp[n]);
  1684.         fp[n] = NULL;
  1685. #ifdef COMMENT
  1686.     if (n == ZCTERM || n == ZSTDIO)    /* See zopeno() */
  1687.       if (fp[ZOFILE] == stdout)
  1688.         fp[ZOFILE] = NULL;
  1689. #endif /* COMMENT */
  1690.     }
  1691.     iflen = -1L;                        /* Invalidate file length */
  1692.     if (x == EOF) {                     /* if we got a close error */
  1693.         debug(F101,"zclose fclose fails","",x);
  1694.         return(-1);
  1695.     } else if (x2 < 0) {                /* or error flushing last buffer */
  1696.         debug(F101,"zclose error flushing last buffer","",x2);
  1697.         return(-1);                     /* then return an error */
  1698.     } else {
  1699.         /* Print log record compatible with wu-ftpd */
  1700.         if (xferlog && (n == ZIFILE || n == ZOFILE)) {
  1701.             char * s, *p;
  1702.             extern char ttname[];
  1703.             if (!iklogopen) (VOID) doiklog(); /* Open log if necessary */
  1704.             debug(F101,"zclose iklogopen","",iklogopen);
  1705.             if (iklogopen) {
  1706.         int len;
  1707.         char * fnam;
  1708.  
  1709.                 timenow = time(NULL);
  1710. #ifdef CK_LOGIN
  1711.                 if (logged_in)
  1712.                   s = clienthost;
  1713.                 else
  1714. #endif /* CK_LOGIN */
  1715.                   s = (char *)ttname;
  1716.                 if (!s) s = "";
  1717.                 if (!*s) s = "*";
  1718. #ifdef CK_LOGIN
  1719.                 if (logged_in) {
  1720.                     p = guestpass;
  1721.                     if (!*p) p = "*";
  1722.                 } else
  1723. #endif /* CK_LOGIN */
  1724.                   p = whoami();
  1725.  
  1726.         len = 24 + 12 + (int)strlen(s) + 16
  1727.           + (int)strlen(fullname) + 1 + 1 + 1 + 1
  1728.             + (int)strlen(p) + 6 + 2 + 12;
  1729.         fnam = fullname;
  1730.         if (!*fnam) fnam = "(pipe)";
  1731.  
  1732.         if (len > IKSDMSGLEN)
  1733.           sprintf(iksdmsg,    /* SAFE */
  1734.                         "%.24s [BUFFER WOULD OVERFLOW]\n",ctime(&timenow));
  1735.         else
  1736.           sprintf(iksdmsg,    /* SAFE */
  1737.                         "%.24s %d %s %s %s %c %s %c %c %s %s %d %s\n",
  1738.                         ctime(&timenow),        /* date/time */
  1739.                         gtimer(),               /* elapsed secs */
  1740.                         s,                      /* peer name */
  1741.             ckfstoa(ffc),            /* byte count */
  1742.                         fnam,            /* full pathname of file */
  1743.                         (binary ? 'b' : 'a'),   /* binary or ascii */
  1744.                         "_",                    /* options = none */
  1745.                         n == ZIFILE ? 'o' : 'i', /* in/out */
  1746. #ifdef CK_LOGIN
  1747.                         (isguest ? 'a' : 'r'),  /* User type */
  1748. #else
  1749.                         'r',
  1750. #endif /* CK_LOGIN */
  1751.                         p,                      /* Username or guest passwd */
  1752. #ifdef CK_LOGIN
  1753.                         logged_in ? "iks" : "kermit", /* Record ID */
  1754. #else
  1755.                         "kermit",
  1756. #endif /* CK_LOGIN */
  1757.                         0,              /* User ID on client system unknown */
  1758.                         "*"             /* Ditto */
  1759.                         );
  1760.                 debug(F110,"zclose iksdmsg",iksdmsg,0);
  1761.                 write(xferlog, iksdmsg, (int)strlen(iksdmsg));
  1762.             }
  1763.         }
  1764.         debug(F101,"zclose returns","",1);
  1765.         return(1);
  1766.     }
  1767. }
  1768.  
  1769. /*  Z C H I N  --  Get a character from the input file.  */
  1770.  
  1771. /*  Returns -1 if EOF, 0 otherwise with character returned in argument  */
  1772.  
  1773. int
  1774. zchin(n,c) int n; int *c; {
  1775.     int a;
  1776.  
  1777. #ifdef IKSD
  1778.     if (inserver && !local && (n == ZCTERM || n == ZSTDIO)) {
  1779.         a = coninc(0);
  1780.         if (*c < 0)
  1781.           return(-1);
  1782.     } else
  1783. #endif /* IKSD */
  1784.     /* (PWP) Just in case this gets called when it shouldn't. */
  1785.     if (n == ZIFILE) {
  1786.         a = zminchar();            /* Note: this catches Ctrl-Z */
  1787.         if (a < 0)            /* (See zinfill()...) */
  1788.       return(-1);
  1789.     } else {
  1790.     a = getc(fp[n]);
  1791.     if (a == EOF) return(-1);
  1792. #ifdef CK_CTRLZ
  1793.     /* If SET FILE EOF CTRL-Z, first Ctrl-Z marks EOF */
  1794.     if (!binary && a == 0x1A && eofmethod == XYEOF_Z)
  1795.       return(-1);
  1796. #endif /* CK_CTRLZ */
  1797.     }
  1798.     *c = (CHAR) a & 0377;
  1799.     return(0);
  1800. }
  1801.  
  1802. /*  Z S I N L  --  Read a line from a file  */
  1803.  
  1804. /*
  1805.   Writes the line into the address provided by the caller.
  1806.   n is the Kermit "channel number".
  1807.   Writing terminates when newline is encountered, newline is not copied.
  1808.   Writing also terminates upon EOF or if length x is exhausted.
  1809.   Returns 0 on success, -1 on EOF or error.
  1810. */
  1811. int
  1812. zsinl(n,s,x) int n, x; char *s; {
  1813.     int a, z = 0;                       /* z is return code. */
  1814.     int count = 0;
  1815.     int len = 0;
  1816.     char *buf;
  1817.     extern CHAR feol;                   /* Line terminator */
  1818.  
  1819.     if (!s || chkfn(n) < 1)             /* Make sure file is open, etc */
  1820.       return(-1);
  1821.     buf = s;
  1822.     s[0] = '\0';                        /* Don't return junk */
  1823.  
  1824.     a = -1;                             /* Current character, none yet. */
  1825.     while (x--) {                       /* Up to given length */
  1826.         int old = 0;
  1827.         if (feol)                       /* Previous character */
  1828.           old = a;
  1829.         if (zchin(n,&a) < 0) {          /* Read a character from the file */
  1830.             debug(F101,"zsinl zchin fail","",count);
  1831.             if (count == 0)
  1832.               z = -1;                   /* EOF or other error */
  1833.             break;
  1834.         } else
  1835.           count++;
  1836.         if (feol) {                     /* Single-character line terminator */
  1837.             if (a == feol)
  1838.               break;
  1839.         } else {                        /* CRLF line terminator */
  1840.             if (a == '\015')            /* CR, get next character */
  1841.               continue;
  1842.             if (old == '\015') {        /* Previous character was CR */
  1843.                 if (a == '\012') {      /* This one is LF, so we have a line */
  1844.                     break;
  1845.                 } else {                /* Not LF, deposit CR */
  1846.                     *s++ = '\015';
  1847.                     x--;
  1848.                     len++;
  1849.                 }
  1850.             }
  1851.         }
  1852.         *s = a;                         /* Deposit character */
  1853.         s++;
  1854.         len++;
  1855.     }
  1856.     *s = '\0';                          /* Terminate the string */
  1857.     debug(F011,"zsinl",buf,len);
  1858.     return(z);
  1859. }
  1860.  
  1861. /*  Z X I N  --  Read x bytes from a file  */
  1862.  
  1863. /*
  1864.   Reads x bytes (or less) from channel n and writes them
  1865.   to the address provided by the caller.
  1866.   Returns number of bytes read on success, 0 on EOF or error.
  1867. */
  1868. int
  1869. zxin(n,s,x) int n, x; char *s; {
  1870. #ifdef IKSD
  1871.     if (inserver && !local && (n == ZCTERM || n == ZSTDIO)) {
  1872.         int a, i;
  1873.         a = ttchk();
  1874.         if (a < 1) return(0);
  1875.         for (i = 0; i < a && i < x; i++)
  1876.           s[i] = coninc(0);
  1877.         return(i);
  1878.     }
  1879. #endif /* IKSD */
  1880.  
  1881.     return(fread(s, sizeof (char), x, fp[n]));
  1882. }
  1883.  
  1884. /*
  1885.   Z I N F I L L  --  Buffered file input.
  1886.  
  1887.   (re)fill the file input buffer with data.  All file input
  1888.   should go through this routine, usually by calling the zminchar()
  1889.   macro defined in ckcker.h.  Returns:
  1890.  
  1891.   Value 0..255 on success, the character that was read.
  1892.   -1 on end of file.
  1893.   -2 on any kind of error other than end of file.
  1894.   -3 timeout when reading from pipe (Kermit packet mode only).
  1895. */
  1896. int
  1897. zinfill() {
  1898.     extern int kactive, srvping;
  1899.     errno = 0;
  1900.  
  1901. #ifdef ZDEBUG
  1902.     printf("ZINFILL fp[%d]=%ld\n",ZIFILE,fp[ZIFILE]);
  1903. #endif /* ZDEBUG */
  1904.  
  1905. #ifdef IKSD
  1906.     if (inserver && !local && fp[ZIFILE] == stdin) {
  1907.         int a, i;
  1908.         a = ttchk();
  1909.         if (a < 0) return(-2);
  1910.         for (i = 0; i < a && i < INBUFSIZE; i++) {
  1911.             zinbuffer[i] = coninc(0);
  1912.         }
  1913.         zincnt = i;
  1914.         /* set pointer to beginning, (== &zinbuffer[0]) */
  1915.         zinptr = zinbuffer;
  1916.         if (zincnt == 0) return(-1);
  1917.         zincnt--;                       /* One less char in buffer */
  1918.         return((int)(*zinptr++) & 0377); /* because we return the first */
  1919.     }
  1920. #endif /* IKSD */
  1921.  
  1922.     debug(F101,"zinfill kactive","",kactive);
  1923.  
  1924.     if (!(kactive && ispipe[ZIFILE])) {
  1925.         if (feof(fp[ZIFILE])) {
  1926.             debug(F100,"ZINFILL feof","",0);
  1927. #ifdef ZDEBUG
  1928.             printf("ZINFILL EOF\n");
  1929. #endif /* ZDEBUG */
  1930.             return(-1);
  1931.         }
  1932.     }
  1933.     clearerr(fp[ZIFILE]);
  1934.  
  1935. #ifdef SELECT
  1936.     /* Here we can call select() to get a timeout... */
  1937.     if (kactive && ispipe[ZIFILE]) {
  1938.         int secs, z = 0;
  1939. #ifndef NOXFER
  1940.         if (srvping) {
  1941.             secs = 1;
  1942.             debug(F101,"zinfill calling ttwait","",secs);
  1943.             z = ttwait(fileno(fp[ZIFILE]),secs);
  1944.             debug(F101,"zinfill ttwait","",z);
  1945.         }
  1946. #endif /* NOXFER */
  1947.         if (z == 0)
  1948.           return(-3);
  1949.     }
  1950. #endif /* SELECT */
  1951.  
  1952. #ifdef DEBUG
  1953.     if (deblog) {
  1954.         int i;
  1955.         debug(F101,"ZINFILL INBUFSIZE","",INBUFSIZE);
  1956. #ifdef USE_MEMCPY
  1957.         memset(zinbuffer, 0xFF, INBUFSIZE);
  1958. #else
  1959.         for (i = 0; i < INBUFSIZE; i++) {
  1960.             zinbuffer[i] = 0xFF;
  1961. #ifdef COMMENT                /* Too much! */
  1962.             debug(F101,"ZINFILL zinbuffer[i]","",i);
  1963. #endif /* COMMENT */
  1964.         }
  1965. #endif /* USE_MEMCPY */
  1966.     ckstrncpy(zinbuffer,"zinbuffer is a valid buffer",INBUFSIZE);
  1967.     /* debug(F111,"ZINFILL about to call fread",zinbuffer,zinbuffer); */
  1968.     }
  1969. #endif /* DEBUG */
  1970.  
  1971. /*
  1972.   Note: The following read MUST be nonblocking when reading from a pipe
  1973.   and we want timeouts to work.  See zxcmd().
  1974. */
  1975.     zincnt = fread(zinbuffer, sizeof (char), INBUFSIZE, fp[ZIFILE]);
  1976.     debug(F101,"ZINFILL fread","",zincnt); /* Just the size */
  1977. #ifdef ZDEBUG
  1978.     printf("FREAD=%d\n",zincnt);
  1979. #endif /* ZDEBUG */
  1980. #ifdef CK_CTRLZ
  1981.     /* If SET FILE EOF CTRL-Z, first Ctrl-Z marks EOF */
  1982.     if (zincnt > 0 && !binary && eofmethod == XYEOF_Z) {
  1983.     register int i;
  1984.     for (i = 0; i < zincnt; i++) {
  1985.         if (zinbuffer[i] == SUB) {
  1986.         zincnt = i;        /* Stop at first Ctrl-Z */
  1987.         if (i == 0)
  1988.           return(-1);
  1989.         break;
  1990.         }
  1991.         }
  1992.     }
  1993. #endif /* CK_CTRLZ */
  1994.  
  1995.     if (zincnt == 0) {                  /* Got nothing? */
  1996.         if (ferror(fp[ZIFILE])) {
  1997.             debug(F100,"ZINFILL ferror","",0);
  1998.             debug(F101,"ZINFILL errno","",errno);
  1999. #ifdef ZDEBUG
  2000.             printf("ZINFILL errno=%d\n",errno);
  2001. #endif /* ZDEBUG */
  2002. #ifdef EWOULDBLOCK
  2003.             return((errno == EWOULDBLOCK) ? -3 : -2);
  2004. #else
  2005.             return(-2);
  2006. #endif /* EWOULDBLOCK */
  2007.         }
  2008.  
  2009.     /* In case feof() didn't work just above -- sometimes it doesn't... */
  2010.  
  2011.         if (feof(fp[ZIFILE]) ) {
  2012.             debug(F100,"ZINFILL count 0 EOF return -1","",0);
  2013.             return (-1);
  2014.         } else {
  2015.             debug(F100,"ZINFILL count 0 not EOF return -2","",0);
  2016.             return(-2);
  2017.         }
  2018.     }
  2019.     zinptr = zinbuffer;    /* set pointer to beginning, (== &zinbuffer[0]) */
  2020.     zincnt--;                           /* One less char in buffer */
  2021.     return((int)(*zinptr++) & 0377);    /* because we return the first */
  2022. }
  2023.  
  2024. /*  Z S O U T  --  Write a string out to the given file, buffered.  */
  2025.  
  2026. /*  Returns 0 on success, -1 on failure */
  2027.  
  2028. int
  2029. zsout(n,s) int n; char *s; {
  2030.     int rc = 0;
  2031.     rc = chkfn(n);
  2032.     if (rc < 1) return(-1);             /* Keep this, prevents memory faults */
  2033.     if (!s) return(0);                  /* Null pointer, do nothing, succeed */
  2034.     if (!*s) return(0);                 /* empty string, ditto */
  2035.  
  2036. #ifdef IKSD
  2037.     /*
  2038.       This happens with client-side Kermit server when a REMOTE command
  2039.       was sent from the server to the client and the server is supposed to
  2040.       display the text, but of course there is no place to display it
  2041.       since it is in remote mode executing Kermit protocol.
  2042.     */
  2043.     if (inserver && !local && (n == ZCTERM || n == ZSTDIO)) {
  2044. #ifdef COMMENT
  2045.         return(ttol(s,((int)strlen(s)) < 0) ? -1 : 0);
  2046. #else
  2047.         return(0);
  2048. #endif /* COMMENT */
  2049.     }
  2050. #endif /* IKSD */
  2051.  
  2052.     if (n == ZSFILE) {
  2053.     int k;
  2054.     k = strlen(s);
  2055.     rc = write(fileno(fp[n]),s,k);
  2056.     return((rc == k) ? 0 : -1);
  2057.     }
  2058.     rc = fputs(s,fp[n]) == EOF ? -1 : 0;
  2059.     if (n == ZWFILE)
  2060.       fflush(fp[n]);
  2061.     return(rc);
  2062. }
  2063.  
  2064. /*  Z S O U T L  --  Write string to file, with line terminator, buffered  */
  2065.  
  2066. /*  Returns 0 on success, -1 on failure */
  2067.  
  2068. int
  2069. zsoutl(n,s) int n; char *s; {
  2070.     if (zsout(n,s) < 0)
  2071.         return(-1);
  2072.  
  2073. #ifdef IKSD
  2074.     if (inserver && !local && (n == ZCTERM || n == ZSTDIO)) {
  2075. #ifdef COMMENT
  2076.         return(ttoc(LF));
  2077. #else
  2078.         return(0);                      /* See comments in zsout() */
  2079. #endif /* COMMENT */
  2080.     }
  2081. #endif /* IKSD */
  2082.  
  2083.     if (n == ZSFILE)                    /* Session log is unbuffered */
  2084.       return(write(fileno(fp[n]),"\n",1) == 1 ? 0 : -1);
  2085.     else if (fputs("\n",fp[n]) == EOF)
  2086.       return(-1);
  2087.     if (n == ZDIFIL || n == ZWFILE)     /* Flush connection log records */
  2088.       fflush(fp[n]);
  2089.     return(0);
  2090. }
  2091.  
  2092. /*  Z S O U T X  --  Write x characters to file, unbuffered.  */
  2093.  
  2094. /*  Returns number of characters written on success, -1 on failure */
  2095.  
  2096. int
  2097. zsoutx(n,s,x) int n, x; char *s; {
  2098.     int k;
  2099.     if (!s) return(0);
  2100.     if (!*s) return(0);
  2101.  
  2102. #ifdef IKSD
  2103.     if (inserver && !local && (n == ZCTERM || n == ZSTDIO)) {
  2104. #ifdef COMMENT
  2105.         return(ttol(s,x));              /* See comments in zsout() */
  2106. #else
  2107.         return(x);
  2108. #endif /* COMMENT */
  2109.     }
  2110. #endif /* IKSD */
  2111.  
  2112.     if ((k = (int)strlen(s)) > x) x = k; /* Nothing else would make sense */
  2113. #ifdef COMMENT
  2114.     if (chkfn(n) < 1) return(-1);
  2115.     return(write(fp[n]->_file,s,x));
  2116. #endif /* COMMENT */
  2117.     return(write(fileno(fp[n]),s,x) == x ? x : -1);
  2118. }
  2119.  
  2120. /*  Z C H O U T  --  Add a character to the given file.  */
  2121.  
  2122. /*  Should return 0 or greater on success, -1 on failure (e.g. disk full)  */
  2123.  
  2124. int
  2125. #ifdef CK_ANSIC
  2126. zchout(register int n, char c)
  2127. #else
  2128. zchout(n,c) register int n; char c;
  2129. #endif /* CK_ANSIC */
  2130. /* zchout() */ {
  2131.     /* if (chkfn(n) < 1) return(-1); */
  2132.  
  2133. #ifdef IKSD
  2134.     if (inserver && !local && (n == ZCTERM || n == ZSTDIO)) {
  2135. #ifdef COMMENT
  2136.         return(ttoc(c));
  2137. #else
  2138.         return(0);                      /* See comments in zsout() */
  2139. #endif /* COMMENT */
  2140.     }
  2141. #endif /* IKSD */
  2142.  
  2143.     if (n == ZSFILE)                    /* Use unbuffered for session log */
  2144.       return(write(fileno(fp[n]),&c,1) == 1 ? 0 : -1);
  2145.                                 /* Buffered for everything else */
  2146.     if (putc(c,fp[n]) == EOF)   /* If true, maybe there was an error */
  2147.       return(ferror(fp[n])?-1:0);       /* Check to make sure */
  2148.     else                                /* Otherwise... */
  2149.       return(0);                        /* There was no error. */
  2150. }
  2151.  
  2152. /* (PWP) buffered character output routine to speed up file IO */
  2153.  
  2154. int
  2155. zoutdump() {
  2156.     int x;
  2157.     char * zp;
  2158.     zoutptr = zoutbuffer;               /* Reset buffer pointer in all cases */
  2159. #ifdef DEBUG
  2160.     if (deblog)
  2161.       debug(F101,"zoutdump zoutcnt","",zoutcnt);
  2162. #endif /* DEBUG */
  2163.     if (zoutcnt == 0) {                 /* Nothing to output */
  2164.         return(0);
  2165.     } else if (zoutcnt < 0) {           /* Unexpected negative argument */
  2166.         zoutcnt = 0;                    /* Reset output buffer count */
  2167.         return(-1);                     /* and fail. */
  2168.     }
  2169.  
  2170. #ifdef IKSD
  2171.     if (inserver && !local && fp[ZOFILE] == stdout) {
  2172. #ifdef COMMENT
  2173.         x = ttol(zoutbuffer,zoutcnt);
  2174. #else
  2175.         x = 1;                          /* See comments in zsout() */
  2176. #endif /* COMMENT */
  2177.         zoutcnt = 0;
  2178.         return(x > 0 ? 0 : -1);
  2179.     }
  2180. #endif /* IKSD */
  2181.  
  2182. /*
  2183.   Frank Prindle suggested that replacing this fwrite() by an fflush()
  2184.   followed by a write() would improve the efficiency, especially when
  2185.   writing to stdout.  Subsequent tests showed a 5-fold improvement.
  2186. */
  2187. #ifdef COMMENT
  2188.     if (x = fwrite(zoutbuffer, 1, zoutcnt, fp[ZOFILE])) ...
  2189. #endif /* COMMENT */
  2190.  
  2191. #ifndef CK_NONBLOCK
  2192.     fflush(fp[ZOFILE]);
  2193. #endif /* CK_NONBLOCK */
  2194.     zp = zoutbuffer;
  2195.     while (zoutcnt > 0) {
  2196.         if ((x = write(fileno(fp[ZOFILE]),zp,zoutcnt)) > -1) {
  2197. #ifdef DEBUG
  2198.             if (deblog)                 /* Save a function call... */
  2199.               debug(F101,"zoutdump wrote","",x);
  2200. #endif /* DEBUG */
  2201.             zoutcnt -= x;               /* Adjust output buffer count */
  2202.             zp += x;                    /* and pointer */
  2203.         } else {
  2204. #ifdef DEBUG
  2205.             if (deblog) {
  2206.                 debug(F101,"zoutdump write error","",errno);
  2207.                 debug(F101,"zoutdump write returns","",x);
  2208.             }
  2209. #endif /* DEBUG */
  2210.             zoutcnt = 0;                /* Reset output buffer count */
  2211.             return(-1);                 /* write() failed */
  2212.         }
  2213.     }
  2214.     return(0);
  2215. }
  2216.  
  2217. /*  C H K F N  --  Internal function to verify file number is ok  */
  2218.  
  2219. /*
  2220.  Returns:
  2221.   -1: File number n is out of range
  2222.    0: n is in range, but file is not open
  2223.    1: n in range and file is open
  2224. */
  2225. int
  2226. chkfn(n) int n; {
  2227.     /* if (n != ZDFILE) debug(F101,"chkfn","",n); */
  2228.     if (n < 0 || n >= ZNFILS) {
  2229.         if (n != ZDFILE) debug(F101,"chkfn out of range","",n);
  2230.         return(-1);
  2231.     } else {
  2232.         /* if (n != ZDFILE) debug(F101,"chkfn fp[n]","",fp[n]); */
  2233.         return((fp[n] == NULL) ? 0 : 1);
  2234.     }
  2235. }
  2236.  
  2237. /*  Z G E T F S -- Return file size regardless of accessibility */
  2238. /*
  2239.   Used for directory listings, etc.
  2240.   Returns:
  2241.     The size of the file in bytes, 0 or greater, if the size can be learned.
  2242.     -1 if the file size can not be obtained.
  2243.   Also (and this is a hack just for UNIX):
  2244.     If the argument is the name of a symbolic link,
  2245.     the global variable issymlink is set to 1,
  2246.     and the global buffer linkname[] gets the link value.
  2247.     And it sets zgfs_dir to 1 if it's a directory, otherwise 0.
  2248.   This lets us avoid numerous redundant calls to stat().
  2249. */
  2250. int zgfs_link = 0;
  2251. int zgfs_dir = 0;
  2252. time_t zgfs_mtime = 0;
  2253. unsigned int zgfs_mode = 0;
  2254.  
  2255. #ifdef CKSYMLINK
  2256. char linkname[CKMAXPATH+1];
  2257. #ifndef _IFLNK
  2258. #define _IFLNK 0120000
  2259. #endif /* _IFLNK */
  2260. #endif /* CKSYMLINK */
  2261.  
  2262. CK_OFF_T
  2263. zgetfs(name) char *name; {
  2264.     struct stat buf;
  2265.     char fnam[CKMAXPATH+4];
  2266.     CK_OFF_T size = (CK_OFF_T)-1;
  2267.     int x;
  2268.     int needrlink = 0;
  2269.     char * s;
  2270.  
  2271.     if (!name) name = "";
  2272.     if (!*name) return(-1);
  2273.  
  2274. #ifdef UNIX
  2275.     x = strlen(name);
  2276.     if (x == 9 && !strcmp(name,"/dev/null"))
  2277.       return(0);
  2278. #endif /* UNIX */
  2279.  
  2280.     s = name;
  2281. #ifdef DTILDE
  2282.     if (*s == '~') {
  2283.         s = tilde_expand(s);
  2284.         if (!s) s = "";
  2285.         if (!*s) s = name;
  2286.     }
  2287. #endif /* DTILDE */
  2288.     x = ckstrncpy(fnam,s,CKMAXPATH);
  2289.     s = fnam;
  2290.     debug(F111,"zgetfs fnam",s,x);
  2291.     if (x > 0 && s[x-1] == '/')
  2292.       s[x-1] = '\0';
  2293.  
  2294.     zgfs_dir = 0;                       /* Assume it's not a directory */
  2295.     zgfs_link = 0;                      /* Assume it's not a symlink */
  2296.     zgfs_mtime = 0;            /* No time yet */
  2297.     zgfs_mode = 0;            /* No permission bits yet */
  2298.  
  2299. #ifdef CKSYMLINK                        /* We're doing symlinks? */
  2300. #ifdef USE_LSTAT                        /* OK to use lstat()? */
  2301.     x = lstat(s,&buf);
  2302.     debug(F101,"STAT","",1);
  2303.     if (x < 0)                          /* stat() failed */
  2304.       return(-1);
  2305.     if (                                /* Now see if it's a symlink */
  2306. #ifdef S_ISLNK
  2307.         S_ISLNK(buf.st_mode)
  2308. #else
  2309. #ifdef _IFLNK
  2310.         ((_IFMT & buf.st_mode) == _IFLNK)
  2311. #endif /* _IFLNK */
  2312. #endif /* S_ISLNK */
  2313.         ) {
  2314.         zgfs_link = 1;                  /* It's a symlink */
  2315.         linkname[0] = '\0';             /* Get the name */
  2316.         x = readlink(s,linkname,CKMAXPATH);
  2317.         debug(F101,"zgetfs readlink",s,x);
  2318.         if (x > -1 && x < CKMAXPATH) {  /* It's a link */
  2319.             linkname[x] = '\0';
  2320.             size = buf.st_size;         /* Remember size of link */
  2321.             x = stat(s,&buf);           /* Now stat the linked-to file */
  2322.         debug(F101,"STAT","",2);
  2323.             if (x < 0)                  /* so we can see if it's a directory */
  2324.               return(-1);
  2325.         } else {
  2326.             ckstrncpy(linkname,"(lookup failed)",CKMAXPATH);
  2327.         }
  2328.     }
  2329. #else  /* !USE_LSTAT */
  2330.     x = stat(s,&buf);                   /* No lstat(), use stat() instead */
  2331.     debug(F101,"STAT","",3);
  2332.     if (x < 0)
  2333.       return(-1);
  2334. #endif /* USE_LSTAT */
  2335.  
  2336.     /* Do we need to call readlink()? */
  2337.  
  2338. #ifdef NOLINKBITS
  2339. /*
  2340.   lstat() does not work in SCO operating systems.  From "man NS lstat":
  2341.  
  2342.   lstat obtains information about the file named by path. In the case of a
  2343.   symbolic link, lstat returns information about the link, and not the file
  2344.   named by the link. It is only used by the NFS automount daemon and should
  2345.   not be utilized by users.
  2346. */
  2347.     needrlink = 1;
  2348.     debug(F101,"zgetfs forced needrlink","",needrlink);
  2349. #else
  2350. #ifdef S_ISLNK
  2351.     needrlink = S_ISLNK(buf.st_mode);
  2352.     debug(F101,"zgetfs S_ISLNK needrlink","",needrlink);
  2353. #else
  2354. #ifdef _IFLNK
  2355.     needrlink = (_IFMT & buf.st_mode) == _IFLNK;
  2356.     debug(F101,"zgetfs _IFLNK needrlink","",needrlink);
  2357. #else
  2358.     needrlink = 1;
  2359.     debug(F101,"zgetfs default needrlink","",needrlink);
  2360. #endif /* _IFLNK */
  2361. #endif /* S_ISLNK */
  2362. #endif /* NOLINKBITS */
  2363.  
  2364.     if (needrlink) {
  2365.         linkname[0] = '\0';
  2366.         errno = 0;
  2367.         x = readlink(s,linkname,CKMAXPATH);
  2368. #ifdef DEBUG
  2369.         debug(F111,"zgetfs readlink",s,x);
  2370.         if (x < 0)
  2371.           debug(F101,"zgetfs readlink errno","",errno);
  2372.         else
  2373.           debug(F110,"zgetfs readlink result",linkname,0);
  2374. #endif /* DEBUG */
  2375.         if (x > -1 && x < CKMAXPATH) {
  2376.             zgfs_link = 1;
  2377.             linkname[x] = '\0';
  2378.         }
  2379.     }
  2380. #else  /* !CKSYMLINK */
  2381.     x = stat(s,&buf);                   /* Just stat the file */
  2382.     debug(F111,"zgetfs stat",s,x);
  2383.     if (x < 0)                          /* and get the size */
  2384.       return(-1);
  2385. #endif /* CKSYMLINK */
  2386.  
  2387.     zgfs_mtime = buf.st_mtime;
  2388.     zgfs_mode = buf.st_mode;
  2389.     zgfs_dir = (S_ISDIR(buf.st_mode)) ? 1 : 0; /* Set "is directory" flag */
  2390.     debug(F111,"zgetfs size",s,size);
  2391.     debug(F111,"zgetfs st_size",s,buf.st_size);
  2392.     return((size < 0L) ? buf.st_size : size); /* Return the size */
  2393. }
  2394.  
  2395.  
  2396. /*  Z C H K I  --  Check if input file exists and is readable  */
  2397.  
  2398. /*
  2399.   Returns:
  2400.    >= 0 if the file can be read (returns the size).
  2401.      -1 if file doesn't exist or can't be accessed,
  2402.      -2 if file exists but is not readable (e.g. a directory file).
  2403.      -3 if file exists but protected against read access.
  2404.  
  2405.   For Berkeley Unix, a file must be of type "regular" to be readable.
  2406.   Directory files, special files, and symbolic links are not readable.
  2407. */
  2408. CK_OFF_T
  2409. zchki(name) char *name; {
  2410.     struct stat buf;
  2411.     char * s;
  2412.     int x, itsadir = 0;
  2413.     extern int zchkid, diractive, matchfifo;
  2414.  
  2415.     if (!name)
  2416.       return(-1);
  2417.     x = strlen(name);
  2418.     if (x < 1)
  2419.       return(-1);
  2420.     s = name;
  2421.  
  2422. #ifdef UNIX
  2423.     if (x == 9 && !strcmp(s,"/dev/null"))
  2424.       return(0);
  2425.     if (x == 8 && !strcmp(s,"/dev/tty"))
  2426.       return(0);
  2427. #endif /* UNIX */
  2428.  
  2429. #ifdef DTILDE
  2430.     if (*s == '~') {
  2431.         s = tilde_expand(s);
  2432.         if (!s) s = "";
  2433.         if (!*s) s = name;
  2434.     }
  2435. #endif /* DTILDE */
  2436.  
  2437. #ifdef CKROOT
  2438.     debug(F111,"zchki setroot",ckroot,ckrootset);
  2439.     if (ckrootset) if (!zinroot(name)) {
  2440.     debug(F110,"zchki setroot violation",name,0);
  2441.     return(-1);
  2442.     }
  2443. #endif /* CKROOT */
  2444.  
  2445.     x = stat(s,&buf);
  2446.     debug(F101,"STAT","",5);
  2447.     if (x < 0) {
  2448.         debug(F111,"zchki stat fails",s,errno);
  2449.         return(-1);
  2450.     }
  2451.     if (S_ISDIR (buf.st_mode))
  2452.       itsadir = 1;
  2453.  
  2454.     if (!(itsadir && zchkid)) {         /* Unless this... */
  2455.         if (!S_ISREG (buf.st_mode)      /* Must be regular file */
  2456. #ifdef S_ISFIFO
  2457.             && (!matchfifo || !S_ISFIFO (buf.st_mode))  /* or FIFO */
  2458. #endif /* S_ISFIFO */
  2459.             ) {
  2460.             debug(F111,"zchki not regular file (or fifo)",s,matchfifo);
  2461.             return(-2);
  2462.         }
  2463.     }
  2464.     debug(F111,"zchki stat ok:",s,x);
  2465.  
  2466.     if (diractive) {            /* If listing don't check access */
  2467.     x = 1;
  2468.     } else {
  2469. #ifdef SW_ACC_ID
  2470.     debug(F100,"zchki swapping ids for access()","",0);
  2471.     priv_on();
  2472. #endif /* SW_ACC_ID */
  2473.     if ((x = access(s,R_OK)) < 0)
  2474.       x = access(s,X_OK);        /* For RUN-class commands */
  2475. #ifdef SW_ACC_ID
  2476.     priv_off();
  2477.     debug(F100,"zchki swapped ids restored","",0);
  2478. #endif /* SW_ACC_ID */
  2479.     }
  2480.     if (x < 0) {            /* Is the file accessible? */
  2481.         debug(F111,"zchki access failed:",s,x); /* No */
  2482.         return(-3);
  2483.     } else {
  2484.         iflen = buf.st_size;            /* Yes, remember size */
  2485.         ckstrncpy(nambuf,s,CKMAXPATH);  /* and name globally. */
  2486.         debug(F111,"zchki access ok:",s,iflen);
  2487.         return((iflen > -1L) ? iflen : 0L);
  2488.     }
  2489. }
  2490.  
  2491. /*  Z C H K O  --  Check if output file can be created  */
  2492.  
  2493. /*
  2494.   Returns -1 if write permission for the file would be denied, 0 otherwise.
  2495.  
  2496.   NOTE: The design is flawed.  There is no distinction among:
  2497.    . Can I overwrite an existing file?
  2498.    . Can I create a file (or directory) in an existing directory?
  2499.    . Can I create a file (or directory) and its parent(s)?
  2500. */
  2501. int
  2502. zchko(name) char *name; {
  2503.     int i, x, itsadir = 0;
  2504.     char *s = NULL;
  2505.     char * oname;
  2506.     extern int zchkod;                  /* Used by IF WRITEABLE */
  2507.  
  2508.     debug(F110,"zchko entry",name,0);
  2509.  
  2510.     if (!name) return(-1);              /* Watch out for null pointer. */
  2511.  
  2512.     oname = name;
  2513.  
  2514. #ifdef CKROOT
  2515.     debug(F111,"zchko setroot",ckroot,ckrootset);
  2516.     if (ckrootset) if (!zinroot(name)) {
  2517.     debug(F110,"zchko setroot violation",name,0);
  2518.     errno = EACCES;
  2519.     return(-1);
  2520.     }
  2521. #endif /* CKROOT */
  2522.  
  2523.     x = (int)strlen(name);              /* Get length of filename */
  2524.     debug(F111,"zchko len",name,x);
  2525.     debug(F111,"zchko zchkod",name,zchkod);
  2526.  
  2527. #ifdef UNIX
  2528. /*
  2529.   Writing to null device is OK.
  2530. */
  2531.     if (x == 9 && !strcmp(name,"/dev/null"))
  2532.       return(0);
  2533.     if (x == 8 && !strcmp(name,"/dev/tty"))
  2534.       return(0);
  2535. #endif /* UNIX */
  2536.  
  2537.     s = name;
  2538. #ifdef DTILDE
  2539.     if (*s == '~') {
  2540.         s = tilde_expand(s);
  2541.         if (!s) s = "";
  2542.         if (!*s) s = name;
  2543.     x = strlen(s);
  2544.     }
  2545. #endif /* DTILDE */
  2546.     name = s;
  2547.     s = NULL;
  2548. /*
  2549.   zchkod is a global flag meaning we're checking not to see if the directory
  2550.   file is writeable, but if it's OK to create files IN the directory.
  2551. */
  2552.     if (!zchkod && isdir(name)) {    /* Directories are not writeable */
  2553.     debug(F111,"zchko isdir",name,1);
  2554.     return(-1);
  2555.     }
  2556.     s = malloc(x+3);                    /* Must copy because we can't */
  2557.     if (!s) {                           /* write into our argument. */
  2558.         fprintf(stderr,"zchko: Malloc error 46\n");
  2559.         return(-1);
  2560.     }
  2561.     ckstrncpy(s,name,x+3);
  2562. #ifdef UNIX
  2563. #ifdef NOUUCP
  2564.     {                    /* 2009/10/20 */
  2565.     /* Allow tty devices to opened as output files */
  2566.     int fd, istty = 0, mode = 0;
  2567.     debug(F110,"zchko attempting to open",name,0);
  2568.     /* Don't block on lack of Carrier or other modem signals */
  2569. #ifdef O_NONBLOCK
  2570.     mode = O_NONBLOCK;
  2571. #else
  2572. #ifdef O_NDELAY
  2573.     mode = O_NDELAY;
  2574. #else
  2575. #ifdef FNDELAY
  2576.     mode = FNDELAY;
  2577. #endif /* FNDELAY */
  2578. #endif    /* O_NDELAY */
  2579. #endif    /* O_NONBLOCK */
  2580.     debug(F111,"zchko open mode",name,mode);
  2581.     fd = open(name,O_WRONLY,mode);    /* Must attempt to open it */
  2582.     debug(F111,"zchko open",name,fd); 
  2583.     if (fd > -1) {            /* to get a file descriptor */
  2584.         if (isatty(fd))        /* for isatty() */
  2585.           istty++;
  2586.         debug(F111,"zchko isatty",name,istty);
  2587.         fd = close(fd);
  2588.         if (istty) {
  2589.         goto doaccess;
  2590.         }
  2591.     } else {
  2592.         debug(F101,"zchko open errno","",errno); 
  2593.         x = -1;
  2594.     }
  2595.     }
  2596. #endif    /* NOUUCP */
  2597. #endif    /* UNIX */
  2598.     for (i = x; i > 0; i--) {           /* Strip filename from right. */
  2599.         if (ISDIRSEP(s[i-1])) {
  2600.             itsadir = 1;
  2601.             break;
  2602.         }
  2603.     }
  2604.     debug(F101,"zchko i","",i);
  2605.     debug(F101,"zchko itsadir","",itsadir);
  2606.  
  2607. #ifdef COMMENT
  2608. /* X/OPEN XPG3-compliant systems fail if argument ends with "/"...  */
  2609.     if (i == 0)                         /* If no path, use current directory */
  2610.       strcpy(s,"./");
  2611.     else                                /* Otherwise, use given one. */
  2612.       s[i] = '\0';
  2613. #else
  2614. #ifdef COMMENT
  2615. /*
  2616.   The following does not work for "foo/bar" where the foo directory does
  2617.   not exist even though we could create it: access("foo/.") fails, but
  2618.   access("foo") works OK.
  2619. */
  2620. /* So now we use "path/." if path given, or "." if no path given. */
  2621.     s[i++] = '.';                       /* Append "." to path. */
  2622.     s[i] = '\0';
  2623. #else
  2624. /* So NOW we strip path segments from the right as long as they don't */
  2625. /* exist -- we only call access() for path segments that *do* exist.. */
  2626. /* (But this isn't quite right either since now zchko(/foo/bar/baz/xxx) */
  2627. /* succeeds when I have write access to foo and bar but baz doesn't exit.) */
  2628.  
  2629.     if (itsadir && i > 0) {
  2630.         s[i-1] = '\0';
  2631.         while (s[0] && !isdir(s)) {
  2632.             for (i = (int)strlen(s); i > 0; i--) {
  2633.                 if (ISDIRSEP(s[i-1])) {
  2634.                     s[i-1] = '\0';
  2635.                     break;
  2636.                 }
  2637.             }
  2638.             if (i == 0)
  2639.               s[0] = '\0';
  2640.         }
  2641.     } else {
  2642.         s[i++] = '.';                   /* Append "." to path. */
  2643.         s[i] = '\0';
  2644.     }
  2645. #endif /* COMMENT */
  2646. #endif /* COMMENT */
  2647.  
  2648.     if (!s[0])
  2649.       ckstrncpy(s,".",x+3);
  2650.  
  2651.   doaccess:
  2652.  
  2653. #ifdef SW_ACC_ID
  2654.     debug(F100,"zchko swapping ids for access()","",0);
  2655.     priv_on();
  2656. #endif /* SW_ACC_ID */
  2657.  
  2658.     x = access(s,W_OK);                 /* Check access of path. */
  2659.  
  2660. #ifdef SW_ACC_ID
  2661.     priv_off();
  2662.     debug(F100,"zchko swapped ids restored","",0);
  2663. #endif /* SW_ACC_ID */
  2664.  
  2665.     if (x < 0)
  2666.       debug(F111,"zchko access failed:",s,errno);
  2667.     else
  2668.       debug(F111,"zchko access ok:",s,x);
  2669.     if (s) free(s);            /* Free temporary storage */
  2670.  
  2671.     return((x < 0) ? -1 : 0);           /* and return. */
  2672. }
  2673.  
  2674. /*  Z D E L E T  --  Delete the named file.  */
  2675.  
  2676. /* Returns: -1 on error, 0 on success */
  2677.  
  2678. int
  2679. zdelet(name) char *name; {
  2680.     int x;
  2681. #ifdef CK_LOGIN
  2682.     if (isguest)
  2683.       return(-1);
  2684. #endif /* CK_LOGIN */
  2685.  
  2686. #ifdef CKROOT
  2687.     debug(F111,"zdelet setroot",ckroot,ckrootset);
  2688.     if (ckrootset) if (!zinroot(name)) {
  2689.     debug(F110,"zdelet setroot violation",name,0);
  2690.     return(-1);
  2691.     }
  2692. #endif /* CKROOT */
  2693.  
  2694.     x = unlink(name);
  2695.     debug(F111,"zdelet",name,x);
  2696. #ifdef CKSYSLOG
  2697.     if (ckxsyslog >= SYSLG_FC && ckxlogging) {
  2698.         fullname[0] = '\0';
  2699.         zfnqfp(name,CKMAXPATH,fullname);
  2700.         debug(F110,"zdelet fullname",fullname,0);
  2701.         if (x < 0)
  2702.           syslog(LOG_INFO, "file[] %s: delete failed (%m)", fullname);
  2703.         else
  2704.           syslog(LOG_INFO, "file[] %s: delete ok", fullname);
  2705.     }
  2706. #endif /* CKSYSLOG */
  2707.     return(x);
  2708. }
  2709.  
  2710. /*  Z R T O L  --  Convert remote filename into local form  */
  2711.  
  2712. VOID
  2713. zrtol(name,name2) char *name, *name2; {
  2714.     nzrtol(name,name2,1,0,CKMAXPATH);
  2715. }
  2716.  
  2717. VOID
  2718. nzrtol(name,name2,fncnv,fnrpath,max)
  2719.     char *name, *name2; int fncnv, fnrpath, max;
  2720. { /* nzrtol */
  2721.     char *s, *p;
  2722.     int flag = 0, n = 0;
  2723.     char fullname[CKMAXPATH+1];
  2724.     int devnull = 0;
  2725.     int acase = 0;
  2726.     if (!name2) return;
  2727.     if (!name) name = "";
  2728.  
  2729.     debug(F111,"nzrtol name",name,fncnv);
  2730.  
  2731. #ifdef DTILDE
  2732.     s = name;
  2733.     if (*s == '~') {
  2734.         s = tilde_expand(s);
  2735.         if (!s) s = "";
  2736.         if (*s) name = s;
  2737.     }
  2738. #endif /* DTILDE */
  2739.  
  2740.     /* Handle the path -- we don't have to convert its format, since */
  2741.     /* the standard path format and our (UNIX) format are the same. */
  2742.  
  2743.     fullname[0] = NUL;
  2744.     devnull = !strcmp(name,"/dev/null");
  2745.  
  2746.     if (!devnull && fnrpath == PATH_OFF) { /* RECEIVE PATHNAMES OFF */
  2747.         zstrip(name,&p);
  2748.         strncpy(fullname,p,CKMAXPATH);
  2749.     } else if (!devnull && fnrpath == PATH_ABS) { /* REC PATHNAMES ABSOLUTE */
  2750.         strncpy(fullname,name,CKMAXPATH);
  2751.     } else if (!devnull && isabsolute(name)) { /* RECEIVE PATHNAMES RELATIVE */
  2752.     ckmakmsg(fullname,CKMAXPATH,".",name,NULL,NULL);
  2753.     } else {                            /* Ditto */
  2754.         ckstrncpy(fullname,name,CKMAXPATH);
  2755.     }
  2756.     fullname[CKMAXPATH] = NUL;
  2757.     debug(F110,"nzrtol fullname",fullname,0);
  2758.  
  2759. #ifndef NOTRUNCATE
  2760. /*
  2761.   The maximum length for any segment of a filename is MAXNAMLEN, defined
  2762.   above.  On some platforms (at least QNX) if a segment exceeds this limit,
  2763.   the open fails with ENAMETOOLONG, so we must prevent it by truncating each
  2764.   overlong name segment to the maximum segment length before passing the
  2765.   name to open().  This must be done even when file names are literal, so as
  2766.   not to halt a file transfer unnecessarily.
  2767. */
  2768.     {
  2769.         char buf[CKMAXPATH+1];          /* New temporary buffer on stack */
  2770.         char *p = fullname;             /* Source and  */
  2771.         char *s = buf;                  /* destination pointers */
  2772.         int i = 0, n = 0;
  2773.         debug(F101,"nzrtol sizing MAXNAMLEN","",MAXNAMLEN);
  2774.         while (*p && n < CKMAXPATH) {   /* Copy name to new buffer */
  2775.             if (++i > MAXNAMLEN) {      /* If this segment too long */
  2776.                 while (*p && *p != '/') /* skip past the rest... */
  2777.                   p++;
  2778.                 i = 0;                  /* and reset counter. */
  2779.             } else if (*p == '/') {     /* End of this segment. */
  2780.                 i = 0;                  /* Reset counter. */
  2781.             }
  2782.             *s++ = *p++;                /* Copy this character. */
  2783.             n++;
  2784.         }
  2785.         *s = NUL;
  2786.         ckstrncpy(fullname,buf,CKMAXPATH); /* Copy back to original buffer. */
  2787.         debug(F111,"nzrtol sizing",fullname,n);
  2788.     }
  2789. #endif /* NOTRUNCATE */
  2790.  
  2791.     if (!fncnv || devnull) {            /* Not converting */
  2792.         ckstrncpy(name2,fullname,max);  /* We're done. */
  2793.         return;
  2794.     }
  2795.     name = fullname;                    /* Converting */
  2796.  
  2797.     p = name2;
  2798.     for (; *name != '\0' && n < maxnam; name++) {
  2799.         if (*name > SP) flag = 1;       /* Strip leading blanks and controls */
  2800.         if (flag == 0 && *name < '!')
  2801.           continue;
  2802.     if (fncnv > 0) {
  2803.         if (*name == SP) {
  2804.         *p++ = '_';
  2805.         n++;
  2806.         continue;
  2807.         }
  2808.         if (isupper(*name))        /* Check for mixed case */
  2809.           acase |= 1;
  2810.         else if (islower(*name))
  2811.           acase |= 2;
  2812.     }
  2813.         *p++ = *name;
  2814.         n++;
  2815.     }
  2816.     *p-- = '\0';                        /* Terminate */
  2817.     while (*p < '!' && p > name2)       /* Strip trailing blanks & controls */
  2818.       *p-- = '\0';
  2819.  
  2820.     if (*name2 == '\0') {               /* Nothing left? */
  2821.         ckstrncpy(name2,"NONAME",max);    /* do this... */
  2822.     } else if (acase == 1) {            /* All uppercase? */
  2823.         p = name2;                      /* So convert all letters to lower */
  2824.         while (*p) {
  2825.             if (isupper(*p))
  2826.               *p = tolower(*p);
  2827.             p++;
  2828.         }
  2829.     }
  2830.     debug(F110,"nzrtol new name",name2,0);
  2831. }
  2832.  
  2833.  
  2834. /*  Z S T R I P  --  Strip device & directory name from file specification */
  2835.  
  2836. /*  Strip pathname from filename "name", return pointer to result in name2 */
  2837.  
  2838. static char work[CKMAXPATH+1];
  2839.  
  2840. VOID
  2841. zstrip(name,name2) char *name, **name2; {
  2842.     char *cp, *pp;
  2843.     int n = 0;
  2844.  
  2845.     debug(F110,"zstrip before",name,0);
  2846.     if (!name) { *name2 = ""; return; }
  2847.     pp = work;
  2848. #ifdef DTILDE
  2849.     /* Strip leading tilde */
  2850.     if (*name == '~') name++;
  2851.     debug(F110,"zstrip after tilde-stripping",name,0);
  2852. #endif /* DTILDE */
  2853.     for (cp = name; *cp; cp++) {
  2854.         if (ISDIRSEP(*cp)) {
  2855.             pp = work;
  2856.             n = 0;
  2857.         } else {
  2858.             *pp++ = *cp;
  2859.             if (n++ >= CKMAXPATH)
  2860.               break;
  2861.         }
  2862.     }
  2863.     *pp = '\0';                         /* Terminate the string */
  2864.     *name2 = work;
  2865.     debug(F110,"zstrip after",*name2,0);
  2866. }
  2867.  
  2868. /*  Z L T O R  --  Local TO Remote */
  2869.  
  2870. VOID
  2871. zltor(name,name2) char *name, *name2; {
  2872.     nzltor(name,name2,1,0,CKMAXPATH);
  2873. }
  2874.  
  2875. /*  N Z L T O R  --  New Local TO Remote */
  2876.  
  2877. /*
  2878.   fncnv = 0 for no conversion, > 0 for regular conversion, < 0 for minimal.
  2879. */
  2880. VOID
  2881. nzltor(name,name2,fncnv,fnspath,max)
  2882.     char *name, *name2; int fncnv, fnspath, max;
  2883. { /* nzltor */
  2884.     char *cp, *pp;
  2885. #ifdef COMMENT
  2886.     int dc = 0;
  2887. #endif /* COMMENT */
  2888.     int n = 0;
  2889.     char *dotp = NULL;
  2890.     char *dirp = NULL;
  2891.     char fullname[CKMAXPATH+1];
  2892.     char *p;
  2893.     CHAR c;
  2894.  
  2895. #ifndef NOCSETS
  2896.     extern int fcharset, /* tcharset, */ language;
  2897.     int langsv;
  2898.     _PROTOTYP ( CHAR (*sxo), (CHAR) ) = NULL; /* Translation functions */
  2899. #ifdef CK_ANSIC
  2900.     extern CHAR (*xls[MAXTCSETS+1][MAXFCSETS+1])(CHAR);
  2901. #else
  2902.     extern CHAR (*xls[MAXTCSETS+1][MAXFCSETS+1])();
  2903. #endif /* CK_ANSIC */
  2904.     langsv = language;
  2905.     language = L_USASCII;
  2906. #ifdef COMMENT
  2907.     /* Proper translation of filenames must be done elsewhere */
  2908.     n = tcharset ? tcharset : TC_USASCII;
  2909.     sxo = xls[n][fcharset];
  2910. #else
  2911.     sxo = xls[TC_USASCII][fcharset];
  2912. #endif /* COMMENT */
  2913. #endif /* NOCSETS */
  2914.  
  2915.     debug(F110,"nzltor name",name,0);
  2916.  
  2917.     /* Handle pathname */
  2918.  
  2919.     fullname[0] = NUL;
  2920.     if (fnspath == PATH_OFF) {          /* PATHNAMES OFF */
  2921.         zstrip(name,&p);
  2922.         ckstrncpy(fullname,p,CKMAXPATH);
  2923.     } else {                            /* PATHNAMES RELATIVE or ABSOLUTE */
  2924.         char * p = name;
  2925.         while (1) {
  2926.             if (!strncmp(p,"../",3))
  2927.               p += 3;
  2928.             else if (!strncmp(p,"./",2))
  2929.               p += 2;
  2930.             else
  2931.               break;
  2932.         }
  2933.         if (fnspath == PATH_ABS) {      /* ABSOLUTE */
  2934.             zfnqfp(p,CKMAXPATH,fullname);
  2935.         } else {                        /* RELATIVE */
  2936.             ckstrncpy(fullname,p,CKMAXPATH);
  2937.         }
  2938.     }
  2939.     debug(F110,"nzltor fullname",fullname,0);
  2940.  
  2941.     if (!fncnv) {                       /* Not converting */
  2942.         ckstrncpy(name2,fullname,max);  /* We're done. */
  2943. #ifndef NOCSETS
  2944.         langsv = language;
  2945. #endif /* NOCSETS */
  2946.         return;
  2947.     }
  2948.     name = fullname;                    /* Converting */
  2949.  
  2950. #ifdef aegis
  2951.     char *namechars;
  2952.     int tilde = 0, bslash = 0;
  2953.  
  2954.     if ((namechars = getenv("NAMECHARS")) != NULL) {
  2955.         if (ckstrchr(namechars, '~' ) != NULL) tilde  = '~';
  2956.         if (ckstrchr(namechars, '\\') != NULL) bslash = '\\';
  2957.     } else {
  2958.         tilde = '~';
  2959.         bslash = '\\';
  2960.     }
  2961. #endif /* aegis */
  2962.  
  2963.     pp = work;                          /* Output buffer */
  2964.     for (cp = name, n = 0; *cp && n < max; cp++,n++) { /* Convert name chars */
  2965.         c = *cp;
  2966. #ifndef NOCSETS
  2967.         if (sxo) c = (*sxo)(c);         /* Convert to ASCII */
  2968. #endif /* NOCSETS */
  2969.         if (fncnv > 0 && islower(c))    /* Uppercase letters */
  2970.           *pp++ = toupper(c);           /* Change tilde to hyphen */
  2971.         else if (c == '~')
  2972.           *pp++ = '-';
  2973.         else if (fncnv > 0 && c == '#')    /* Change number sign to 'X' */
  2974.           *pp++ = 'X';
  2975.         else if (c == '*' || c == '?')  /* Change wildcard chars to 'X' */
  2976.           *pp++ = 'X';
  2977.         else if (c == ' ')              /* Change space to underscore */
  2978.           *pp++ = '_';
  2979.         else if (c < ' ')               /* Change controls to 'X' */
  2980.           *pp++ = 'X';
  2981.         else if (fncnv > 0 && c == '.') { /* Change dot to underscore */
  2982.             dotp = pp;                  /* Remember where we last did this */
  2983.             *pp++ = '_';
  2984.         } else {
  2985.             if (c == '/')
  2986.               dirp = pp;
  2987.             *pp++ = c;
  2988.         }
  2989.     }
  2990.     *pp = NUL;                          /* Tie it off. */
  2991. #ifdef COMMENT
  2992.     if (dotp) *dotp = '.';              /* Restore last dot (if any) */
  2993. #else
  2994.     if (dotp > dirp) *dotp = '.';       /* Restore last dot in file name */
  2995. #endif /* COMMENT */
  2996.     cp = name2;                         /* If nothing before dot, */
  2997.     if (*work == '.') *cp++ = 'X';      /* insert 'X' */
  2998.     ckstrncpy(cp,work,max);
  2999. #ifndef NOCSETS
  3000.     language = langsv;
  3001. #endif /* NOCSETS */
  3002.     debug(F110,"nzltor name2",name2,0);
  3003. }
  3004.  
  3005.  
  3006. /*  Z C H D I R  --  Change directory  */
  3007. /*
  3008.   Call with:
  3009.     dirnam = pointer to name of directory to change to,
  3010.       which may be "" or NULL to indicate user's home directory.
  3011.   Returns:
  3012.     0 on failure
  3013.     1 on success
  3014. */
  3015. int
  3016. zchdir(dirnam) char *dirnam; {
  3017.     char *hd, *sp;
  3018. #ifdef IKSDB
  3019.     _PROTOTYP (int slotdir,(char *,char *));
  3020. #endif /* IKSDB */
  3021. #ifndef NOSPL
  3022.     extern struct mtab *mactab;             /* Main macro table */
  3023.     extern int nmac;                        /* Number of macros */
  3024. #endif /* NOSPL */
  3025.  
  3026.     debug(F110,"zchdir",dirnam,0);
  3027.     if (!dirnam) dirnam = "";
  3028.     if (!*dirnam)                       /* If argument is null or empty, */
  3029.       dirnam = zhome();                 /* use user's home directory. */
  3030.     sp = dirnam;
  3031.     debug(F110,"zchdir 2",dirnam,0);
  3032.  
  3033. #ifdef DTILDE
  3034.     hd = tilde_expand(dirnam);          /* Attempt to expand tilde */
  3035.     if (!hd) hd = "";
  3036.     if (*hd == '\0') hd = dirnam;       /* in directory name. */
  3037. #else
  3038.     hd = dirnam;
  3039. #endif /* DTILDE */
  3040.     debug(F110,"zchdir 3",hd,0);
  3041.  
  3042. #ifdef CKROOT
  3043.     debug(F111,"zchdir setroot",ckroot,ckrootset);
  3044.     if (ckrootset) if (!zinroot(hd)) {
  3045.     debug(F110,"zchdir setroot violation",hd,0);
  3046.     return(0);
  3047.     }
  3048. #endif /* CKROOT */
  3049.  
  3050. #ifdef pdp11
  3051.     /* Just to save some space */
  3052.     return((chdir(hd) == 0) ? 1 : 0);
  3053. #else
  3054.     if (chdir(hd) == 0) {                       /* Try to cd */
  3055. #ifdef IKSDB
  3056. #ifdef CK_LOGIN
  3057.         if (inserver && ikdbopen)
  3058.           slotdir(isguest ? anonroot : "", zgtdir());
  3059. #endif /* CK_LOGIN */
  3060. #endif /* IKSDB */
  3061.  
  3062. #ifndef NOSPL
  3063.         if (nmac) {            /* Any macros defined? */
  3064.             int k;            /* Yes */
  3065.             static int on_cd = 0;
  3066.             if (!on_cd) {
  3067.                 on_cd = 1;
  3068.                 k = mlook(mactab,"on_cd",nmac);   /* Look this up */
  3069.                 if (k >= 0) {                     /* If found, */
  3070.                     if (dodo(k,zgtdir(),0) > -1)  /* set it up, */
  3071.               parser(1);                  /* and execute it */
  3072.                 }
  3073.                 on_cd = 0;
  3074.             }
  3075.         }
  3076. #endif /* NOSPL */
  3077.         return(1);
  3078.     }
  3079.     return(0);
  3080. #endif /* pdp11 */
  3081. }
  3082.  
  3083. int
  3084. #ifdef CK_ANSIC
  3085. zchkpid(unsigned long xpid)
  3086. #else
  3087. zchkpid(xpid) unsigned long xpid;
  3088. #endif /* CK_ANSIC */
  3089. {
  3090.     return((kill((PID_T)xpid,0) < 0) ? 0 : 1);
  3091. }
  3092.  
  3093.  
  3094. /*  Z H O M E  --  Return pointer to user's home directory  */
  3095.  
  3096. static char * zhomdir = NULL;
  3097.  
  3098. char *
  3099. zhome() {
  3100.     char * home;
  3101.  
  3102. #ifdef CKROOT
  3103.     if (ckrootset)
  3104.       return((char *)ckroot);
  3105. #endif /* CKROOT */
  3106.  
  3107. #ifdef Plan9
  3108.     home = getenv("home");
  3109. #else
  3110.     home = getenv("HOME");
  3111. #endif /* Plan9 */
  3112.     makestr(&zhomdir,home);
  3113.     return(home ? zhomdir : ".");
  3114. }
  3115.  
  3116. /*  Z G T D I R  --  Returns a pointer to the current directory  */
  3117.  
  3118. /*
  3119.   The "preferred" interface for getting the current directory in modern UNIX
  3120.   is getcwd() [POSIX 1003.1 5.2.2].  However, on certain platforms (such as
  3121.   SunOS), it is implemented by forking a shell, feeding it the pwd command,
  3122.   and returning the result, which is not only inefficient but also can result
  3123.   in stray messages to the terminal.  In such cases -- as well as when
  3124.   getcwd() is not available at all -- getwd() can be used instead by defining
  3125.   USE_GETWD.  However, note that getwd() provides no buffer-length argument
  3126.   and therefore no safeguard against memory leaks.
  3127. */
  3128. #ifndef USE_GETWD
  3129. #ifdef BSD42
  3130. #define USE_GETWD
  3131. #else
  3132. #ifdef SUNOS4
  3133. #define USE_GETWD
  3134. #endif /* SUNOS4 */
  3135. #endif /* BSD42 */
  3136. #endif /* USE_GETWD */
  3137.  
  3138. #ifdef pdp11
  3139. #define CWDBL 80                        /* Save every byte we can... */
  3140. #else
  3141. #define CWDBL CKMAXPATH
  3142. #endif /* pdp11 */
  3143. static char cwdbuf[CWDBL+2];
  3144. /*
  3145.   NOTE: The getcwd() prototypes are commented out on purpose.  If you get
  3146.   compile-time warnings, search through your system's header files to see
  3147.   which one has the needed prototype, and #include it.  Usually it is
  3148.   <unistd.h>.  See the section for including <unistd.h> in ckcdeb.h and
  3149.   make any needed adjustments there (and report them).
  3150. */
  3151. char *
  3152. zgtdir() {
  3153.     char * buf = cwdbuf;
  3154.     char * s;
  3155.  
  3156. #ifdef USE_GETWD
  3157.     extern char *getwd();
  3158.     s = getwd(buf);
  3159.     debug(F110,"zgtdir BSD4 getwd()",s,0);
  3160.     if (!s) s = "./";
  3161.     return(s);
  3162. #else
  3163. #ifdef BSD44
  3164. #ifdef DCLGETCWD
  3165. _PROTOTYP( char * getcwd, (char *, SIZE_T) );
  3166. #endif /* DCLGETCWD */
  3167.     debug(F101,"zgtdir BSD44 CWDBL","",CWDBL);
  3168.     s = getcwd(buf,CWDBL);
  3169.     if (!s) s = "./";
  3170.     return(s);
  3171. #else
  3172. #ifdef MINIX2
  3173. #ifdef DCLGETCWD
  3174.     _PROTOTYP( char * getcwd, (char *, SIZE_T) );
  3175. #endif /* DCLGETCWD */
  3176.     debug(F101,"zgtdir MINIX2 CWDBL","",CWDBL);
  3177.     s = getcwd(buf,CWDBL);
  3178.     if (!s) s = "./";
  3179.     return(s);
  3180. #else
  3181. #ifdef SVORPOSIX
  3182. #ifdef COMMENT
  3183. /* This non-ANSI prototype can be fatal at runtime! (e.g. in SCO3.2v5.0.5). */
  3184. /* Anyway it's already prototyped in some header file that we have included. */
  3185.     extern char *getcwd();
  3186. #else
  3187. #ifdef DCLGETCWD
  3188.     _PROTOTYP( char * getcwd, (char *, SIZE_T) );
  3189. #endif /* DCLGETCWD */
  3190. #endif /* COMMENT */
  3191.     debug(F101,"zgtdir SVORPOSIX CWDBL","",CWDBL);
  3192.     s = getcwd(buf,CWDBL);
  3193.     if (!s) s = "./";
  3194.     return(s);
  3195. #else
  3196. #ifdef COHERENT
  3197. #ifdef _I386
  3198. #ifdef DCLGETCWD
  3199.     extern char *getcwd();
  3200. #endif /* DCLGETCWD */
  3201.     debug(F101,"zgtdir COHERENT _I386 CWDBL","",CWDBL);
  3202.     s = getcwd(buf,CWDBL);
  3203.     if (!s) s = "./";
  3204.     return(s);
  3205. #else
  3206.     extern char *getwd();
  3207.     debug(F101,"zgtdir COHERENT CWDBL","",CWDBL);
  3208.     s = getwd(buf);
  3209.     if (!s) s = "./";
  3210.     return(s);
  3211. #endif /* _I386 */
  3212. #else
  3213. #ifdef SUNOS4
  3214.     debug(F101,"zgtdir SUNOS CWDBL","",CWDBL);
  3215.     s = getcwd(buf,CWDBL);
  3216.     if (!s) s = "./";
  3217.     return(s);
  3218. #else
  3219.     return("./");
  3220. #endif /* SUNOS4 */
  3221. #endif /* COHERENT */
  3222. #endif /* SYSVORPOSIX */
  3223. #endif /* MINIX2 */
  3224. #endif /* BSD44 */
  3225. #endif /* USE_GETWD */
  3226. }
  3227.  
  3228. /*  Z X C M D -- Run a system command so its output can be read like a file */
  3229.  
  3230. #ifndef NOPUSH
  3231. int
  3232. zxcmd(filnum,comand) int filnum; char *comand; {
  3233.     int out;
  3234.     int pipes[2];
  3235.     extern int kactive;                 /* From ckcpro.w and ckcmai.c */
  3236.  
  3237.     if (nopush) {
  3238.         debug(F100,"zxcmd fails: nopush","",0);
  3239.         return(-1);
  3240.     }
  3241.     debug(F111,"zxcmd",comand,filnum);
  3242.     if (chkfn(filnum) < 0) return(-1);  /* Need a valid Kermit file number. */
  3243.     if (filnum == ZSTDIO || filnum == ZCTERM) /* But not one of these. */
  3244.       return(0);
  3245.  
  3246.     out = (filnum == ZIFILE || filnum == ZRFILE) ? 0 : 1 ;
  3247.     debug(F101,"zxcmd out",comand,out);
  3248.  
  3249. /* Output to a command */
  3250.  
  3251.     if (out) {                          /* Need popen() to do this. */
  3252.     ckstrncpy(fullname,"(pipe)",CKMAXPATH);
  3253. #ifdef NOPOPEN
  3254.         return(0);                      /* no popen(), fail. */
  3255. #else
  3256. /* Use popen() to run the command. */
  3257.  
  3258. #ifdef _POSIX_SOURCE
  3259. /* Strictly speaking, popen() is not available in POSIX.1 */
  3260. #define DCLPOPEN
  3261. #endif /* _POSIX_SOURCE */
  3262.  
  3263.     debug(F110,"zxcmd out",comand,0);
  3264.  
  3265.         if (priv_chk()) {
  3266.         debug(F100,"zxcmd priv_chk failed","",0);
  3267.             return(0);
  3268.     }    
  3269.     errno = 0;
  3270.         fp[filnum] = popen(comand,"w");
  3271.     debug(F111,"zxcmd popen",fp[filnum] ? "OK" : "Failed", errno);
  3272.     if (fp[filnum] == NULL)
  3273.       return(0);
  3274. #ifdef COMMENT
  3275. /* I wonder what this is all about... */
  3276.     close(pipes[0]);        /* Don't need the input side */
  3277.     fp[filnum] = fdopen(pipes[1],"w"); /* Open output stream. */
  3278.     fp[ZSYSFN] = fp[filnum];           /* Remember. */
  3279. #endif /* COMMENT */
  3280.     ispipe[filnum] = 1;
  3281.     zoutcnt = 0;            /* (PWP) reset input buffer */
  3282.     zoutptr = zoutbuffer;
  3283.     return(1);
  3284. #endif /* NOPOPEN */
  3285.     }
  3286.  
  3287. /* Input from a command */
  3288.  
  3289. #ifdef SNI541
  3290.     /* SINIX-L 5.41 does not like fdopen() */
  3291.     return(0);
  3292. #else
  3293.     if (pipe(pipes) != 0) {
  3294.         debug(F100,"zxcmd pipe failure","",0);
  3295.         return(0);                      /* can't make pipe, fail */
  3296.     }
  3297.  
  3298. /* Create a fork in which to run the named process */
  3299.  
  3300.     if ((
  3301. #ifdef aegis
  3302.          pid = vfork()                  /* child */
  3303. #else
  3304.          pid = fork()                   /* child */
  3305. #endif /* aegis */
  3306.          ) == 0) {
  3307.  
  3308. /* We're in the fork. */
  3309.  
  3310.         char *shpath, *shname, *shptr;  /* Find user's preferred shell */
  3311. #ifndef aegis
  3312.         struct passwd *p;
  3313.         char *defshell;
  3314. #ifdef HPUX10                           /* Default shell */
  3315.         defshell = "/usr/bin/sh";
  3316. #else
  3317. #ifdef Plan9
  3318.         defshell = "/bin/rc";
  3319. #else
  3320.         defshell = "/bin/sh";
  3321. #endif /* Plan9 */
  3322. #endif /* HPUX10 */
  3323. #endif /* aegis */
  3324.         if (priv_can()) exit(1);        /* Turn off any privileges! */
  3325.         debug(F101,"zxcmd pid","",pid);
  3326.         close(pipes[0]);                /* close input side of pipe */
  3327.         close(0);                       /* close stdin */
  3328.         if (open("/dev/null",0) < 0) return(0); /* replace input by null */
  3329. #ifndef OXOS
  3330. #ifndef SVORPOSIX
  3331.         dup2(pipes[1],1);               /* BSD: replace stdout & stderr */
  3332.         dup2(pipes[1],2);               /* by the pipe */
  3333. #else
  3334.         close(1);                       /* AT&T: close stdout */
  3335.         if (dup(pipes[1]) != 1)         /* Send stdout to the pipe */
  3336.           return(0);
  3337.         close(2);                       /* Send stderr to the pipe */
  3338.         if (dup(pipes[1]) != 2)
  3339.           return(0);
  3340. #endif /* SVORPOSIX */
  3341. #else /* OXOS */
  3342.         dup2(pipes[1],1);
  3343.         dup2(pipes[1],2);
  3344. #endif /* OXOS */
  3345.         close(pipes[1]);                /* Don't need this any more. */
  3346.  
  3347. #ifdef aegis
  3348.         if ((shpath = getenv("SERVERSHELL")) == NULL)
  3349.           shpath = "/bin/sh";
  3350. #else
  3351.         shpath = getenv("SHELL");       /* What shell? */
  3352.         if (shpath == NULL) {
  3353.             p = getpwuid( real_uid() ); /* Get login data */
  3354.             /* debug(F111,"zxcmd shpath","getpwuid()",p); */
  3355.             if (p == (struct passwd *)NULL || !*(p->pw_shell))
  3356.               shpath = defshell;
  3357.             else shpath = p->pw_shell;
  3358.         }
  3359. #endif /* aegis */
  3360.         shptr = shname = shpath;
  3361.         while (*shptr != '\0')
  3362.           if (*shptr++ == '/')
  3363.             shname = shptr;
  3364.         debug(F110,shpath,shname,0);
  3365.     restorsigs();            /* Restore ignored signals */
  3366.         execl(shpath,shname,"-c",comand,(char *)NULL); /* Execute the cmd */
  3367.         exit(0);                        /* just punt if it failed. */
  3368.     } else if (pid == (PID_T) -1) {
  3369.         debug(F100,"zxcmd fork failure","",0);
  3370.         return(0);
  3371.     }
  3372.     debug(F101,"zxcmd pid","",pid);
  3373.     close(pipes[1]);                    /* Don't need the output side */
  3374.     ispipe[filnum] = 1;                 /* Remember it's a pipe */
  3375.     fp[filnum] = fdopen(pipes[0],"r");    /* Open a stream for input. */
  3376.  
  3377. #ifdef DONDELAY
  3378. #ifdef SELECT
  3379.     if (filnum == ZIFILE && kactive) {  /* Make pipe reads nonblocking */
  3380.         int flags, x;
  3381.         if ((flags = fcntl(fileno(fp[filnum]),F_GETFL,0)) > -1) {
  3382.             debug(F101,"zxcmd fcntl 1 pipe flags","",flags);
  3383.             x = fcntl(fileno(fp[filnum]),F_SETFL, flags |
  3384. #ifdef QNX
  3385.                   O_NONBLOCK
  3386. #else
  3387.                   O_NDELAY
  3388. #endif /* QNX */
  3389.                   );
  3390.             debug(F101,"zxcmd fcntl 2 result","",x);
  3391.         }
  3392.     }
  3393. #endif /* SELECT */
  3394. #endif /* DONDELAY */
  3395. #endif /* SNI541 */
  3396.     fp[ZSYSFN] = fp[filnum];            /* Remember. */
  3397.     zincnt = 0;                         /* (PWP) reset input buffer */
  3398.     zinptr = zinbuffer;
  3399.     fullname[0] = '\0';
  3400.     return(1);
  3401. } /* zxcmd */
  3402.  
  3403. /*  Z C L O S F  - wait for the child fork to terminate and close the pipe. */
  3404.  
  3405. /*  Used internally by zclose - returns -1 on failure, 1 on success. */
  3406.  
  3407. int
  3408. zclosf(filnum) int filnum; {
  3409.     int wstat, out;
  3410.     int statusp;
  3411.  
  3412.     debug(F101,"zclosf filnum","",filnum);
  3413.     out = (filnum == ZIFILE || filnum == ZRFILE) ? 0 : 1 ;
  3414.     debug(F101,"zclosf out","",out);
  3415.  
  3416. #ifndef NOPOPEN
  3417.     if (ispipe[filnum]
  3418.         /* In UNIX we use popen() only for output files */
  3419.         && out
  3420.         ) {
  3421.         int x;
  3422.         x = pclose(fp[filnum]);
  3423.         pexitstat = x >> 8;
  3424.         debug(F101,"zclosf pclose","",x);
  3425.         debug(F101,"zclosf pexitstat","",pexitstat);
  3426.         fp[filnum] = fp[ZSYSFN] = NULL;
  3427.         ispipe[filnum] = 0;
  3428.         return((x != 0) ? -1 : 1);
  3429.     }
  3430. #endif /* NOPOPEN */
  3431.     /* debug(F101,"zclosf fp[filnum]","", fp[filnum]); */
  3432.     /* debug(F101,"zclosf fp[ZSYSFN]","", fp[ZSYSFN]); */
  3433.  
  3434.     if (pid != (PID_T) 0) {
  3435.         debug(F101,"zclosf killing pid","",pid);
  3436. #ifdef Plan9
  3437.         kill(pid, SIGKILL);
  3438. #else
  3439.         kill(pid,9);
  3440. #endif /* Plan9 */
  3441.  
  3442. #ifndef CK_CHILD
  3443. /*
  3444.   This is the original code (before 20 April 1997) and has proven totally
  3445.   portable.  But it does not give us the process's return code.
  3446. */
  3447.         while ((wstat = wait((WAIT_T *)0)) != pid && wstat != -1) ;
  3448. #else
  3449. /* Here we try to get the return code.  Let's hope this is portable too. */
  3450.         while ((wstat = wait(&statusp)) != pid && wstat != -1) ;
  3451.         pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
  3452.         debug(F101,"zclosf wait statusp","",statusp);
  3453.         debug(F101,"zclosf wait pexitstat","",pexitstat);
  3454. #endif /* CK_CHILD */
  3455.         pid = 0;
  3456.     }
  3457.     fclose(fp[filnum]);
  3458.     fp[filnum] = fp[ZSYSFN] = NULL;
  3459.  
  3460.     ispipe[filnum] = 0;
  3461.     /* debug(F101,"zclosf fp[filnum]","",fp[filnum]); */
  3462. #ifdef CK_CHILD
  3463.     return(pexitstat == 0 ? 1 : -1);
  3464. #else
  3465.     return(1);
  3466. #endif /* CK_CHILD */
  3467. }
  3468.  
  3469. #else  /* NOPUSH */
  3470.  
  3471. int
  3472. zxcmd(filnum,comand) int filnum; char *comand; {
  3473.     return(0);
  3474. }
  3475. int
  3476. zclosf(filnum) int filnum; {
  3477.     return(EOF);
  3478. }
  3479. #endif /* NOPUSH */
  3480.  
  3481.  
  3482. /*  Z X P A N D  --  Expand a wildcard string into an array of strings  */
  3483. /*
  3484.   As of C-Kermit 7.0, this API is obsolete, replaced by nzxpand(), and this
  3485.   function is only used internally.  See nzxpand() below.
  3486.  
  3487.   Returns the number of files that match fnarg, with data structures set up
  3488.   so that first file (if any) will be returned by the next znext() call.
  3489.  
  3490.   Depends on external variable wildxpand: 0 means we expand wildcards
  3491.   internally, nonzero means we call the shell to do it.
  3492.   
  3493.   AND in C-Kermit 8.0.212 and later, on extern wildena: 1 means wildcards
  3494.   are enabled, 0 means disabled, the characters are taken literally.
  3495. */
  3496. static int xdironly = 0;
  3497. static int xfilonly = 0;
  3498. static int xmatchdot = 0;
  3499. static int xrecursive = 0;
  3500. static int xnobackup = 0;
  3501. static int xnolinks = 0;
  3502.  
  3503. static char *freeptr = NULL, **resptr = NULL; /* Copies of caller's args */
  3504. static int remlen;                      /* Remaining space in caller's array */
  3505. static int numfnd = 0;            /* Number of matches found */
  3506.  
  3507. #define MINSPACE 1024
  3508.  
  3509. static int
  3510. initspace(resarry,len) char * resarry[]; int len; {
  3511. #ifdef DYNAMIC
  3512.     if (len < MINSPACE) len = MINSPACE;
  3513.     if (!sspace) {                      /* Need to allocate string space? */
  3514.         while (len >= MINSPACE) {
  3515.             if ((sspace = malloc(len+2))) { /* Got it. */
  3516.                 debug(F101,"fgen string space","",len);
  3517.                 break;
  3518.             }
  3519.             len = (len / 2) + (len / 4); /* Didn't, reduce by 3/4 */
  3520.         }
  3521.         if (len <= MINSPACE) {        /* Did we get it? */
  3522.             fprintf(stderr,"fgen can't malloc string space\n");
  3523.             return(-1);
  3524.         }
  3525.     ssplen = len;
  3526.     }
  3527. #endif /* DYNAMIC */
  3528.  
  3529.     freeptr = sspace;                   /* This is where matches are copied. */
  3530.     resptr = resarry;            /* Static copies of these so */
  3531.     remlen = len;                       /* recursive calls can alter them. */
  3532.     debug(F101,"initspace ssplen","",ssplen);
  3533.     return(0);
  3534. }
  3535.  
  3536. /*
  3537.   Z S E T F I L  --  Query or change the size of file list buffers.
  3538.  
  3539.   fc = 1: Change current string space to n, return new size.
  3540.   fc = 2: Return current string space size.
  3541.   fc = 3: Change current maxnames to n, return new maxnames.
  3542.   fc = 4: Return current maxnames.
  3543.   Returns < 0 on error.
  3544. */
  3545. int
  3546. zsetfil(n, fc) int n, fc; {
  3547. #ifdef DYNAMIC
  3548.     switch (fc) {
  3549.       case 1:                /* Stringspace */
  3550.     if (sspace) {
  3551.         free(sspace);
  3552.         sspace = NULL;
  3553.     }
  3554.     if (initspace(mtchs,n) < 0)
  3555.       return(-1);
  3556.       case 2:                /* Fall thru deliberately */
  3557.     return(ssplen);
  3558.       case 3:                /* Listsize */
  3559.     if (mtchs) {
  3560.         free((char *)mtchs);
  3561.         mtchs = NULL;
  3562.     }
  3563.     mtchs = (char **)malloc(n * sizeof(char *));
  3564.     if (!mtchs)
  3565.       return(-1);
  3566.     maxnames = n;
  3567.       case 4:                /* Fall thru deliberately */
  3568.     return(maxnames);
  3569.     }
  3570. #endif /* DYNAMIC */
  3571.     return(-1);
  3572. }
  3573.  
  3574.  
  3575.  
  3576. #ifndef NONZXPAND
  3577. #ifndef pdp11
  3578. static
  3579. #endif /* pdp11 */
  3580. #endif /* NONZXPAND */
  3581. int
  3582. zxpand(fnarg) char *fnarg; {
  3583.     extern int diractive;
  3584.     char fnbuf[CKMAXPATH+8], * fn, * p;
  3585.  
  3586. #ifdef DTILDE                           /* Built with tilde-expansion? */
  3587.     char *tnam;
  3588. #endif /* DTILDE */
  3589.     int x;
  3590.     int haveonedir = 0;
  3591.  
  3592.     if (!fnarg) {                       /* If no argument provided */
  3593.     nxpand = fcount = 0;
  3594.     return(0);            /* Return zero files found */
  3595.     }
  3596.     debug(F110,"zxpand entry",fnarg,0);
  3597.     debug(F101,"zxpand xdironly","",xdironly);
  3598.     debug(F101,"zxpand xfilonly","",xfilonly);
  3599.  
  3600.     if (!*fnarg) {            /* If no argument provided */
  3601.     nxpand = fcount = 0;
  3602.     return(0);            /* Return zero files found */
  3603.     }
  3604.  
  3605. #ifdef CKROOT
  3606.     debug(F111,"zxpand setroot",ckroot,ckrootset);
  3607.     if (ckrootset) if (!zinroot(fnarg)) {
  3608.     debug(F110,"zxpand setroot violation",fnarg,0);
  3609.     nxpand = fcount = 0;
  3610.     return(0);
  3611.     }
  3612. #endif /* CKROOT */
  3613.  
  3614. #ifdef COMMENT
  3615. /*
  3616.   This would have been perfect, except it makes us return fully qualified
  3617.   pathnames for all files.
  3618. */
  3619.     zfnqfp(fnarg,CKMAXPATH,fnbuf);
  3620.     debug(F110,"zxpand zfnqfp",fnbuf,0);
  3621.     s = zgtdir();
  3622.     debug(F110,"zxpand zgtdir",s,0);
  3623.     p = fnbuf;
  3624.     while (*p && *s)                    /* Make it relative */
  3625.       if (*s++ != *p++)
  3626.         break;
  3627.     fn = (*s) ? fnbuf : p;
  3628.     debug(F110,"zxpand fn 0",fn,0);
  3629.     if (!*fn) {
  3630.         fn = fnbuf;
  3631.         fnbuf[0] = '*';
  3632.         fnbuf[1] = '\0';
  3633.     }
  3634.     debug(F110,"zxpand fn 0.5",fn,0);
  3635. #else
  3636. #ifdef DTILDE                           /* Built with tilde-expansion? */
  3637.     if (*fnarg == '~') {                /* Starts with tilde? */
  3638.         tnam = tilde_expand(fnarg);     /* Try to expand it. */
  3639.         ckstrncpy(fnbuf,tnam,CKMAXPATH);
  3640.     } else
  3641. #endif /* DTILDE */
  3642.       ckstrncpy(fnbuf,fnarg,CKMAXPATH);
  3643.     fn = fnbuf;                         /* Point to what we'll work with */
  3644. #endif /* COMMENT */
  3645.     debug(F110,"zxpand fn 1",fn,0);
  3646.  
  3647.     if (!*fn)                           /* But make sure something is there */
  3648.       return(0);
  3649.  
  3650.     p = fn + (int)strlen(fn) - 1;
  3651.     if (*p == '/') {                    /* If last char = / it must be a dir */
  3652.     if (!xfilonly && !iswild(p)) haveonedir++;
  3653.         ckstrncat(fn, "*", CKMAXPATH+8); /* so append '*' */
  3654.     } else if (p > fn) {                /* If ends in "/." */
  3655.         if (*(p-1) == '/' && *p == '.') /* change '.' to '*' */
  3656.           *p = '*';
  3657.     } else if (p == fn) {               /* If it's '.' alone */
  3658.         if (*p == '.')                  /* change '.' to '*' */
  3659.           *p = '*';
  3660.     }
  3661.     debug(F110,"zxpand fn 2",fn,0);
  3662.     x = isdir(fn);                      /* Is it a directory? */
  3663.     debug(F111,"zxpand isdir 1",fn,x);
  3664.     if (x) {                            /* If so, make it into a wildcard */
  3665.     if (!xfilonly && !iswild(p))
  3666.       haveonedir++;
  3667.         if ((x = strlen(fn)) > 0) {
  3668.             if (!ISDIRSEP(fn[x-1]))
  3669.               fn[x++] = DIRSEP;
  3670.             fn[x++] = '*';
  3671.             fn[x] = '\0';
  3672.         }
  3673.     }
  3674.     debug(F111,"zxpand fn 3 haveonedir",fn,haveonedir);
  3675. /*
  3676.   The following allows us to parse a single directory name without opening
  3677.   the directory and looking at its contents.  The diractive flag is a horrible
  3678.   hack (especially since DIR /NORECURSIVE turns it off), but otherwise we'd
  3679.   have to change the API.
  3680. */
  3681.     debug(F111,"zxpand fn 3 diractive",fn,diractive);
  3682.     if (!diractive && haveonedir) {
  3683.     fcount = 0;
  3684.     if (!mtchs) {
  3685.         mtchs = (char **)malloc(maxnames * sizeof(*mtchs));
  3686.         if (!mtchs)
  3687.           return(nxpand = fcount);
  3688.     }
  3689.     fcount = 1;
  3690.     debug(F110,"zxpand haveonedir A1",fnarg,0);
  3691.     initspace(mtchs,ssplen);
  3692.     addresult(fnarg,1);
  3693.     if (numfnd < 0) return(-1);
  3694.     mtchptr = mtchs;        /* Save pointer for next. */
  3695.     debug(F111,"zxpand haveonedir A2",*mtchptr,numfnd);
  3696.     return(nxpand = fcount);
  3697.     }
  3698.  
  3699. #ifndef NOPUSH
  3700.     if (!nopush && wildxpand)           /* Who is expanding wildcards? */
  3701.       fcount = (mtchs == NULL &&        /* Shell */
  3702.                 (mtchs = (char **)malloc(maxnames * sizeof(*mtchs))) == NULL)
  3703.         ? 0
  3704.           :  shxpand(fn,mtchs,maxnames);
  3705.     else
  3706. #endif /* NOPUSH */
  3707.       fcount = (mtchs == NULL &&        /* Kermit */
  3708.                 (mtchs = (char **)malloc(maxnames * sizeof(*mtchs))) == NULL)
  3709.         ? 0
  3710.           : fgen(fn,mtchs,maxnames);      /* Look up the file. */
  3711.  
  3712.     if (fcount == 0 && haveonedir) {
  3713.     fcount = 1;
  3714.     debug(F110,"zxpand haveonedir B",fnarg,0);
  3715.     addresult(fnarg,1);
  3716.     if (numfnd < 0) return(-1);
  3717.     }
  3718.     mtchptr = mtchs;                    /* Save pointer for next. */
  3719.     nxpand = fcount;
  3720.  
  3721. #ifdef DEBUG
  3722.     if (deblog) {
  3723.         if (fcount > 1)
  3724.           debug(F111,"zxpand ok",mtchs[0],fcount);
  3725.         else
  3726.           debug(F101,"zxpand fcount","",fcount);
  3727.     }
  3728. #endif /* DEBUG */
  3729.     return(fcount);
  3730. }
  3731.  
  3732. #ifndef NONZXPAND
  3733. /*  N Z X P A N D  --  Expand a file list, with options.  */
  3734. /*
  3735.   Call with:
  3736.    s = pointer to filename or pattern.
  3737.    flags = option bits:
  3738.  
  3739.      flags & ZX_FILONLY   Match regular files
  3740.      flags & ZX_DIRONLY   Match directories
  3741.      flags & ZX_RECURSE   Descend through directory tree
  3742.      flags & ZX_MATCHDOT  Match "dot files"
  3743.      flags & ZX_NOBACKUP  Don't match "backup files"
  3744.      flags & ZX_NOLINKS   Don't follow symlinks.
  3745.  
  3746.    Returns the number of files that match s, with data structures set up
  3747.    so that first file (if any) will be returned by the next znext() call.
  3748. */
  3749. int
  3750. nzxpand(s,flags) char * s; int flags; {
  3751.     char * p;
  3752.     int x;
  3753.  
  3754.     debug(F111,"nzxpand",s,flags);
  3755.     x = flags & (ZX_DIRONLY|ZX_FILONLY);
  3756.     xdironly = (x == ZX_DIRONLY);
  3757.     xfilonly = (x == ZX_FILONLY);
  3758.     if (xdironly && xfilonly) {
  3759.         xdironly = 0;
  3760.         xfilonly = 0;
  3761.     }
  3762.     xmatchdot  = (flags & ZX_MATCHDOT);
  3763.     debug(F111,"nzxpand xmatchdot 1",s,xmatchdot);
  3764.     /* If xmatchdot not set by caller but pattern implies it, set it anyway */
  3765.     if (!xmatchdot && ((p = ckstrchr(s,'.')))) {
  3766.     if (p == s && p[1] != '/') {
  3767.         xmatchdot = 1;
  3768.         debug(F111,"nzxpand xmatchdot 2",s,xmatchdot);
  3769.     } else if (p > s) {
  3770.         xmatchdot = (*(p-1) == ',') || (*(p-1) == '{') || (*(p-1) == '/');
  3771.         debug(F111,"nzxpand xmatchdot 3",s,xmatchdot);
  3772.     }
  3773.     }
  3774.     xrecursive = (flags & ZX_RECURSE);
  3775.     xnobackup  = (flags & ZX_NOBACKUP);
  3776.     xnolinks   = (flags & ZX_NOLINKS);
  3777.  
  3778. #ifdef DEBUG
  3779.     if (deblog) {
  3780.     debug(F101,"nzxpand xdironly","",xdironly);
  3781.     debug(F101,"nzxpand xfilonly","",xfilonly);
  3782.     debug(F101,"nzxpand xmatchdot","",xmatchdot);
  3783.     debug(F101,"nzxpand xrecursive","",xrecursive);
  3784.     debug(F101,"nzxpand xnobackup","",xnobackup);
  3785.     debug(F101,"nzxpand xnolinks","",xnolinks);
  3786.     }
  3787. #endif /* DEBUG */
  3788.  
  3789.     x = zxpand(s);
  3790.     if (x > 1)
  3791.       sh_sort(mtchs,NULL,x,0,0,1);    /* Alphabetize the list */
  3792.     xdironly = 0;
  3793.     xfilonly = 0;
  3794.     xmatchdot = 0;
  3795.     xrecursive = 0;
  3796.     xnobackup = 0;
  3797.     xnolinks = 0;
  3798.     return(x);
  3799. }
  3800. #endif /* NONZXPAND */
  3801.  
  3802. #ifndef NOZXREWIND
  3803. /*  Z X R E W I N D  --  Rewinds the zxpand() list */
  3804.  
  3805. int
  3806. zxrewind() {
  3807.     /* if (!mtchs) return(-1); */
  3808.     fcount = nxpand;
  3809.     mtchptr = mtchs;
  3810.     return(nxpand);
  3811. }
  3812. #endif /* NOZXREWIND */
  3813.  
  3814. /*  Z N E X T  --  Get name of next file from list created by zxpand(). */
  3815. /*
  3816.   Returns >0 if there's another file, with its name copied into the arg string,
  3817.   or 0 if no more files in list.
  3818. */
  3819. int
  3820. znext(fn) char *fn; {
  3821.     if (fcount-- > 0) {
  3822.         ckstrncpy(fn,*mtchptr++,CKMAXPATH);
  3823.     } else {
  3824.         fn[0] = '\0';
  3825.     }
  3826. #ifndef COMMENT
  3827.     debug(F111,"znext",fn,fcount+1);
  3828.     return(fcount+1);
  3829. #else
  3830.     debug(F111,"znext",fn,fcount);      /* Return 0 if no filename to return */
  3831.     return(fcount);
  3832. #endif /* COMMENT */
  3833. }
  3834.  
  3835. /*  Z C H K S P A  --  Check if there is enough space to store the file  */
  3836.  
  3837. /*
  3838.  Call with file specification f, size n in bytes.
  3839.  Returns -1 on error, 0 if not enough space, 1 if enough space.
  3840. */
  3841. /*ARGSUSED*/
  3842. int
  3843. #ifdef CK_ANSIC
  3844. zchkspa(char *f, CK_OFF_T n)
  3845. #else
  3846. zchkspa(f,n) char *f; CK_OFF_T n;
  3847. #endif /* CK_ANSIC */
  3848. /* zchkspa() */ {
  3849.     /* In UNIX there is no good (and portable) way. */
  3850.     return(1);                          /* Always say OK. */
  3851. }
  3852.  
  3853. #ifdef COMMENT                /* (not used) */
  3854.  
  3855. /*  I S B A C K U P  --  Tells if given file has a backup suffix  */
  3856. /*
  3857.    Returns:
  3858.    -1: Invalid argument
  3859.     0: File does not have a backup suffix
  3860.    >0: Backup suffix number
  3861. */
  3862. int
  3863. isbackup(fn) char * fn; {        /* Get backup suffix number */
  3864.     int i, j, k, x, state, flag;
  3865.  
  3866.     if (!fn)                /* Watch out for null pointers. */
  3867.       return(-1);
  3868.     if (!*fn)                /* And empty names. */
  3869.       return(-1);
  3870.  
  3871.     flag = state = 0;
  3872.     for (i = (int)strlen(fn) - 1; (!flag && (i > 0)); i--) {
  3873.     switch (state) {
  3874.       case 0:            /* State 0 - final char */
  3875.         if (fn[i] == '~')        /* Is tilde */
  3876.           state = 1;        /* Switch to next state */
  3877.         else            /* Otherwise */
  3878.           flag = 1;            /* Quit - no backup suffix. */
  3879.         break;
  3880.       case 1:            /* State 1 - digits */
  3881.         if (fn[i] == '~'  && fn[i-1] == '.') { /* Have suffix */
  3882.         return(atoi(&fn[i+1]));
  3883.         } else if (fn[i] >= '0' && fn[i] <= '9') { /* In number part */
  3884.         continue;        /* Keep going */
  3885.         } else {            /* Something else */
  3886.         flag = 1;        /* Not a backup suffix - quit. */
  3887.         }
  3888.         break;
  3889.     }
  3890.     }
  3891.     return(0);
  3892. }
  3893. #endif /* COMMENT */
  3894.  
  3895.  
  3896. /*  Z N E W N  --  Make a new name for the given file  */
  3897.  
  3898. /*
  3899.   Given the name, fn, of a file that already exists, this function builds a
  3900.   new name of the form "<oldname>.~<n>~", where <oldname> is argument name
  3901.   (fn), and <n> is a version number, one higher than any existing version
  3902.   number for that file, up to 99999.  This format is consistent with that used
  3903.   by GNU EMACS.  If the constructed name is too long for the system's maximum,
  3904.   enough characters are truncated from the end of <fn> to allow the version
  3905.   number to fit.  If no free version numbers exist between 1 and 99999, a
  3906.   version number of "xxxx" is used.  Returns a pointer to the new name in
  3907.   argument s.
  3908. */
  3909. #ifdef pdp11
  3910. #define ZNEWNBL 63                      /* Name buffer length */
  3911. #define ZNEWNMD 3                       /* Max digits for version number */
  3912. #else
  3913. #define ZNEWNBL CKMAXPATH
  3914. #define ZNEWNMD 4
  3915. #endif /* pdp11 */
  3916.  
  3917. #define MAXBUDIGITS 5
  3918.  
  3919. static char znewbuf[ZNEWNBL+12];
  3920.  
  3921. VOID
  3922. znewn(fn,s) char *fn, **s; {
  3923.     char * buf;                /* Pointer to buffer for new name */
  3924.     char * xp, * namepart = NULL;       /* Pointer to filename part */
  3925.     struct zfnfp * fnfp;                /* znfqfp() result struct pointer */
  3926.     int d = 0, t, fnlen, buflen;
  3927.     int n, i, k, flag, state;
  3928.     int max = MAXNAMLEN;                /* Maximum name length */
  3929.     char * dname = NULL;
  3930.  
  3931.     buf = znewbuf;
  3932.     *s = NULL;                          /* Initialize return value */
  3933.     if (!fn) fn = "";                   /* Check filename argument */
  3934.     i = strlen(fn);
  3935.  
  3936. /* If incoming file already has a backup suffix, remove it. */
  3937. /* Then we'll tack a new on later, which will be the highest for this file. */
  3938.  
  3939.     if (i <= max && i > 0 && fn[i-1] == '~') {
  3940.     char * p;
  3941.     i--;
  3942.     debug(F111,"znewn suffix removal",fn,i);
  3943.     if ((dname = (char *)malloc(i+1))) {
  3944.         ckstrncpy(dname,fn,i+1);
  3945.         p = dname;
  3946.         for (flag = state = 0; (!flag && (i > 0)); i--) {
  3947.         switch (state) {
  3948.           case 0:        /* State 0 - final char */
  3949.             if (p[i] == '~')    /* Is tilde */
  3950.               state = 1;    /* Switch to next state */
  3951.             else        /* Otherwise */
  3952.               flag = 1;        /* Quit - no backup suffix. */
  3953.             break;
  3954.           case 1:        /* State 1 - digits */
  3955.             if (p[i] == '~'  && p[i-1] == '.') { /* Have suffix */
  3956.             p[i-1] = NUL;    /* Trim it */
  3957.             fn = dname;
  3958.             debug(F111,"znewn suffix removal 2",fn,i);
  3959.             flag = 1;    /* done */
  3960.             } else if (p[i] >= '0' && p[i] <= '9') { /* Number part */
  3961.             continue;    /* Keep going */
  3962.             } else {        /* Something else */
  3963.             flag = 1;    /* Not a backup suffix - quit. */
  3964.             }
  3965.             break;
  3966.         }
  3967.         }
  3968.     }
  3969.     }
  3970.     if ((fnlen = strlen(fn)) < 1) {    /* Get length */
  3971.     if (dname) free(dname);
  3972.     return;
  3973.     }
  3974.     debug(F111,"znewn",fn,fnlen);
  3975.  
  3976.     debug(F101,"znewn max 1","",max);
  3977.     if (max < 14) max = 14;             /* Make max reasonable for any UNIX */
  3978.     if (max > ZNEWNBL) max = ZNEWNBL;
  3979.     debug(F101,"znewn max 2","",max);
  3980.  
  3981.     if ((fnfp = zfnqfp(fn, ZNEWNBL, buf))) { /* Get fully qualified name */
  3982.         namepart = fnfp->fname;         /* Isolate the filename */
  3983.         k = strlen(fn);                 /* Length of name part */
  3984.         debug(F111,"znewn namepart",namepart,k);
  3985.     } else {
  3986.     if (dname) free(dname);
  3987.     return;
  3988.     }
  3989.     buflen = fnfp->len;                 /* Length of fully qualified name */
  3990.     debug(F111,"znewn len",buf,buflen);
  3991.  
  3992.     if (k + MAXBUDIGITS + 3 < max) {    /* Backup name fits - no overflow */
  3993.     /* Make pattern for backup names */
  3994.         ckstrncpy(buf+buflen,".~*~",ZNEWNBL+12-buflen);
  3995.         n = nzxpand(buf,ZX_FILONLY);    /* Expand the pattern */
  3996.         debug(F111,"znewn A matches",buf,n);
  3997.         while (n-- > 0) {               /* Find any existing name.~n~ files */
  3998.             xp = *mtchptr++;            /* Point at matching name */
  3999.             t = atoi(xp+buflen+2);      /* Get number */
  4000.             if (t > d) d = t;           /* Save d = highest version number */
  4001.         }
  4002.         sprintf(buf+buflen,".~%d~",d+1); /* Yes, make "name.~<d+1>~" */
  4003.         debug(F110,"znewn A newname",buf,0);
  4004.     } else {                            /* Backup name would be too long */
  4005.         int xlen;                       /* So we have to eat back into it */
  4006.         int delta;
  4007.         char buf2[ZNEWNBL+12];
  4008.  
  4009.         delta = max - k;
  4010.         debug(F101,"znewn B delta","",delta);
  4011.  
  4012.         for (i = MAXBUDIGITS; i > 0; i--) { /* In this case the format of */
  4013.             ckstrncpy(buf2,buf,ZNEWNBL+12); /* the backup name depends on */
  4014.             xlen = buflen - i - 3 + delta;  /* how many digits are in the */
  4015.             ckstrncpy(buf2+xlen,".~*~",ZNEWNBL+12-xlen); /* backup number */
  4016.             n = nzxpand(buf2,ZX_FILONLY);
  4017.             debug(F111,"znewn B matches",buf2,n);
  4018.             if (n > 0)
  4019.               break;
  4020.         }
  4021.         while (n-- > 0) {               /* Find any existing name.~n~ files */
  4022.             xp = *mtchptr++;            /* Point at matching name */
  4023.             t = atoi(xp+xlen+2);        /* Get number */
  4024.             if (t > d) d = t;           /* Save d = highest version number */
  4025.         }
  4026.         if (d > 0)                      /* If the odometer turned over... */
  4027.           if ((d % 10) == 9)            /* back up one space. */
  4028.             xlen--;
  4029.         sprintf(buf2+xlen,".~%d~",d+1); /* This just fits */
  4030.         ckstrncpy(buf,buf2,ZNEWNBL+12);    /* (we could be more clever here...) */
  4031.         debug(F110,"znewn B new name",buf,0);
  4032.     }
  4033.     *s = buf;                           /* Point to new name */
  4034.     ck_znewn = d+1;                     /* Also make it available globally */
  4035.     if (dname) free(dname);
  4036.     return;
  4037. }
  4038.  
  4039. /*  Z R E N A M E  --  Rename a file  */
  4040. /*
  4041.    Call with old and new names.
  4042.    If new name is the name of a directory, the 'old' file is moved to
  4043.    that directory.
  4044.    Returns 0 on success, -1 on failure.
  4045. */
  4046. int
  4047. zrename(old,new) char *old, *new; {
  4048.     char *p, *s;
  4049.     int x;
  4050.  
  4051.     if (!old) old = "";
  4052.     if (!new) new = "";
  4053.     debug(F110,"zrename old",old,0);
  4054.     debug(F110,"zrename new",new,0);
  4055.     if (!*old) return(-1);
  4056.     if (!*new) return(-1);
  4057.  
  4058. #ifdef IKSD
  4059. #ifdef CK_LOGIN
  4060.     if (inserver && isguest)
  4061.       return(-1);
  4062. #endif /* CK_LOGIN */
  4063. #endif /* IKSD */
  4064.  
  4065. #ifdef CKROOT
  4066.     debug(F111,"zrename setroot",ckroot,ckrootset);
  4067.     if (ckrootset) {
  4068.     if (!zinroot(old)) {
  4069.         debug(F110,"zrename old: setroot violation",old,0);
  4070.         return(-1);
  4071.     }
  4072.     if (!zinroot(new)) {
  4073.         debug(F110,"zrename new: setroot violation",new,0);
  4074.         return(-1);
  4075.     }
  4076.     }
  4077. #endif /* CKROOT */
  4078.  
  4079.     p = NULL;
  4080.     s = new;
  4081.  
  4082.     if (isdir(new)) {
  4083.         char *q = NULL;
  4084.         x = strlen(new);
  4085.         if (!(p = malloc(strlen(new) + strlen(old) + 2)))
  4086.           return(-1);
  4087.         strcpy(p,new);                  /* (safe) Directory part */
  4088.         if (!ISDIRSEP(*(new+x-1)))      /* Separator, if needed */
  4089.           strcat(p,"/");        /* (safe) */
  4090.         zstrip(old,&q);                 /* Strip path part from old name */
  4091.         strcat(p,q);                    /* cat to new directory (safe) */
  4092.         s = p;
  4093.         debug(F110,"zrename dir",s,0);
  4094.     }
  4095. #ifdef DEBUG
  4096.     else debug(F110,"zrename no dir",s,0);
  4097. #endif /* DEBUG */
  4098.  
  4099. #ifdef IKSD
  4100.     if (inserver && (!ENABLED(en_del))) {
  4101.     if (zchki(s) > -1)        /* Destination file exists? */
  4102.       return(-1);
  4103.     }
  4104. #endif /* IKSD */
  4105.  
  4106.     x = -1;                             /* Return code. */
  4107. #ifdef RENAME
  4108. /* Atomic, preferred, uses a single system call, rename(), if available. */
  4109.     x = rename(old,s);
  4110.     debug(F111,"zrename rename()",old,x);
  4111.     if (x) x = -1;
  4112. #endif /* RENAME */
  4113.  
  4114.     /* If rename() failed or not available try link()/unlink() */
  4115.  
  4116.     if (x < 0) {
  4117.     if (zchko(old) > -1) {        /* Requires write access to orignal */
  4118.         x = link(old,s);
  4119.         debug(F111,"zrename link()",old,x);
  4120.         if (x > -1) {        /* Make a link with the new name. */
  4121.         x = unlink(old);
  4122.         debug(F111,"zrename unlink()",old,x);
  4123.         }
  4124.         /* If link/unlink failed copy and delete */
  4125.         if (x < 0) {
  4126.         x = zcopy(old,s);
  4127.         debug(F111,"zrename zcopy()",old,x);
  4128.         if (x > -1) {
  4129.             x = zdelet(old);
  4130.             debug(F111,"zrename zdelet()",old,x);
  4131.         }
  4132.         }
  4133.     }
  4134.     }
  4135.     fullname[0] = '\0';            /* Clear this out for next time. */
  4136.  
  4137. #ifdef CKSYSLOG
  4138.     if (ckxsyslog >= SYSLG_FC && ckxlogging) {
  4139.         zfnqfp(old,CKMAXPATH,fullname);
  4140.         tmp2[0] = '\0';
  4141.         zfnqfp(s,CKMAXPATH,tmp2);
  4142.         if (x > -1)
  4143.           syslog(LOG_INFO,"file[] %s: renamed to %s ok", fullname, tmp2);
  4144.         else
  4145.           syslog(LOG_INFO,"file[] %s: rename to %s failed (%m)",fullname,tmp2);
  4146.     }
  4147. #endif /* CKSYSLOG */
  4148.  
  4149.     if (p) free(p);
  4150.     return(x);
  4151. }
  4152.  
  4153. /*  Z C O P Y  --  Copy a single file. */
  4154. /*
  4155.   Call with source and destination names.
  4156.   If destination is a directory, the source file is
  4157.   copied to that directory with its original name.
  4158.   Returns:
  4159.    0 on success.
  4160.   <0 on failure:
  4161.   -2 = source file is not a regular file.
  4162.   -3 = source file not found.
  4163.   -4 = permission denied.
  4164.   -5 = source and destination are the same file.
  4165.   -6 = i/o error.
  4166.   -1 = other error.
  4167. */
  4168. int
  4169. zcopy(source,destination) char *source, *destination; {
  4170.     char *src, *dst;            /* Local pointers to filenames */
  4171.     int x, y, rc;                       /* Workers */
  4172.     int in = -1, out = -1;              /* i/o file descriptors */
  4173.     struct stat srcbuf;                 /* Source file info buffer */
  4174.     int perms;                          /* Output file permissions */
  4175.     char buf[1024];                     /* File copying buffer */
  4176.  
  4177.     if (!source) source = "";
  4178.     if (!destination) destination = "";
  4179.  
  4180.     debug(F110,"zcopy src arg",source,0);
  4181.     debug(F110,"zcopy dst arg",destination,0);
  4182.  
  4183.     if (!*source) return(-1);
  4184.     if (!*destination) return(-1);
  4185.  
  4186. #ifdef IKSD
  4187. #ifdef CK_LOGIN
  4188.     if (inserver && isguest)
  4189.       return(-4);
  4190. #endif /* CK_LOGIN */
  4191. #endif /* IKSD */
  4192.  
  4193. #ifdef CKROOT
  4194.     debug(F111,"zcopy setroot",ckroot,ckrootset);
  4195.     if (ckrootset) {
  4196.     if (!zinroot(source)) {
  4197.         debug(F110,"zcopy source: setroot violation",source,0);
  4198.         return(-1);
  4199.     }
  4200.     if (!zinroot(destination)) {
  4201.         debug(F110,"zcopy destination: setroot violation",destination,0);
  4202.         return(-1);
  4203.     }
  4204.     }
  4205. #endif /* CKROOT */
  4206.  
  4207.     src = source;
  4208.     dst = destination;
  4209.  
  4210.     if (stat(src,&srcbuf) == 0) {       /* Get source file info */
  4211.         struct stat dstbuf;             /* Destination file info buffer */
  4212.     debug(F101,"STAT","",6);
  4213.         if (stat(dst,&dstbuf) == 0) {
  4214.         debug(F101,"STAT","",7);
  4215.             if (srcbuf.st_dev == dstbuf.st_dev)
  4216.               if (srcbuf.st_ino == dstbuf.st_ino) {
  4217.                   debug(F100,"zcopy files identical: stat()","",0);
  4218.                   return(-5);
  4219.               }
  4220.         }
  4221.     } else {                            /* stat() failed... */
  4222.     debug(F101,"STAT","",8);
  4223.         debug(F111,"source file not found",src,errno);
  4224.         return(-3);
  4225.     }
  4226.     fullname[0] = '\0';                 /* Get full pathnames */
  4227.     if (zfnqfp(source,CKMAXPATH,fullname))
  4228.       src = fullname;
  4229.     debug(F110,"zcopy src",src,0);
  4230.     tmp2[0] = '\0';
  4231.     if (zfnqfp(destination,CKMAXPATH,tmp2))
  4232.       dst = tmp2;
  4233.     debug(F110,"zcopy dst 1",dst,0);
  4234.     if (!strcmp(src,dst)) {             /* Src and dst are same file? */
  4235.         debug(F100,"zcopy files identical: strcmp()","",0); /* This... */
  4236.         return(-5);                     /* should not happen. */
  4237.     }
  4238.     if (isdir(src)) {                   /* Source file is a directory? */
  4239.         debug(F110,"zcopy source is directory",src,0);
  4240.         return(-2);                     /* Fail */
  4241.     }
  4242.     if (isdir(dst)) {                   /* Destination is a directory? */
  4243.         char *q = NULL;                 /* Yes, add filename to it. */
  4244.         x = strlen(dst);
  4245.     if (x < 1) return(-1);
  4246.         if (!ISDIRSEP(*(dst+x-1))) {    /* Add separator if needed */
  4247.             tmp2[x++] = '/';
  4248.             tmp2[x] = '\0';
  4249.         }
  4250.     debug(F111,"zcopy dst 2",dst,x);
  4251.         zstrip(src,&q);                 /* Strip path part from old name */
  4252.         ckstrncpy(tmp2+x,q,CKMAXPATH-x); /* Concatenate it to new name */
  4253.     }
  4254.     debug(F110,"zcopy dst 3",dst,0);
  4255.  
  4256. #ifdef IKSD
  4257.     if (inserver && (!ENABLED(en_del))) {
  4258.     if (zchki(dst) > -1)        /* Destination file exists? */
  4259.       return(-4);
  4260.     }
  4261. #endif /* IKSD */
  4262.  
  4263.     perms = umask(0);                   /* Get user's umask */
  4264.     umask(perms);            /* Put it back! */
  4265.     perms ^= 0777;                      /* Flip the bits */
  4266.     perms &= 0666;                      /* Zero execute bits from umask */
  4267.     perms |= (srcbuf.st_mode & 0111);   /* OR in source file's execute bits */
  4268.     rc = -1;                            /* Default return code */
  4269.     errno = 0;                          /* Reset errno */
  4270.     in = open(src, O_RDONLY, 0);        /* Open source file */
  4271.     debug(F111,"zcopy open source",src,in);
  4272.     if (in > -1) {                      /* If open... */
  4273.     /* Open destination file */
  4274. #ifdef O_TRUNC
  4275.         out = open(dst, O_WRONLY|O_CREAT|O_TRUNC, perms);
  4276. #else
  4277.         out = open(dst, O_WRONLY|O_CREAT, perms);
  4278. #endif /* O_TRUNC */
  4279.         debug(F111,"zcopy open dest",dst,out);
  4280.         if (out > -1) {                 /* If open... */
  4281.             while ((x = read(in,buf,1024)) > 0) { /* Copy in 1K blocks */
  4282.                 y = write(out,buf,x);
  4283.                 if (y < 0) {            /* On write failure */
  4284.                     x = -1;
  4285.                     rc = -6;            /* Indicate i/o error */
  4286.                     break;
  4287.                 }
  4288.             }
  4289.             debug(F101,"zcopy final read","",x);
  4290.             debug(F101,"zcopy errno","",errno);
  4291.             rc = (x == 0) ? 0 : -6;     /* In case of read failure */
  4292.         }
  4293.     }
  4294.     if (in > -1) close(in);             /* Close files */
  4295.     if (out > -1) close(out);
  4296.     if (rc == -1) {                     /* Set return code */
  4297.         switch (errno) {
  4298.           case ENOENT: rc = -3; break;
  4299.           case EACCES: rc = -4; break;
  4300.           case EIO:    rc = -6;
  4301.         }
  4302.     }
  4303.  
  4304. #ifdef CKSYSLOG
  4305.     if (rc > -1 && ckxsyslog >= SYSLG_FC && ckxlogging) {
  4306.         if (rc)
  4307.           syslog(LOG_INFO,"file[] %s: copy to %s failed (%m)", fullname, tmp2);
  4308.         else
  4309.           syslog(LOG_INFO,"file[] %s: copy to %s ok", fullname, tmp2);
  4310.     }
  4311. #endif /* CKSYSLOG */
  4312.  
  4313.     return(rc);
  4314. }
  4315.  
  4316. /*  Z S A T T R */
  4317. /*
  4318.  Fills in a Kermit file attribute structure for the file which is to be sent.
  4319.  Returns 0 on success with the structure filled in, or -1 on failure.
  4320.  If any string member is null, then it should be ignored.
  4321.  If any numeric member is -1, then it should be ignored.
  4322. */
  4323. #ifdef CK_PERMS
  4324.  
  4325. #ifdef CK_GPERMS
  4326. #undef CK_GPERMS
  4327. #endif /* CK_GPERMS */
  4328.  
  4329. #ifdef UNIX
  4330. #ifndef S_IRUSR
  4331. #define S_IRUSR 0400
  4332. #endif /* S_IRUSR */
  4333. #ifndef S_IWUSR
  4334. #define S_IXUSR 0200
  4335. #endif /* S_IWUSR */
  4336. #ifndef S_IXUSR
  4337. #define S_IXUSR 0100
  4338. #endif /* S_IXUSR */
  4339. #endif /* UNIX */
  4340.  
  4341. #ifdef S_IRUSR
  4342. #ifdef S_IWUSR
  4343. #ifdef S_IXUSR
  4344. #define CK_GPERMS
  4345. #endif /* S_IXUSR */
  4346. #endif /* S_IWUSR */
  4347. #endif /* S_IRUSR */
  4348.  
  4349. static char gperms[2];
  4350.  
  4351. #endif /* CK_GPERMS */
  4352.  
  4353. static char lperms[24];
  4354.  
  4355. #ifdef CK_PERMS
  4356. static char xlperms[24];
  4357.  
  4358. /*  Z S E T P E R M  --  Set permissions of a file  */
  4359.  
  4360. int
  4361. zsetperm(f,code) char * f; int code; {
  4362.     int x;
  4363. #ifdef CK_SCO32V4
  4364.     mode_t mask;
  4365. #else
  4366.     int mask;
  4367. #endif /* CK_SCO32V4 */
  4368.     mask = code;
  4369.     if (inserver && guest) {
  4370.     debug(F110,"zsetperm guest",f,0);
  4371.     return(0);
  4372.     }
  4373.     x = chmod(f,mask);
  4374.     if (x < 0) {
  4375.     debug(F111,"zsetperm error",f,errno);
  4376.     return(0);
  4377.     }
  4378.     debug(F111,"zsetperm ok",f,mask);
  4379.     return(1);
  4380. }
  4381.  
  4382. /*  Z G P E R M  --  Get permissions of a file as an octal string  */
  4383.  
  4384. char *
  4385. zgperm(f) char *f; {
  4386.     extern int diractive;
  4387.     int x; char *s = (char *)xlperms;
  4388.     struct stat buf;
  4389.     debug(F110,"zgperm",f,0);
  4390.     if (!f) return("----------");
  4391.     if (!*f) return("----------");
  4392.  
  4393. #ifdef CKROOT
  4394.     debug(F111,"zgperm setroot",ckroot,ckrootset);
  4395.     if (ckrootset) if (!zinroot(f)) {
  4396.     debug(F110,"zgperm setroot violation",f,0);
  4397.     return("----------");
  4398.     }
  4399. #endif /* CKROOT */
  4400.  
  4401. #ifdef USE_LSTAT
  4402.     if (diractive)
  4403.       x = lstat(f,&buf);
  4404.     else
  4405. #endif /* USE_LSTAT */
  4406.       x = stat(f,&buf);
  4407.     debug(F101,"STAT","",9);
  4408.     if (x < 0)
  4409.       return("----------");
  4410.     sprintf(s,"%o",buf.st_mode);
  4411.     debug(F110,"zgperm",s,0);
  4412.     return(s);
  4413. }
  4414.  
  4415. /* Like zgperm() but returns permissions in "ls -l" string format */
  4416.  
  4417. static char xsperms[24];
  4418.  
  4419. char *
  4420. ziperm(f) char * f; {
  4421.     extern int diractive;
  4422.     int x; char *s = (char *)xsperms;
  4423.     struct stat buf;
  4424.     unsigned int perms = 0;
  4425.  
  4426.     debug(F110,"ziperm",f,0);
  4427.  
  4428.     if (!f) return(NULL);
  4429.     if (!*f) return(NULL);
  4430.  
  4431.     if (diractive && zgfs_mode != 0) {
  4432.     perms = zgfs_mode;        /* zgetfs() already got them */
  4433.     } else {
  4434. #ifdef USE_LSTAT
  4435.     if (diractive)
  4436.       x = lstat(f,&buf);
  4437.     else
  4438. #endif /* USE_LSTAT */
  4439.       x = stat(f,&buf);
  4440.     debug(F101,"STAT","",10);
  4441.     if (x < 0)
  4442.       return("----------");
  4443.     perms = buf.st_mode;
  4444.     }
  4445.     switch (perms & S_IFMT) {
  4446.       case S_IFDIR:
  4447.         *s++ = 'd';
  4448.         break;
  4449.       case S_IFCHR:                     /* Character special */
  4450.         *s++ = 'c';
  4451.         break;
  4452.       case S_IFBLK:                     /* Block special */
  4453.         *s++ = 'b';
  4454.         break;
  4455.       case S_IFREG:                     /* Regular */
  4456.         *s++ = '-';
  4457.         break;
  4458. #ifdef S_IFLNK
  4459.       case S_IFLNK:                     /* Symbolic link */
  4460.         *s++ = 'l';
  4461.         break;
  4462. #endif /* S_IFLNK */
  4463. #ifdef S_IFSOCK
  4464.       case S_IFSOCK:                    /* Socket */
  4465.         *s++ = 's';
  4466.         break;
  4467. #endif /* S_IFSOCK */
  4468. #ifdef S_IFIFO
  4469. #ifndef Plan9
  4470. #ifndef COHERENT
  4471.       case S_IFIFO:                     /* FIFO */
  4472.         *s++ = 'p';
  4473.         break;
  4474. #endif /* COHERENT */
  4475. #endif /* Plan9 */
  4476. #endif /* S_IFIFO */
  4477. #ifdef S_IFWHT
  4478.       case S_IFWHT:                     /* Whiteout */
  4479.         *s++ = 'w';
  4480.         break;
  4481. #endif /* S_IFWHT */
  4482.       default:                          /* Unknown */
  4483.         *s++ = '?';
  4484.         break;
  4485.     }
  4486.     if (perms & S_IRUSR)          /* Owner's permissions */
  4487.       *s++ = 'r';
  4488.     else
  4489.       *s++ = '-';
  4490.     if (perms & S_IWUSR)
  4491.       *s++ = 'w';
  4492.     else
  4493.       *s++ = '-';
  4494.     switch (perms & (S_IXUSR | S_ISUID)) {
  4495.       case 0:
  4496.         *s++ = '-';
  4497.         break;
  4498.       case S_IXUSR:
  4499.         *s++ = 'x';
  4500.         break;
  4501.       case S_ISUID:
  4502.         *s++ = 'S';
  4503.         break;
  4504.       case S_IXUSR | S_ISUID:
  4505.         *s++ = 's';
  4506.         break;
  4507.     }
  4508.     if (perms & S_IRGRP)          /* Group permissions */
  4509.       *s++ = 'r';
  4510.     else
  4511.       *s++ = '-';
  4512.     if (perms & S_IWGRP)
  4513.       *s++ = 'w';
  4514.     else
  4515.       *s++ = '-';
  4516.     switch (perms & (S_IXGRP | S_ISGID)) {
  4517.       case 0:
  4518.         *s++ = '-';
  4519.         break;
  4520.       case S_IXGRP:
  4521.         *s++ = 'x';
  4522.         break;
  4523.       case S_ISGID:
  4524.         *s++ = 'S';
  4525.         break;
  4526.       case S_IXGRP | S_ISGID:
  4527.         *s++ = 's';
  4528.         break;
  4529.     }
  4530.     if (perms & S_IROTH)          /* World permissions */
  4531.       *s++ = 'r';
  4532.     else
  4533.       *s++ = '-';
  4534.     if (perms & S_IWOTH)
  4535.       *s++ = 'w';
  4536.     else
  4537.       *s++ = '-';
  4538.     switch (
  4539. #ifdef Plan9
  4540.             perms & (S_IXOTH)
  4541. #else
  4542.             perms & (S_IXOTH | S_ISVTX)
  4543. #endif
  4544.             ) {
  4545.       case 0:
  4546.         *s++ = '-';
  4547.         break;
  4548.       case S_IXOTH:
  4549.         *s++ = 'x';
  4550.         break;
  4551. #ifndef Plan9
  4552.       case S_ISVTX:
  4553.         *s++ = 'T';
  4554.         break;
  4555.       case S_IXOTH | S_ISVTX:
  4556.         *s++ = 't';
  4557.         break;
  4558. #endif /* Plan9 */
  4559.     }
  4560.     *s = '\0';
  4561.     debug(F110,"ziperm",xsperms,0);
  4562.     return((char *)xsperms);
  4563. }
  4564.  
  4565. #else
  4566.  
  4567. char *
  4568. zgperm(f) char *f; {
  4569.     return("----------");
  4570. }
  4571. char *
  4572. ziperms(f) char *f; {
  4573.     return("----------");
  4574. }
  4575. #endif /* CK_PERMS */
  4576.  
  4577. int
  4578. zsattr(xx) struct zattr *xx; {
  4579.     CK_OFF_T k; int x;
  4580.     struct stat buf;
  4581.  
  4582.     k = iflen % 1024;            /* File length in K */
  4583.     if (k) k = 1L;
  4584.     xx->lengthk = (iflen / 1024) + k;
  4585.     xx->type.len = 0;                   /* File type can't be filled in here */
  4586.     xx->type.val = "";
  4587.     if (*nambuf) {
  4588.         xx->date.val = zfcdat(nambuf);  /* File creation date */
  4589.         xx->date.len = (int)strlen(xx->date.val);
  4590.     } else {
  4591.         xx->date.len = 0;
  4592.         xx->date.val = "";
  4593.     }
  4594.     xx->creator.len = 0;                /* File creator */
  4595.     xx->creator.val = "";
  4596.     xx->account.len = 0;                /* File account */
  4597.     xx->account.val = "";
  4598.     xx->area.len = 0;                   /* File area */
  4599.     xx->area.val = "";
  4600.     xx->password.len = 0;               /* Area password */
  4601.     xx->password.val = "";
  4602.     xx->blksize = -1L;                  /* File blocksize */
  4603.     xx->xaccess.len = 0;                /* File access */
  4604.     xx->xaccess.val = "";
  4605.     xx->encoding.len = 0;               /* Transfer syntax */
  4606.     xx->encoding.val = 0;
  4607.     xx->disp.len = 0;                   /* Disposition upon arrival */
  4608.     xx->disp.val = "";
  4609.     xx->lprotect.len = 0;               /* Local protection */
  4610.     xx->lprotect.val = "";
  4611.     xx->gprotect.len = 0;               /* Generic protection */
  4612.     xx->gprotect.val = "";
  4613.     x = -1;
  4614.     if (*nambuf) x = stat(nambuf,&buf);
  4615.     debug(F101,"STAT","",11);
  4616.     if (x >= 0) {
  4617.         debug(F111,"zsattr buf.st_mode & 0777",nambuf,buf.st_mode & 0777);
  4618.         /* UNIX filemode as an octal string without filetype bits */
  4619.         sprintf(lperms,"%o",buf.st_mode & 0777);
  4620.         xx->lprotect.len = (int)strlen(lperms);
  4621.         xx->lprotect.val = (char *)lperms;
  4622.         x = 0;
  4623. #ifdef CK_GPERMS
  4624.         /* Generic permissions only if we have stat.h symbols defined */
  4625.         if (buf.st_mode & S_IRUSR) x |= 1;      /* Read */
  4626.         if (buf.st_mode & S_IWUSR) x |= (2+16); /* Write and Delete */
  4627.         if (buf.st_mode & S_IXUSR) x |= 4;      /* Execute */
  4628.         gperms[0] = tochar(x);
  4629.         gperms[1] = NUL;
  4630.         xx->gprotect.len = 1;
  4631.         xx->gprotect.val = (char *)gperms;
  4632. #endif /* CK_GPERMS */
  4633.     }
  4634.     debug(F111,"zsattr lperms",xx->lprotect.val,xx->lprotect.len);
  4635.     debug(F111,"zsattr gperms",xx->gprotect.val,xx->gprotect.len);
  4636.     xx->systemid.val = "U1";            /* U1 = UNIX */
  4637.     xx->systemid.len = 2;               /* System ID */
  4638.     xx->recfm.len = 0;                  /* Record format */
  4639.     xx->recfm.val = "";
  4640.     xx->sysparam.len = 0;               /* System-dependent parameters */
  4641.     xx->sysparam.val = "";
  4642.     xx->length = iflen;                 /* Length */
  4643.     return(0);
  4644. }
  4645.  
  4646. /* Z F C D A T  --  Get file creation date */
  4647. /*
  4648.   Call with pointer to filename.
  4649.   On success, returns pointer to modification date in yyyymmdd hh:mm:ss format.
  4650.   On failure, returns pointer to null string.
  4651. */
  4652. static char datbuf[40];
  4653.  
  4654. char *
  4655. #ifdef CK_ANSIC
  4656. zdtstr(time_t timearg)
  4657. #else
  4658. zdtstr(timearg) time_t timearg;
  4659. #endif /* CK_ANSIC */
  4660. /* zdtstr */ {
  4661. #ifndef TIMESTAMP
  4662.     return("");
  4663. #else
  4664.     struct tm * time_stamp;
  4665.     struct tm * localtime();
  4666.     int yy, ss;
  4667.  
  4668.     debug(F101,"zdtstr timearg","",timearg);
  4669.     if (timearg < 0)
  4670.       return("");
  4671.     time_stamp = localtime(&(timearg));
  4672.     if (!time_stamp) {
  4673.         debug(F100,"localtime returns null","",0);
  4674.         return("");
  4675.     }
  4676. /*
  4677.   We assume that tm_year is ALWAYS years since 1900.
  4678.   Any platform where this is not the case will have problems
  4679.   starting in 2000.
  4680. */
  4681.     yy = time_stamp->tm_year;           /* Year - 1900 */
  4682.     debug(F101,"zdtstr tm_year","",time_stamp->tm_year);
  4683.     if (yy > 1000) {
  4684.         debug(F101,"zstrdt YEAR-2000 ALERT 1: localtime year","",yy);
  4685.     }
  4686.     yy += 1900;
  4687.     debug(F101,"zdatstr year","",yy);
  4688.  
  4689.     if (time_stamp->tm_mon  < 0 || time_stamp->tm_mon  > 11)
  4690.       return("");
  4691.     if (time_stamp->tm_mday < 0 || time_stamp->tm_mday > 31)
  4692.       return("");
  4693.     if (time_stamp->tm_hour < 0 || time_stamp->tm_hour > 23)
  4694.       return("");
  4695.     if (time_stamp->tm_min  < 0 || time_stamp->tm_min  > 59)
  4696.       return("");
  4697.     ss = time_stamp->tm_sec;            /* Seconds */
  4698.     if (ss < 0 || ss  > 59)             /* Some systems give a BIG number */
  4699.       ss = 0;
  4700.     sprintf(datbuf,
  4701. #ifdef pdp11
  4702. /* For some reason, 2.1x BSD sprintf gets the last field wrong. */
  4703.             "%04d%02d%02d %02d:%02d:00",
  4704. #else
  4705.             "%04d%02d%02d %02d:%02d:%02d",
  4706. #endif /* pdp11 */
  4707.             yy,
  4708.             time_stamp->tm_mon + 1,
  4709.             time_stamp->tm_mday,
  4710.             time_stamp->tm_hour,
  4711.             time_stamp->tm_min
  4712. #ifndef pdp11
  4713.             , ss
  4714. #endif /* pdp11 */
  4715.             );
  4716.     yy = (int)strlen(datbuf);
  4717.     debug(F111,"zdatstr",datbuf,yy);
  4718.     if (yy > 17) datbuf[17] = '\0';
  4719.     return(datbuf);
  4720. #endif /* TIMESTAMP */
  4721. }
  4722.  
  4723. char *
  4724. zfcdat(name) char *name; {
  4725. #ifdef TIMESTAMP
  4726.     struct stat buffer;
  4727.     extern int diractive;
  4728.     unsigned int mtime;
  4729.     int x;
  4730.     char * s;
  4731.  
  4732.     if (!name)
  4733.       return("");
  4734.     s = name;
  4735.     if (!*s)
  4736.       return("");
  4737.  
  4738. #ifdef CKROOT
  4739.     debug(F111,"zfcdat setroot",ckroot,ckrootset);
  4740.     if (ckrootset) if (!zinroot(name)) {
  4741.     debug(F110,"zfcdat setroot violation",name,0);
  4742.     return("");
  4743.     }
  4744. #endif /* CKROOT */
  4745.  
  4746. #ifdef DTILDE
  4747.     if (*s == '~') {
  4748.         s = tilde_expand(s);
  4749.         if (!s) s = "";
  4750.         if (!*s) s = name;
  4751.     }
  4752. #endif /* DTILDE */
  4753.  
  4754.     datbuf[0] = '\0';
  4755.     x = 0;
  4756.     debug(F111,"zfcdat",s,diractive);
  4757.  
  4758.     if (diractive && zgfs_mtime) {
  4759.     mtime = zgfs_mtime;
  4760.     } else {
  4761. #ifdef USE_LSTAT
  4762.     if (diractive) {
  4763.         x = lstat(s,&buffer);
  4764.         debug(F101,"STAT","",12);
  4765.         debug(F101,"zfcdat lstat","",x);
  4766.     } else {
  4767. #endif /* USE_LSTAT */
  4768.         x = stat(s,&buffer);
  4769.         debug(F101,"STAT","",13);
  4770.         debug(F101,"zfcdat stat","",x);
  4771. #ifdef USE_LSTAT
  4772.     }
  4773. #endif /* USE_LSTAT */
  4774.     if (x != 0) {
  4775. #ifdef USE_LSTAT
  4776.         debug(F111,"zfcdat stat failed",s,errno);
  4777. #else
  4778.         debug(F111,"zfcdat lstat failed",s,errno);
  4779. #endif /* USE_LSTAT */
  4780.         return("");
  4781.     }
  4782.     debug(F101,"zfcdat buffer.st_mtime","",buffer.st_mtime);
  4783.     mtime = buffer.st_mtime;
  4784.     }
  4785.     return(zdtstr(mtime));
  4786. #else
  4787.     return("");
  4788. #endif /* TIMESTAMP */
  4789. }
  4790.  
  4791. #ifndef NOTIMESTAMP
  4792.  
  4793. /* Z S T R D T  --  Converts local date string to internal representation */
  4794. /*
  4795.   In our case (UNIX) this is seconds since midnite 1 Jan 1970 UTC,
  4796.   suitable for comparison with UNIX file dates.  As far as I know, there is
  4797.   no library or system call -- at least nothing reasonably portable -- to
  4798.   convert local time to UTC.
  4799. */
  4800. time_t
  4801. zstrdt(date,len) char * date; int len; {
  4802. #ifdef M_UNIX
  4803. /*
  4804.   SCO UNIX 3.2v2.0 and ODT 2.0 lack prototypes for ftime().
  4805.   ODT 3.0 (3.2v4.2 OS) has a prototype, which may vary in
  4806.   dependence on the XPG4 supplement presence.  So always use
  4807.   what the system header file supplies in ODT 3.0...
  4808. */
  4809. #ifndef ODT30
  4810. #ifndef _SCO_DS
  4811.     extern void ftime();  /* extern void ftime(struct timeb *) */
  4812. #endif /* _SCO_DS */
  4813. #endif /* ODT30 */
  4814. #else
  4815. #ifndef M_XENIX
  4816.     extern int ftime();
  4817. #endif /* M_XENIX */
  4818. #endif /* M_UNIX */
  4819.     extern struct tm * localtime();
  4820.  
  4821.     /* And this should have been declared always through a header file */
  4822. #ifdef HPUX10
  4823.     time_t tmx;
  4824.     long days;
  4825. #else
  4826. #ifdef BSD44
  4827.     time_t tmx;
  4828.     long days;
  4829. #else
  4830.     long tmx, days;
  4831. #endif /* BSD44 */
  4832. #endif /* HPUX10 */
  4833.     int i, n, isleapyear;
  4834.                    /*       J  F  M  A   M   J   J   A   S   O   N   D   */
  4835.                    /*      31 28 31 30  31  30  31  31  30  31  30  31   */
  4836.     static
  4837.     int monthdays [13] = {  0,0,31,59,90,120,151,181,212,243,273,304,334 };
  4838.     char s[5];
  4839.     struct tm *time_stamp;
  4840.  
  4841. #ifdef BSD44
  4842.     struct timeval tp[2];
  4843.     long xtimezone = 0L;
  4844. #else
  4845. #ifdef V7
  4846.     struct utimbuf {
  4847.       time_t timep[2];          /* New access and modificaton time */
  4848.     } tp;
  4849.     char *tz;
  4850.     long timezone;              /* In case timezone not defined in .h file */
  4851. #else
  4852. #ifdef SYSUTIMEH
  4853.     struct utimbuf tp;
  4854. #else
  4855.     struct utimbuf {
  4856.         time_t atime;
  4857.         time_t mtime;
  4858.     } tp;
  4859. #endif /* SYSUTIMEH */
  4860. #endif /* V7 */
  4861. #endif /* BSD44 */
  4862.  
  4863. #ifdef ANYBSD
  4864.     long timezone = 0L;
  4865.     static struct timeb tbp;
  4866. #endif /* ANYBSD */
  4867.  
  4868. #ifdef BEBOX
  4869.     long timezone = 0L;
  4870. #endif /* BEBOX */
  4871.  
  4872.     debug(F111,"zstrdt",date,len);
  4873.  
  4874.     if ((len == 0)
  4875.         || (len != 17)
  4876.         || (date[8] != ' ')
  4877.         || (date[11] != ':')
  4878.         || (date[14] != ':') ) {
  4879.         debug(F111,"Bad creation date ",date,len);
  4880.         return(-1);
  4881.     }
  4882.     debug(F111,"zstrdt date check 1",date,len);
  4883.     for(i = 0; i < 8; i++) {
  4884.         if (!isdigit(date[i])) {
  4885.             debug(F111,"Bad creation date ",date,len);
  4886.             return(-1);
  4887.         }
  4888.     }
  4889.     debug(F111,"zstrdt date check 2",date,len);
  4890.     i++;
  4891.  
  4892.     for (; i < 16; i += 3) {
  4893.         if ((!isdigit(date[i])) || (!isdigit(date[i + 1]))) {
  4894.             debug(F111,"Bad creation date ",date,len);
  4895.             return(-1);
  4896.         }
  4897.     }
  4898.     debug(F111,"zstrdt date check 3",date,len);
  4899.  
  4900.  
  4901. #ifdef COMMENT /* was BSD44 */
  4902. /*
  4903.    man gettimeofday on BSDI 3.1 says:
  4904.    "The timezone field is no longer used; timezone information is stored out-
  4905.      side the kernel.  See ctime(3) for more information."  So this chunk of
  4906.    code is effectively a no-op, at least in BSDI 3.x.
  4907. */
  4908.     {
  4909.         int x;
  4910.         struct timezone tzp;
  4911.         x = gettimeofday(NULL, &tzp);
  4912.         debug(F101,"zstrdt BSD44 gettimeofday","",x);
  4913.         if (x > -1)
  4914.           xtimezone = tzp.tz_minuteswest * 60L;
  4915.         else
  4916.           xtimezone = 0L;
  4917.         debug(F101,"zstrdt BSD44 timezone","",xtimezone);
  4918.     }
  4919. #else
  4920. #ifdef ANYBSD
  4921.     debug(F100,"zstrdt BSD calling ftime","",0);
  4922.     ftime(&tbp);
  4923.     debug(F100,"zstrdt BSD back from ftime","",0);
  4924.     timezone = tbp.timezone * 60L;
  4925.     debug(F101,"zstrdt BSD timezone","",timezone);
  4926. #else
  4927. #ifdef SVORPOSIX
  4928.     tzset();                            /* Set timezone */
  4929. #else
  4930. #ifdef V7
  4931.     if ((tz = getenv("TZ")) == NULL)
  4932.       timezone = 0;                     /* UTC/GMT */
  4933.     else
  4934.       timezone = atoi(&tz[3]);          /* Set 'timezone'. */
  4935.     timezone *= 60L;
  4936. #endif /* V7 */
  4937. #endif /* SVORPOSIX */
  4938. #endif /* ANYBSD */
  4939. #endif /* COMMENT (was BSD44) */
  4940.  
  4941.     debug(F100,"zstrdt so far so good","",0);
  4942.  
  4943.     s[4] = '\0';
  4944.     for (i = 0; i < 4; i++)             /* Fix the year */
  4945.       s[i] = date[i];
  4946.  
  4947.     n = atoi(s);
  4948.     debug(F111,"zstrdt year",s,n);
  4949.     if (n < 1970) {
  4950.         debug(F100,"zstrdt fails - year","",n);
  4951.         return(-1);
  4952.     }
  4953.  
  4954. /*  Previous year's leap days.  This won't work after year 2100. */
  4955.  
  4956.     isleapyear = (( n % 4 == 0 && n % 100 !=0) || n % 400 == 0);
  4957.     days = (long) (n - 1970) * 365;
  4958.     days += (n - 1968 - 1) / 4 - (n - 1900 - 1) / 100 + (n - 1600 - 1) / 400;
  4959.  
  4960.     s[2] = '\0';
  4961.  
  4962.     for (i = 4; i < 16; i += 2) {
  4963.         s[0] = date[i];
  4964.         s[1] = date[i + 1];
  4965.         n = atoi(s);
  4966.         switch (i) {
  4967.           case 4:                       /* MM: month */
  4968.             if ((n < 1 ) || ( n > 12)) {
  4969.                 debug(F111,"zstrdt 4 bad date ",date,len);
  4970.                 return(-1);
  4971.             }
  4972.             days += monthdays [n];
  4973.             if (isleapyear && n > 2)
  4974.               ++days;
  4975.             continue;
  4976.  
  4977.           case 6:                       /* DD: day */
  4978.             if ((n < 1 ) || ( n > 31)) {
  4979.                 debug(F111,"zstrdt 6 bad date ",date,len);
  4980.                 return(-1);
  4981.             }
  4982.             tmx = (days + n - 1) * 24L * 60L * 60L;
  4983.             i++;                        /* Skip the space */
  4984.             continue;
  4985.  
  4986.           case 9:                       /* hh: hour */
  4987.             if ((n < 0 ) || ( n > 23)) {
  4988.                 debug(F111,"zstrdt 9 bad date ",date,len);
  4989.                 return(-1);
  4990.             }
  4991.             tmx += n * 60L * 60L;
  4992.             i++;                        /* Skip the colon */
  4993.             continue;
  4994.  
  4995.           case 12:                      /* mm: minute */
  4996.             if ((n < 0 ) || ( n > 59)) {
  4997.                 debug(F111,"zstrdt 12 bad date ",date,len);
  4998.                 return(-1);
  4999.             }
  5000. #ifdef COMMENT /* (was BSD44) */        /* Correct for time zone */
  5001.             tmx += xtimezone;
  5002.             debug(F101,"zstrdt BSD44 tmx","",tmx);
  5003. #else
  5004. #ifdef ANYBSD
  5005.             tmx += timezone;
  5006. #else
  5007. #ifndef CONVEX9 /* Don't yet know how to do this here */
  5008. #ifdef ultrix
  5009.             tmx += (long) timezone;
  5010. #else
  5011. #ifdef Plan9
  5012.             {
  5013.                 extern time_t tzoffset;
  5014.                 tmx += tzoffset;
  5015.             }
  5016. #else
  5017. #ifndef BSD44
  5018. #ifndef NOTIMEZONE
  5019.             tmx += timezone;
  5020. #endif    /* NOTIMEZONE */
  5021. #endif /* BSD44 */
  5022. #endif /* Plan9 */
  5023. #endif /* ultrix */
  5024. #endif /* CONVEX9 */
  5025. #endif /* ANYBSD */
  5026. #endif /* COMMENT (was BSD44) */
  5027.             tmx += n * 60L;
  5028.             i++;                        /* Skip the colon */
  5029.             continue;
  5030.  
  5031.           case 15:                      /* ss: second */
  5032.             if ((n < 0 ) || ( n > 59)) {
  5033.                 debug(F111,"zstrdt 15 bad date ",date,len);
  5034.                 return(-1);
  5035.             }
  5036.             tmx += n;
  5037.         }
  5038.         time_stamp = localtime(&tmx);
  5039.         debug(F101,"zstrdt tmx 1","",tmx);
  5040.         if (!time_stamp)
  5041.           return(-1);
  5042. #ifdef COMMENT
  5043.         /* Why was this here? */
  5044.         time_stamp = localtime(&tmx);
  5045.         debug(F101,"zstrdt tmx 2","",tmx);
  5046. #endif /* COMMENT */
  5047. #ifdef BSD44
  5048.         {   /* New to 7.0 - Works in at at least BSDI 3.1 and FreeBSD 2.2.7 */
  5049.             long zz;
  5050.             zz = time_stamp->tm_gmtoff; /* Seconds away from Zero Meridian */
  5051.             debug(F101,"zstrdt BSD44 tm_gmtoff","",zz);
  5052.             tmx -= zz;
  5053.             debug(F101,"zstrdt BSD44 tmx 3 (GMT)","",tmx);
  5054.         }
  5055. #else
  5056.         /*
  5057.            Daylight Savings Time adjustment.
  5058.            Do this everywhere BUT in BSD44 because in BSD44,
  5059.            tm_gmtoff also includes the DST adjustment.
  5060.         */
  5061.         if (time_stamp->tm_isdst) {
  5062.             tmx -= 60L * 60L;
  5063.             debug(F101,"zstrdt tmx 3 (DST)","",tmx);
  5064.         }
  5065. #endif /* BSD44 */
  5066.         n = time_stamp->tm_year;
  5067.         if (n < 300) {
  5068.             n += 1900;
  5069.         }
  5070.     }
  5071.     return(tmx);
  5072. }
  5073.  
  5074.  
  5075. #ifdef ZLOCALTIME
  5076. /* Z L O C A L T I M E  --  GMT/UTC time string to local time string */
  5077.  
  5078. /*
  5079.    Call with: "yyyymmdd hh:mm:ss" GMT/UTC date-time.
  5080.    Returns:   "yyyymmdd hh:mm:ss" local date-time on success, NULL on failure.
  5081. */
  5082. static char zltimbuf[64];
  5083.  
  5084. char *
  5085. zlocaltime(gmtstring) char * gmtstring; {
  5086. #ifdef M_UNIX
  5087. /*
  5088.   SCO UNIX 3.2v2.0 and ODT 2.0 lack prototypes for ftime().
  5089.   ODT 3.0 (3.2v4.2 OS) has a prototype, which may vary in
  5090.   dependence on the XPG4 supplement presence.  So always use
  5091.   what the system header file supplies in ODT 3.0...
  5092. */
  5093. #ifndef ODT30
  5094. #ifndef _SCO_DS
  5095.     extern void ftime();  /* extern void ftime(struct timeb *) */
  5096. #endif /* _SCO_DS */
  5097. #endif /* ODT30 */
  5098. #else
  5099. #ifndef M_XENIX
  5100.     extern int ftime();
  5101. #endif /* M_XENIX */
  5102. #endif /* M_UNIX */
  5103.     extern struct tm * localtime();
  5104.  
  5105.     /* And this should have been declared always through a header file */
  5106. #ifdef HPUX10
  5107.     time_t tmx;
  5108.     long days;
  5109. #else
  5110. #ifdef BSD44
  5111.     time_t tmx;
  5112.     long days;
  5113. #else
  5114.     long tmx, days;
  5115. #endif /* BSD44 */
  5116. #endif /* HPUX10 */
  5117.     int i, n, x, isleapyear;
  5118.                    /*       J  F  M  A   M   J   J   A   S   O   N   D   */
  5119.                    /*      31 28 31 30  31  30  31  31  30  31  30  31   */
  5120.     static
  5121.     int monthdays [13] = {  0,0,31,59,90,120,151,181,212,243,273,304,334 };
  5122.     char s[5];
  5123.     struct tm *time_stamp;
  5124.  
  5125. #ifdef BSD44
  5126.     struct timeval tp[2];
  5127. #else
  5128. #ifdef V7
  5129.     struct utimbuf {
  5130.       time_t timep[2];          /* New access and modificaton time */
  5131.     } tp;
  5132. #else
  5133. #ifdef SYSUTIMEH
  5134.     struct utimbuf tp;
  5135. #else
  5136.     struct utimbuf {
  5137.         time_t atime;
  5138.         time_t mtime;
  5139.     } tp;
  5140. #endif /* SYSUTIMEH */
  5141. #endif /* V7 */
  5142. #endif /* BSD44 */
  5143.  
  5144. #ifdef ANYBSD
  5145.     static struct timeb tbp;
  5146. #endif /* ANYBSD */
  5147.  
  5148.     char * date = gmtstring;
  5149.     int len;
  5150.  
  5151.     len = strlen(date);
  5152.     debug(F111,"zlocaltime",date,len);
  5153.  
  5154.     if ((len == 0)
  5155.         || (len != 17)
  5156.         || (date[8] != ' ')
  5157.         || (date[11] != ':')
  5158.         || (date[14] != ':') ) {
  5159.         debug(F111,"Bad creation date ",date,len);
  5160.         return(NULL);
  5161.     }
  5162.     debug(F111,"zlocaltime date check 1",date,len);
  5163.     for(i = 0; i < 8; i++) {
  5164.         if (!isdigit(date[i])) {
  5165.             debug(F111,"Bad creation date ",date,len);
  5166.             return(NULL);
  5167.         }
  5168.     }
  5169.     debug(F111,"zlocaltime date check 2",date,len);
  5170.     i++;
  5171.  
  5172.     for (; i < 16; i += 3) {
  5173.         if ((!isdigit(date[i])) || (!isdigit(date[i + 1]))) {
  5174.             debug(F111,"Bad creation date ",date,len);
  5175.         return(NULL);
  5176.         }
  5177.     }
  5178.     debug(F111,"zlocaltime date check 3",date,len);
  5179.  
  5180.     debug(F100,"zlocaltime so far so good","",0);
  5181.  
  5182.     s[4] = '\0';
  5183.     for (i = 0; i < 4; i++)             /* Fix the year */
  5184.       s[i] = date[i];
  5185.  
  5186.     n = atoi(s);
  5187.     debug(F111,"zlocaltime year",s,n);
  5188.     if (n < 1970) {
  5189.         debug(F100,"zlocaltime fails - year","",n);
  5190.         return(NULL);
  5191.     }
  5192.  
  5193. /*  Previous year's leap days.  This won't work after year 2100. */
  5194.  
  5195.     isleapyear = (( n % 4 == 0 && n % 100 !=0) || n % 400 == 0);
  5196.     days = (long) (n - 1970) * 365;
  5197.     days += (n - 1968 - 1) / 4 - (n - 1900 - 1) / 100 + (n - 1600 - 1) / 400;
  5198.  
  5199.     s[2] = '\0';
  5200.  
  5201.     for (i = 4; i < 16; i += 2) {
  5202.         s[0] = date[i];
  5203.         s[1] = date[i + 1];
  5204.         n = atoi(s);
  5205.         switch (i) {
  5206.           case 4:                       /* MM: month */
  5207.             if ((n < 1 ) || ( n > 12)) {
  5208.                 debug(F111,"zlocaltime 4 bad date ",date,len);
  5209.                 return(NULL);
  5210.             }
  5211.             days += monthdays [n];
  5212.             if (isleapyear && n > 2)
  5213.               ++days;
  5214.             continue;
  5215.  
  5216.           case 6:                       /* DD: day */
  5217.             if ((n < 1 ) || ( n > 31)) {
  5218.                 debug(F111,"zlocaltime 6 bad date ",date,len);
  5219.                 return(NULL);
  5220.             }
  5221.             tmx = (days + n - 1) * 24L * 60L * 60L;
  5222.             i++;                        /* Skip the space */
  5223.             continue;
  5224.  
  5225.           case 9:                       /* hh: hour */
  5226.             if ((n < 0 ) || ( n > 23)) {
  5227.                 debug(F111,"zlocaltime 9 bad date ",date,len);
  5228.                 return(NULL);
  5229.             }
  5230.             tmx += n * 60L * 60L;
  5231.             i++;                        /* Skip the colon */
  5232.             continue;
  5233.  
  5234.           case 12:                      /* mm: minute */
  5235.             if ((n < 0 ) || ( n > 59)) {
  5236.                 debug(F111,"zlocaltime 12 bad date ",date,len);
  5237.                 return(NULL);
  5238.             }
  5239.             tmx += n * 60L;
  5240.             i++;                        /* Skip the colon */
  5241.             continue;
  5242.  
  5243.           case 15:                      /* ss: second */
  5244.             if ((n < 0 ) || ( n > 59)) {
  5245.                 debug(F111,"zlocaltime 15 bad date ",date,len);
  5246.                 return(NULL);
  5247.             }
  5248.             tmx += n;
  5249.         }
  5250.  
  5251. /*
  5252.   At this point tmx is the time_t representation of the argument date-time
  5253.   string without any timezone or DST adjustments.  Therefore it should be
  5254.   the same as the time_t representation of the GMT/UTC time.  Now we should
  5255.   be able to feed it to localtime() and have it converted to a struct tm
  5256.   representing the local time equivalent of the given UTC time.
  5257. */
  5258.         time_stamp = localtime(&tmx);
  5259.         if (!time_stamp)
  5260.           return(NULL);
  5261.     }
  5262.  
  5263. /* Now we simply reformat the struct tm to a string */
  5264.  
  5265.     x = time_stamp->tm_year;
  5266.     if (time_stamp->tm_year < 70 || time_stamp->tm_year > 8099)
  5267.       return(NULL);
  5268.     if (time_stamp->tm_mon < 0 || time_stamp->tm_mon > 11)
  5269.       return(NULL);
  5270.     if (time_stamp->tm_mday < 1 || time_stamp->tm_mday > 31)
  5271.       return(NULL);
  5272.     if (time_stamp->tm_hour < 0 || time_stamp->tm_hour > 24)
  5273.       return(NULL);
  5274.     if (time_stamp->tm_min < 0 || time_stamp->tm_min > 60)
  5275.       return(NULL);
  5276.     if (time_stamp->tm_sec < 0 || time_stamp->tm_sec > 60)
  5277.       return(NULL);
  5278.     sprintf(zltimbuf,"%04d%02d%02d %02d:%02d:%02d",
  5279.         time_stamp->tm_year + 1900,
  5280.         time_stamp->tm_mon + 1,
  5281.         time_stamp->tm_mday,
  5282.         time_stamp->tm_hour,
  5283.         time_stamp->tm_min,
  5284.         time_stamp->tm_sec
  5285.         );
  5286.     return((char *)zltimbuf);
  5287. }
  5288. #endif /* ZLOCALTIME */
  5289. #endif /* NOTIMESTAMP */
  5290.  
  5291. /* Z S T I M E  --  Set modification date/time+permissions for incoming file */
  5292. /*
  5293.  Call with:
  5294.  f  = pointer to name of existing file.
  5295.  yy = pointer to a Kermit file attribute structure in which yy->date.val
  5296.       is a date of the form yyyymmdd hh:mm:ss, e.g. 19900208 13:00:00.
  5297.       yy->lprotect.val & yy->gprotect.val are permission/protection values.
  5298.  x  = is a function code: 0 means to set the file's attributes as given.
  5299.       1 means compare the date in struct yy with the file creation date.
  5300.  Returns:
  5301.  -1 on any kind of error.
  5302.   0 if x is 0 and the attributes were set successfully.
  5303.   0 if x is 1 and date from attribute structure <= file creation date.
  5304.   1 if x is 1 and date from attribute structure > file creation date.
  5305. */
  5306. int
  5307. zstime(f,yy,x)
  5308.     char *f; struct zattr *yy; int x;
  5309. /* zstime */ {
  5310.     int r = -1;                         /* Return code */
  5311. #ifdef CK_PERMS
  5312.     int setperms = 0;
  5313. #endif /* CK_PERMS */
  5314.     int setdate = 0;
  5315.  
  5316. /* It is ifdef'd TIMESTAMP because it might not work on V7. bk@kullmar.se.  */
  5317.  
  5318. #ifdef TIMESTAMP
  5319. #ifdef BSD44
  5320.     extern int utimes();
  5321. #else
  5322.     extern int utime();
  5323. #endif /* BSD44 */
  5324.  
  5325.     struct stat sb;
  5326.  
  5327. /* At least, the declarations for int functions are not needed anyway */
  5328.  
  5329. #ifdef BSD44
  5330.     struct timeval tp[2];
  5331.     long xtimezone;
  5332. #else
  5333. #ifdef V7
  5334.     struct utimbuf {
  5335.     time_t timep[2];        /* New access and modificaton time */
  5336.     } tp;
  5337.     char *tz;
  5338.     long timezone;                      /* In case not defined in .h file */
  5339. #else
  5340. #ifdef SYSUTIMEH
  5341.     struct utimbuf tp;
  5342. #else
  5343.     struct utimbuf {
  5344.         time_t atime;
  5345.         time_t mtime;
  5346.     } tp;
  5347. #endif /* SYSUTIMEH */
  5348. #endif /* V7 */
  5349. #endif /* BSD44 */
  5350.  
  5351.     long tm = 0L;
  5352.  
  5353.     if (!f) f = "";
  5354.     if (!*f) return(-1);
  5355.     if (!yy) return(-1);
  5356.  
  5357. #ifdef CKROOT
  5358.     debug(F111,"zstime setroot",ckroot,ckrootset);
  5359.     if (ckrootset) if (!zinroot(f)) {
  5360.     debug(F110,"zstime setroot violation",f,0);
  5361.     return(0);
  5362.     }
  5363. #endif /* CKROOT */
  5364.  
  5365.     if (yy->date.len == 0) {            /* No date in struct */
  5366.         if (yy->lprotect.len != 0) {    /* So go do permissions */
  5367.             goto zsperms;
  5368.         } else {
  5369.             debug(F100,"zstime: nothing to do","",0);
  5370.             return(0);
  5371.         }
  5372.     }
  5373.     if ((tm = zstrdt(yy->date.val,yy->date.len)) < 0) {
  5374.         debug(F101,"zstime: zstrdt fails","",0);
  5375.         return(-1);
  5376.     }
  5377.     debug(F101,"zstime: tm","",tm);
  5378.     debug(F111,"zstime: A-pkt date ok ",yy->date.val,yy->date.len);
  5379.  
  5380.     if (stat(f,&sb)) {                  /* Get the time for the file */
  5381.     debug(F101,"STAT","",14);
  5382.         debug(F111,"zstime: Can't stat file:",f,errno);
  5383.         return(-1);
  5384.     }
  5385.     debug(F101,"STAT","",15);
  5386.     setdate = 1;
  5387.  
  5388.   zsperms:
  5389. #ifdef CK_PERMS
  5390.     {
  5391.         int i, x = 0, xx, flag = 0;
  5392.         char * s;
  5393. #ifdef DEBUG
  5394.         char obuf[24];
  5395.         if (deblog) {
  5396.             debug(F111,"zstime lperms",yy->lprotect.val,yy->lprotect.len);
  5397.             debug(F111,"zstime gperms",yy->gprotect.val,yy->gprotect.len);
  5398.             debug(F110,"zstime system id",yy->systemid.val,0);
  5399.             sprintf(obuf,"%o",sb.st_mode);
  5400.             debug(F110,"zstime file perms before",obuf,0);
  5401.         }
  5402. #endif /* DEBUG */
  5403.  
  5404. #ifdef CK_LOGIN
  5405.         debug(F101,"zstime isguest","",isguest);
  5406.         debug(F101,"zstime ckxperms","",ckxperms);
  5407.         if (isguest) {
  5408. #ifdef COMMENT
  5409.             /* Clear owner permissions */
  5410.             sb.st_mode &= (unsigned) 0177077; /* (16 bits) */
  5411. #else
  5412.             /* Set permissions from ckxperms variable */
  5413.             sb.st_mode = ckxperms;
  5414. #endif /* COMMENT */
  5415.             debug(F101,"zstime isguest sb.st_mode","",sb.st_mode);
  5416. #ifdef COMMENT
  5417.             /* We already set them in zopeno() */
  5418.             setperms = 1;
  5419. #endif /* COMMENT */
  5420.             flag = 0;
  5421.         } else
  5422. #endif /* CK_LOGIN */
  5423.           if ((yy->lprotect.len > 0 &&  /* Have local-format permissions */
  5424.             yy->systemid.len > 0 &&     /* from A-packet... */
  5425. #ifdef UNIX
  5426.             !strcmp(yy->systemid.val,"U1") /* AND you are same as me */
  5427. #else
  5428.             0
  5429. #endif /* UNIX */
  5430.              ) || (yy->lprotect.len < 0) /* OR by inheritance from old file */
  5431.             ) {
  5432.             flag = 1;
  5433.             s = yy->lprotect.val;       /* UNIX filemode */
  5434.             xx = yy->lprotect.len;
  5435.             if (xx < 0)                 /* len < 0 means inheritance */
  5436.               xx = 0 - xx;
  5437.             for (i = 0; i < xx; i++) {  /* Decode octal string */
  5438.                 if (*s <= '7' && *s >= '0') {
  5439.                     x = 8 * x + (int)(*s) - '0';
  5440.                 } else {
  5441.                     flag = 0;
  5442.                     break;
  5443.                 }
  5444.                 s++;
  5445.             }
  5446. #ifdef DEBUG
  5447.             sprintf(obuf,"%o",x);
  5448.             debug(F110,"zstime octal lperm",obuf,0);
  5449. #endif /* DEBUG */
  5450.         } else if (!flag && yy->gprotect.len > 0) {
  5451.             int g;
  5452. #ifdef CK_SCO32V4
  5453.             mode_t mask;
  5454. #else
  5455.             int mask;
  5456. #endif /* CK_SCO32V4 */
  5457.             mask = umask(0);            /* Get umask */
  5458.             debug(F101,"zstime mask 1","",mask);
  5459.             umask(mask);                /* Put it back */
  5460.             mask ^= 0777;               /* Flip the bits */
  5461.             debug(F101,"zstime mask 2","",mask);
  5462.             g = xunchar(*(yy->gprotect.val)); /* Decode generic protection */
  5463.             debug(F101,"zstime gprotect","",g);
  5464. #ifdef S_IRUSR
  5465.             debug(F100,"zstime S_IRUSR","",0);
  5466.             if (g & 1) x |= S_IRUSR;    /* Read permission */
  5467.             flag = 1;
  5468. #endif /* S_IRUSR */
  5469. #ifdef S_IWUSR
  5470.             debug(F100,"zstime S_IWUSR","",0);
  5471.             if (g & 2) x |= S_IWUSR;    /* Write permission */
  5472.             if (g & 16) x |= S_IWUSR;   /* Delete permission */
  5473.             flag = 1;
  5474. #endif /* S_IWUSR */
  5475. #ifdef S_IXUSR
  5476.             debug(F100,"zstime S_IXUSR","",0);
  5477.             if (g & 4)                  /* Has execute permission bit */
  5478.               x |= S_IXUSR;
  5479.             else                        /* Doesn't have it */
  5480.               mask &= 0666;             /* so also clear it out of mask */
  5481.             flag = 1;
  5482. #endif /* S_IXUSR */
  5483.             debug(F101,"zstime mask x","",x);
  5484.             x |= mask;
  5485.             debug(F101,"zstime mask x|mask","",x);
  5486.         }
  5487.         debug(F101,"zstime flag","",flag);
  5488.         if (flag) {
  5489. #ifdef S_IFMT
  5490.             debug(F101,"zstime S_IFMT x","",x);
  5491.             sb.st_mode = (sb.st_mode & S_IFMT) | x;
  5492.             setperms = 1;
  5493. #else
  5494. #ifdef _IFMT
  5495.             debug(F101,"zstime _IFMT x","",x);
  5496.             sb.st_mode = (sb.st_mode & _IFMT) | x;
  5497.             setperms = 1;
  5498. #endif /* _IFMT */
  5499. #endif /* S_IFMT */
  5500.         }
  5501. #ifdef DEBUG
  5502.         sprintf(obuf,"%04o",sb.st_mode);
  5503.         debug(F111,"zstime file perms after",obuf,setperms);
  5504. #endif /* DEBUG */
  5505.     }
  5506. #endif /* CK_PERMS */
  5507.  
  5508.     debug(F101,"zstime: sb.st_atime","",sb.st_atime);
  5509.  
  5510. #ifdef BSD44
  5511.     tp[0].tv_sec = sb.st_atime;         /* Access time first */
  5512.     tp[1].tv_sec = tm;                  /* Update time second */
  5513.     debug(F100,"zstime: BSD44 modtime","",0);
  5514. #else
  5515. #ifdef V7
  5516.     tp.timep[0] = tm;                   /* Set modif. time to creation date */
  5517.     tp.timep[1] = sb.st_atime;          /* Don't change the access time */
  5518.     debug(F100,"zstime: V7 modtime","",0);
  5519. #else
  5520. #ifdef SYSUTIMEH
  5521.     tp.modtime = tm;                    /* Set modif. time to creation date */
  5522.     tp.actime = sb.st_atime;            /* Don't change the access time */
  5523.     debug(F100,"zstime: SYSUTIMEH modtime","",0);
  5524. #else
  5525.     tp.mtime = tm;                      /* Set modif. time to creation date */
  5526.     tp.atime = sb.st_atime;             /* Don't change the access time */
  5527.     debug(F100,"zstime: default modtime","",0);
  5528. #endif /* SYSUTIMEH */
  5529. #endif /* V7 */
  5530. #endif /* BSD44 */
  5531.  
  5532.     switch (x) {                        /* Execute desired function */
  5533.       case 0:                           /* Set the creation date of the file */
  5534. #ifdef CK_PERMS                         /* And permissions */
  5535. /*
  5536.   NOTE: If we are inheriting permissions from a previous file, and the
  5537.   previous file was a directory, this would turn the new file into a directory
  5538.   too, but it's not, so we try to unset the right bit.  Luckily, this code
  5539.   will probably never be executed since the upper level modules do not allow
  5540.   reception of a file that has the same name as a directory.
  5541.  
  5542.   NOTE 2: We change the permissions *before* we change the modification time,
  5543.   otherwise changing the permissions would set the mod time to the present
  5544.   time.
  5545. */
  5546.         {
  5547.             int x;
  5548.             debug(F101,"zstime setperms","",setperms);
  5549.             if (S_ISDIR(sb.st_mode)) {
  5550.                 debug(F101,"zstime DIRECTORY bit on","",sb.st_mode);
  5551.                 sb.st_mode ^= 0040000;
  5552.                 debug(F101,"zstime DIRECTORY bit off","",sb.st_mode);
  5553.             }
  5554.             if (setperms) {
  5555.                 x = chmod(f,sb.st_mode);
  5556.                 debug(F101,"zstime chmod","",x);
  5557.             }
  5558.         }
  5559.         if (x < 0) return(-1);
  5560. #endif /* CK_PERMS */
  5561.  
  5562.         if (!setdate)                   /* We don't have a date */
  5563.           return(0);                    /* so skip the following... */
  5564.  
  5565.         if (
  5566. #ifdef BSD44
  5567.             utimes(f,tp)
  5568. #else
  5569.             utime(f,&tp)
  5570. #endif /* BSD44 */
  5571.             ) {                         /* Fix modification time */
  5572.             debug(F111,"zstime 0: can't set modtime for file",f,errno);
  5573.             r = -1;
  5574.         } else  {
  5575.         /* Including the modtime here is not portable */
  5576.             debug(F110,"zstime 0: modtime set for file",f,0);
  5577.             r = 0;
  5578.         }
  5579.         break;
  5580.  
  5581.       case 1:                           /* Compare the dates */
  5582. /*
  5583.   This was st_atime, which was wrong.  We want the file-data modification
  5584.   time, st_mtime.
  5585. */
  5586.         debug(F111,"zstime 1: compare",f,sb.st_mtime);
  5587.         debug(F111,"zstime 1: compare","packet",tm);
  5588.  
  5589.         r = (sb.st_mtime < tm) ? 0 : 1;
  5590.         break;
  5591.  
  5592.       default:                          /* Error */
  5593.         r = -1;
  5594.     }
  5595. #endif /* TIMESTAMP */
  5596.     return(r);
  5597. }
  5598.  
  5599. /* Find initialization file. */
  5600.  
  5601. #ifdef NOTUSED
  5602. int
  5603. zkermini() {
  5604. /*  nothing here for Unix.  This function added for benefit of VMS Kermit.  */
  5605.     return(0);
  5606. }
  5607. #endif /* NOTUSED */
  5608.  
  5609. #ifndef UNIX
  5610. /* Historical -- not used in Unix any more (2001-11-03) */
  5611. #ifndef NOFRILLS
  5612. int
  5613. zmail(p,f) char *p; char *f; {          /* Send file f as mail to address p */
  5614. /*
  5615.   Returns 0 on success
  5616.    2 if mail delivered but temp file can't be deleted
  5617.   -2 if mail can't be delivered
  5618.   -1 on file access error
  5619.   The UNIX version always returns 0 because it can't get a good return
  5620.   code from zsyscmd.
  5621. */
  5622.     int n;
  5623.  
  5624. #ifdef CK_LOGIN
  5625.     if (isguest)
  5626.       return(-2);
  5627. #endif /* CK_LOGIN */
  5628.  
  5629.     if (!f) f = "";
  5630.     if (!*f) return(-1);
  5631.  
  5632. #ifdef CKROOT
  5633.     debug(F111,"zmail setroot",ckroot,ckrootset);
  5634.     if (ckrootset) if (!zinroot(f)) {
  5635.     debug(F110,"zmail setroot violation",f,0);
  5636.     return(-1);
  5637.     }
  5638. #endif /* CKROOT */
  5639.  
  5640. #ifdef BSD4
  5641. /* The idea is to use /usr/ucb/mail, rather than regular mail, so that   */
  5642. /* a subject line can be included with -s.  Since we can't depend on the */
  5643. /* user's path, we use the convention that /usr/ucb/Mail = /usr/ucb/mail */
  5644. /* and even if Mail has been moved to somewhere else, this should still  */
  5645. /* find it...  The search could be made more reliable by actually using  */
  5646. /* access() to see if /usr/ucb/Mail exists. */
  5647.  
  5648.     n = strlen(f);
  5649.     n = n + n + 15 + (int)strlen(p);
  5650.  
  5651.     if (n > ZMBUFLEN)
  5652.       return(-2);
  5653.  
  5654. #ifdef DGUX540
  5655.     sprintf(zmbuf,"mailx -s %c%s%c %s < %s", '"', f, '"', p, f);
  5656. #else
  5657.     sprintf(zmbuf,"Mail -s %c%s%c %s < %s", '"', f, '"', p, f);
  5658. #endif /* DGUX540 */
  5659.     zsyscmd(zmbuf);
  5660. #else
  5661. #ifdef SVORPOSIX
  5662. #ifndef OXOS
  5663.     sprintf(zmbuf,"mail %s < %s", p, f);
  5664. #else /* OXOS */
  5665.     sprintf(zmbuf,"mailx -s %c%s%c %s < %s", '"', f, '"', p, f);
  5666. #endif /* OXOS */
  5667.     zsyscmd(zmbuf);
  5668. #else
  5669.     *zmbuf = '\0';
  5670. #endif
  5671. #endif
  5672.     return(0);
  5673. }
  5674. #endif /* NOFRILLS */
  5675. #endif /* UNIX */
  5676.  
  5677. #ifndef NOFRILLS
  5678. int
  5679. zprint(p,f) char *p; char *f; {         /* Print file f with options p */
  5680.     extern char * printername;          /* From ckuus3.c */
  5681.     extern int printpipe;
  5682.     int n;
  5683.  
  5684. #ifdef CK_LOGIN
  5685.     if (isguest)
  5686.       return(-2);
  5687. #endif /* CK_LOGIN */
  5688.  
  5689.     if (!f) f = "";
  5690.     if (!*f) return(-1);
  5691.  
  5692. #ifdef CKROOT
  5693.     debug(F111,"zprint setroot",ckroot,ckrootset);
  5694.     if (ckrootset) if (!zinroot(f)) {
  5695.     debug(F110,"zprint setroot violation",f,0);
  5696.     return(-1);
  5697.     }
  5698. #endif /* CKROOT */
  5699.  
  5700.     debug(F110,"zprint file",f,0);
  5701.     debug(F110,"zprint flags",p,0);
  5702.     debug(F110,"zprint printername",printername,0);
  5703.     debug(F101,"zprint printpipe","",printpipe);
  5704.  
  5705. #ifdef UNIX
  5706. /*
  5707.   Note use of standard input redirection.  In some systems, lp[r] runs
  5708.   setuid to lp (or ...?), so if user has sent a file into a directory
  5709.   that lp does not have read access to, it can't be printed unless it is
  5710.   fed to lp[r] as standard input.
  5711. */
  5712.     if (printpipe && printername) {
  5713.     n = 8 + (int)strlen(f) + (int)strlen(printername);
  5714.     if (n > ZMBUFLEN)
  5715.       return(-2);
  5716.         sprintf(zmbuf,"cat %s | %s", f, printername);
  5717.     } else if (printername) {
  5718.     n = 8 + (int)strlen(f) + (int)strlen(printername);
  5719.     if (n > ZMBUFLEN)
  5720.       return(-2);
  5721.         sprintf(zmbuf,"cat %s >> %s", f, printername);
  5722.     } else {
  5723.     n = 4 + (int)strlen(PRINTCMD) + (int)strlen(p) + (int)strlen(f);
  5724.     if (n > ZMBUFLEN)
  5725.       return(-2);
  5726.         sprintf(zmbuf,"%s %s < %s", PRINTCMD, p, f);
  5727.     }
  5728.     debug(F110,"zprint command",zmbuf,0);
  5729.     zsyscmd(zmbuf);
  5730. #else /* Not UNIX */
  5731.     *zmbuf = '\0';
  5732. #endif /* UNIX */
  5733.     return(0);
  5734. }
  5735. #endif /* NOFRILLS */
  5736.  
  5737. /*  Wildcard expansion functions...  */
  5738.  
  5739. static char scratch[MAXPATH+4];         /* Used by both methods */
  5740.  
  5741. static int oldmtchs = 0;                /* Let shell (ls) expand them. */
  5742. #ifdef COMMENT
  5743. static char *lscmd = "/bin/ls -d";      /* Command to use. */
  5744. #else
  5745. static char *lscmd = "echo";            /* Command to use. */
  5746. #endif /* COMMENT */
  5747.  
  5748. #ifndef NOPUSH
  5749. int
  5750. shxpand(pat,namlst,len) char *pat, *namlst[]; int len; {
  5751.     char *fgbuf = NULL;                 /* Buffer for forming ls command */
  5752.     char *p, *q;                        /* Workers */
  5753.  
  5754.     int i, x, retcode, itsadir;
  5755.     char c;
  5756.  
  5757.     x = (int)strlen(pat) + (int)strlen(lscmd) + 3; /* Length of ls command */
  5758.     for (i = 0; i < oldmtchs; i++) {    /* Free previous file list */
  5759.         if (namlst[i] ) {               /* If memory is allocated  */
  5760.             free(namlst[i]);            /* Free the memory         */
  5761.             namlst[i] = NULL ;          /* Remember no memory is allocated */
  5762.         }
  5763.     }
  5764.     oldmtchs = 0 ;                      /* Remember there are no matches */
  5765.     fgbuf = malloc(x);                  /* Get buffer for command */
  5766.     if (!fgbuf) return(-1);             /* Fail if cannot */
  5767.     ckmakmsg(fgbuf,x,lscmd," ",pat,NULL); /* Form the command */
  5768.     zxcmd(ZIFILE,fgbuf);                /* Start the command */
  5769.     i = 0;                              /* File counter */
  5770.     p = scratch;                        /* Point to scratch area */
  5771.     retcode = -1;                       /* Assume failure */
  5772.     while ((x = zminchar()) != -1) {    /* Read characters from command */
  5773.         c = (char) x;
  5774.         if (c == ' ' || c == '\n') {    /* Got newline or space? */
  5775.             *p = '\0';                  /* Yes, terminate string */
  5776.             p = scratch;                /* Point back to beginning */
  5777.             if (zchki(p) == -1)         /* Does file exist? */
  5778.               continue;                 /* No, continue */
  5779.             itsadir = isdir(p);         /* Yes, is it a directory? */
  5780.             if (xdironly && !itsadir)   /* Want only dirs but this isn't */
  5781.               continue;                 /* so skip. */
  5782.             if (xfilonly && itsadir)    /* It's a dir but want only files */
  5783.               continue;                 /* so skip. */
  5784.             x = (int)strlen(p);         /* Keep - get length of name */
  5785.             q = malloc(x+1);            /* Allocate space for it */
  5786.             if (!q) goto shxfin;        /* Fail if space can't be obtained */
  5787.             strcpy(q,scratch);          /* (safe) Copy name to space */
  5788.             namlst[i++] = q;            /* Copy pointer to name into array */
  5789.             if (i >= len) goto shxfin;  /* Fail if too many */
  5790.         } else {                        /* Regular character */
  5791.             *p++ = c;                   /* Copy it into scratch area */
  5792.         }
  5793.     }
  5794.     retcode = i;                        /* Return number of matching files */
  5795. shxfin:                                 /* Common exit point */
  5796.     free(fgbuf);                        /* Free command buffer */
  5797.     fgbuf = NULL;
  5798.     zclosf(ZIFILE);                     /* Delete the command fork. */
  5799.     oldmtchs = i;                       /* Remember how many files */
  5800.     return(retcode);
  5801. }
  5802. #endif /* NOPUSH */
  5803.  
  5804. /*
  5805.   Directory-reading functions for UNIX originally written for C-Kermit 4.0
  5806.   by Jeff Damens, CUCCA, 1984.
  5807. */
  5808. static char * xpat = NULL;              /* Global copy of fgen() pattern */
  5809. static char * xpatlast = NULL;          /* Rightmost segment of pattern*/
  5810. static int xpatslash = 0;               /* Slash count in pattern */
  5811. static int xpatwild = 0;                /* Original pattern is wild */
  5812. static int xleafwild = 0;               /* Last segment of pattern is wild */
  5813. static int xpatabsolute = 0;
  5814.  
  5815. #ifdef aegis
  5816. static char bslash;
  5817. #endif /* aegis */
  5818.  
  5819.  
  5820. /*  S P L I T P A T H  */
  5821.  
  5822. /*
  5823.   Splits the slash-separated portions of the argument string into
  5824.   a list of path structures.  Returns the head of the list.  The
  5825.   structures are allocated by malloc, so they must be freed.
  5826.   Splitpath is used internally by the filename generator.
  5827.  
  5828.   Input:
  5829.     A path string.
  5830.  
  5831.   Returns:
  5832.     A linked list of the slash-separated segments of the input.
  5833. */
  5834. static struct path *
  5835. splitpath(p) char *p; {
  5836.     struct path *head,*cur,*prv;
  5837.     int i;
  5838.  
  5839.     debug(F111,"splitpath",p,xrecursive);
  5840.     head = prv = NULL;
  5841.  
  5842.     if (!p) return(NULL);
  5843.     if (!*p) return(NULL);
  5844.  
  5845.     if (!strcmp(p,"**")) {              /* Fix this */
  5846.         p = "*";
  5847.     }
  5848.     if (ISDIRSEP(*p)) p++;              /* Skip leading slash if any */
  5849.  
  5850.     /* Make linked list of path segments from pattern */
  5851.  
  5852.     while (*p) {
  5853.         cur = (struct path *) malloc(sizeof (struct path));
  5854.         /* debug(F101,"splitpath malloc","",cur); */
  5855.         if (cur == NULL) {
  5856.             debug(F100,"splitpath malloc failure","",0);
  5857.             prv -> fwd = NULL;
  5858.             return((struct path *)NULL);
  5859.         }
  5860.         cur -> fwd = NULL;
  5861.         if (head == NULL)               /* First, make list head */
  5862.           head = cur;
  5863.         else                            /* Not first, link into chain */
  5864.           prv -> fwd = cur;
  5865.         prv = cur;                      /* Link from previous to this one */
  5866.  
  5867. #ifdef aegis
  5868.         /* treat backslash as "../" */
  5869.         if (bslash && *p == bslash) {
  5870.             strcpy(cur->npart, "..");    /* safe */
  5871.             ++p;
  5872.         } else {
  5873.             for (i=0; i < MAXNAMLEN && *p && *p != '/' && *p != bslash; i++)
  5874.               cur -> npart[i] = *p++;
  5875.             cur -> npart[i] = '\0';     /* end this segment */
  5876.             if (i >= MAXNAMLEN)
  5877.               while (*p && *p != '/' && *p != bslash)
  5878.                 p++;
  5879.         }
  5880.         if (*p == '/') p++;
  5881. #else
  5882.         /* General case (UNIX) */
  5883.         for (i = 0; i < MAXNAMLEN && !ISDIRSEP(*p) && *p != '\0'; i++) {
  5884.             cur -> npart[i] = *p++;
  5885.         }
  5886.  
  5887.         cur -> npart[i] = '\0';         /* End this path segment */
  5888.         if (i >= MAXNAMLEN)
  5889.           while (!ISDIRSEP(*p) && *p != '\0') p++;
  5890.         if (ISDIRSEP(*p))
  5891.           p++;
  5892.  
  5893. #endif /* aegis */
  5894.     }
  5895.     if (prv) {
  5896.         makestr(&xpatlast,prv -> npart);
  5897.         debug(F110,"splitpath xpatlast",xpatlast,0);
  5898.     }
  5899. #ifdef DEBUG
  5900.     /* Show original path list */
  5901.     if (deblog) {
  5902.         for (i = 0, cur = head; cur; i++) {
  5903.             debug(F111,"SPLITPATH",cur -> npart, i);
  5904.             cur = cur -> fwd;
  5905.         }
  5906.     }
  5907. #endif /* DEBUG */
  5908.     return(head);
  5909. }
  5910.  
  5911. /*  F G E N  --  Generate File List  */
  5912.  
  5913. /*
  5914.   File name generator.  It is passed a string, possibly containing wildcards,
  5915.   and an array of character pointers.  It finds all the matching filenames and
  5916.   stores pointers to them in the array.  The returned strings are allocated
  5917.   from a static buffer local to this module (so the caller doesn't have to
  5918.   worry about deallocating them); this means that successive calls to fgen
  5919.   will wipe out the results of previous calls.
  5920.  
  5921.   Input:
  5922.     A wildcard string, an array to write names to, the length of the array.
  5923.  
  5924.   Returns:
  5925.     The number of matches.
  5926.     The array is filled with filenames that matched the pattern.
  5927.     If there wasn't enough room in the array, -1 is returned.
  5928.  
  5929.   Originally by: Jeff Damens, CUCCA, 1984.  Many changes since then.
  5930. */
  5931. static int
  5932. fgen(pat,resarry,len) char *pat,*resarry[]; int len; {
  5933.     struct path *head;
  5934.     char *sptr, *s;
  5935.     int n;
  5936.  
  5937. #ifdef aegis
  5938.     char *namechars;
  5939.     int tilde = 0, bquote = 0;
  5940.  
  5941.     if ((namechars = getenv("NAMECHARS")) != NULL) {
  5942.         if (ckstrchr(namechars, '~' ) != NULL) tilde  = '~';
  5943.         if (ckstrchr(namechars, '\\') != NULL) bslash = '\\';
  5944.         if (ckstrchr(namechars, '`' ) != NULL) bquote = '`';
  5945.     } else {
  5946.         tilde = '~'; bslash = '\\'; bquote = '`';
  5947.     }
  5948.     sptr = scratch;
  5949.  
  5950.     /* copy "`node_data", etc. anchors */
  5951.     if (bquote && *pat == bquote)
  5952.       while (*pat && *pat != '/' && *pat != bslash)
  5953.         *sptr++ = *pat++;
  5954.     else if (tilde && *pat == tilde)
  5955.       *sptr++ = *pat++;
  5956.     while (*pat == '/')
  5957.       *sptr++ = *pat++;
  5958.     if (sptr == scratch) {
  5959.         strcpy(scratch,"./");        /* safe */
  5960.         sptr = scratch+2;
  5961.     }
  5962.     if (!(head = splitpath(pat))) return(-1);
  5963.  
  5964. #else /* not aegis */
  5965.  
  5966.     debug(F111,"fgen pat",pat,len);
  5967.     debug(F110,"fgen current directory",zgtdir(),0);
  5968.     debug(F101,"fgen stathack","",stathack);
  5969.  
  5970.     scratch[0] = '\0';
  5971.     xpatwild = 0;
  5972.     xleafwild = 0;
  5973.     xpatabsolute = 0;
  5974.  
  5975.     if (!(head = splitpath(pat)))       /* Make the path segment list */
  5976.     return(-1);
  5977.  
  5978.     sptr = scratch;
  5979.  
  5980. #ifdef COMMENT
  5981.     if (strncmp(pat,"./",2) && strncmp(pat,"../",3)) {
  5982. #endif /* COMMENT */
  5983.     if (!ISDIRSEP(*pat))        /* If name is not absolute */
  5984.       *sptr++ = '.';        /* put "./" in front. */
  5985.     *sptr++ = DIRSEP;
  5986. #ifdef COMMENT
  5987.     }
  5988. #endif /* COMMENT */
  5989.     *sptr = '\0';
  5990. #endif /* aegis */
  5991.  
  5992.     makestr(&xpat,pat);                 /* Save copy of original pattern */
  5993.     debug(F110,"fgen scratch",scratch,0);
  5994.  
  5995.     for (n = 0, s = xpat; *s; s++)      /* How many slashes in the pattern */
  5996.       if (*s == DIRSEP)                 /* since these are fences for */
  5997.         n++;                            /* pattern matching */
  5998.     xpatslash = n;
  5999.     debug(F101,"fgen xpatslash","",xpatslash);
  6000.  
  6001.     numfnd = 0;                         /* None found yet */
  6002.  
  6003.     if (initspace(resarry,ssplen) < 0)
  6004.       return(-1);
  6005.  
  6006.     xpatwild = iswild(xpat);        /* Original pattern is wild? */
  6007.     xpatabsolute = isabsolute(xpat);
  6008.     xleafwild = iswild(xpatlast);
  6009.  
  6010.     debug(F111,"fgen xpat",xpat,xpatwild);
  6011.     debug(F111,"fgen xpatlast",xpatlast,xleafwild);
  6012.     debug(F101,"fgen xpatabsolute","",xpatabsolute);
  6013.  
  6014.     traverse(head,scratch,sptr);        /* Go walk the directory tree. */
  6015.     while (head != NULL) {              /* Done - free path segment list. */
  6016.         struct path *next = head -> fwd;
  6017.         free((char *)head);
  6018.         head = next;
  6019.     }
  6020.     debug(F101,"fgen","",numfnd);
  6021.     return(numfnd);                     /* Return the number of matches */
  6022. }
  6023.  
  6024. /* Define LONGFN (long file names) automatically for BSD 2.9 and 4.2 */
  6025. /* LONGFN can also be defined on the cc command line. */
  6026.  
  6027. #ifdef BSD29
  6028. #ifndef LONGFN
  6029. #define LONGFN
  6030. #endif
  6031. #endif
  6032.  
  6033. #ifdef BSD42
  6034. #ifndef LONGFN
  6035. #define LONGFN
  6036. #endif
  6037. #endif
  6038.  
  6039. /*
  6040.    T R A V E R S E  --  Traverse a directory tree.
  6041.  
  6042.    Walks the directory tree looking for matches to its arguments.
  6043.    The algorithm is, briefly:
  6044.  
  6045.     If the current pattern segment contains no wildcards, that
  6046.     segment is added to what we already have.  If the name so far
  6047.     exists, we call ourselves recursively with the next segment
  6048.     in the pattern string; otherwise, we just return.
  6049.  
  6050.     If the current pattern segment contains wildcards, we open the name
  6051.     we've accumulated so far (assuming it is really a directory), then read
  6052.     each filename in it, and, if it matches the wildcard pattern segment, add
  6053.     that filename to what we have so far and call ourselves recursively on
  6054.     the next segment.
  6055.  
  6056.     Finally, when no more pattern segments remain, we add what's accumulated
  6057.     so far to the result array and increment the number of matches.
  6058.  
  6059.   Inputs:
  6060.     A pattern path list (as generated by splitpath), a string pointer that
  6061.     points to what we've traversed so far (this can be initialized to "/"
  6062.     to start the search at the root directory, or to "./" to start the
  6063.     search at the current directory), and a string pointer to the end of
  6064.     the string in the previous argument, plus the global "recursive",
  6065.     "xmatchdot", and "xdironly" flags.
  6066.  
  6067.   Returns: void, with:
  6068.     mtchs[] containing the array of filename string pointers, and:
  6069.     numfnd containing the number of filenames.
  6070.  
  6071.   Although it might be poor practice, the mtchs[] array is revealed to the
  6072.   outside in case it needs it; for example, to be sorted prior to use.
  6073.   (It is poor practice because not all platforms implement file lists the
  6074.   same way; some don't use an array at all.)
  6075.  
  6076.   Note that addresult() acts as a second-level filter; due to selection
  6077.   criteria outside of the pattern, it might decline to add files that
  6078.   this routine asks it to, e.g. because we are collecting only directory
  6079.   names but not the names of regular files.
  6080.  
  6081.   WARNING: In the course of C-Kermit 7.0 development, this routine became
  6082.   ridiculously complex, in order to meet approximately sixty specific
  6083.   requirements.  DON'T EVEN THINK ABOUT MODIFYING THIS ROUTINE!  Trust me;
  6084.   it is not possible to fix anything in it without breaking something else.
  6085.   This routine badly needs a total redesign and rewrite.  Note: There may
  6086.   be some good applications for realpath() and/or scandir() and/or fts_blah()
  6087.   here, on platforms where they are available.
  6088. */
  6089. static VOID
  6090. traverse(pl,sofar,endcur) struct path *pl; char *sofar, *endcur; {
  6091.  
  6092. /* Appropriate declarations for directory routines and structures */
  6093. /* #define OPENDIR means to use opendir(), readdir(), closedir()  */
  6094. /* If OPENDIR not defined, we use open(), read(), close() */
  6095.  
  6096. #ifdef DIRENT                           /* New way, <dirent.h> */
  6097. #define OPENDIR
  6098.     DIR *fd, *opendir();
  6099.     struct dirent *dirbuf;
  6100.     struct dirent *readdir();
  6101. #else /* !DIRENT */
  6102. #ifdef LONGFN                           /* Old way, <dir.h> with opendir() */
  6103. #define OPENDIR
  6104.     DIR *fd, *opendir();
  6105.     struct direct *dirbuf;
  6106. #else /* !LONGFN */
  6107.     int fd;                             /* Old way, <dir.h> with open() */
  6108.     struct direct dir_entry;
  6109.     struct direct *dirbuf = &dir_entry;
  6110. #endif /* LONGFN */
  6111. #endif /* DIRENT */
  6112.     int mopts = 0;            /* ckmatch() opts */
  6113.     int depth = 0;            /* Directory tree depth */
  6114.  
  6115.     char nambuf[MAXNAMLEN+4];           /* Buffer for a filename */
  6116.     int itsadir = 0, segisdir = 0, itswild = 0, mresult, n, x /* , y */ ;
  6117.     struct stat statbuf;                /* For file info. */
  6118.  
  6119.     debug(F101,"STAT","",16);
  6120.     if (pl == NULL) {                   /* End of path-segment list */
  6121.         *--endcur = '\0'; /* Terminate string, overwrite trailing slash */
  6122.         debug(F110,"traverse add: end of path segment",sofar,0);
  6123.         addresult(sofar,-1);
  6124.         return;
  6125.     }
  6126.     if (stathack) {
  6127.     /* This speeds up the search a lot and we still get good results */
  6128.     /* but it breaks the tagging of directory names done in addresult */
  6129.     if (xrecursive || xfilonly || xdironly || xpatslash) {
  6130.         itsadir = xisdir(sofar);
  6131.         debug(F101,"STAT","",17);
  6132.     } else
  6133.       itsadir = (strncmp(sofar,"./",2) == 0);
  6134.     } else {
  6135.     itsadir = xisdir(sofar);
  6136.     debug(F101,"STAT","",18);
  6137.     }
  6138.     debug(F111,"traverse entry sofar",sofar,itsadir);
  6139.  
  6140. #ifdef CKSYMLINK                        /* We're doing symlinks? */
  6141. #ifdef USE_LSTAT                        /* OK to use lstat()? */
  6142.     if (itsadir && xnolinks) {        /* If not following symlinks */
  6143.     int x;
  6144.     struct stat buf;
  6145.     x = lstat(sofar,&buf);
  6146.     debug(F111,"traverse lstat 1",sofar,x);
  6147.     if (x > -1 &&
  6148. #ifdef S_ISLNK
  6149.         S_ISLNK(buf.st_mode)
  6150. #else
  6151. #ifdef _IFLNK
  6152.         ((_IFMT & buf.st_mode) == _IFLNK)
  6153. #endif /* _IFLNK */
  6154. #endif /* S_ISLNK */
  6155.         )
  6156.       itsadir = 0;
  6157.     }
  6158. #endif /* USE_LSTAT */
  6159. #endif /* CKSYMLINK */
  6160.  
  6161.     if (!xmatchdot && xpatlast[0] == '.')
  6162.       xmatchdot = 1;
  6163.     if (!xmatchdot && xpat[0] == '.' && xpat[1] != '/' && xpat[1] != '.')
  6164.       xmatchdot = 1;
  6165.  
  6166.     /* ckmatch() options */
  6167.  
  6168.     if (xmatchdot)   mopts |= 1;    /* Match dot */
  6169.     if (!xrecursive) mopts |= 2;    /* Dirsep is fence */
  6170.  
  6171.     debug(F111,"traverse entry xpat",xpat,xpatslash);
  6172.     debug(F111,"traverse entry xpatlast",xpatlast,xmatchdot);
  6173.     debug(F110,"traverse entry pl -> npart",pl -> npart,0);
  6174.  
  6175. #ifdef RECURSIVE
  6176.     if (xrecursive > 0 && !itsadir) {
  6177.         char * s;         /* Recursive descent and this is a regular file */
  6178.         *--endcur = '\0'; /* Terminate string, overwrite trailing slash */
  6179.  
  6180.         /* Find the nth slash from the right and match from there... */
  6181.         /* (n == the number of slashes in the original pattern - see fgen) */
  6182.         if (*sofar == '/') {
  6183.             debug(F110,"traverse xpatslash absolute",sofar,0);
  6184.             s = sofar;
  6185.         } else {
  6186.             debug(F111,"traverse xpatslash relative",sofar,xpatslash);
  6187.             for (s = endcur - 1, n = 0; s >= sofar; s--) {
  6188.                 if (*s == '/') {
  6189.                     if (++n >= xpatslash) {
  6190.                         s++;
  6191.                         break;
  6192.                     }
  6193.                 }
  6194.             }
  6195.         }
  6196. #ifndef NOSKIPMATCH
  6197.     /* This speeds things up a bit. */
  6198.     /* If it causes trouble define NOSKIPMATCH and rebuild. */
  6199.     if (xpat[0] == '*' && !xpat[1])
  6200.       x = xmatchdot ? 1 : (s[0] != '.');
  6201.     else
  6202. #endif /* NOSKIPMATCH */
  6203.       x = ckmatch(xpat, s, 1, mopts); /* Match with original pattern */
  6204.         debug(F111,"traverse xpatslash ckmatch",s,x);
  6205.         if (x > 0) {
  6206.             debug(F110,"traverse add: recursive, match, && !isdir",sofar,0);
  6207.             addresult(sofar,itsadir);
  6208.         }
  6209.         return;
  6210.     }
  6211. #endif /* RECURSIVE */
  6212.  
  6213.     debug(F111,"traverse sofar 2",sofar,0);
  6214.  
  6215.     segisdir = ((pl -> fwd) == NULL) ? 0 : 1;
  6216.     itswild = wildena ? (iswild(pl -> npart)) : 0; /* 15 Jun 2005 */
  6217.  
  6218.     debug(F111,"traverse segisdir",sofar,segisdir);
  6219.     debug(F111,"traverse itswild ",pl -> npart,itswild);
  6220.  
  6221. #ifdef RECURSIVE
  6222.     if (xrecursive > 0) {               /* If recursing and... */
  6223.         if (segisdir && itswild)        /* this is a dir and npart is wild */
  6224.           goto blah;                    /* or... */
  6225.         else if (!xpatabsolute && !xpatwild) /* search object is nonwild */
  6226.           goto blah;                    /* then go recurse */
  6227.     }
  6228. #endif /* RECURSIVE */
  6229.  
  6230.     if (!itswild) {                     /* This path segment not wild? */
  6231. #ifdef COMMENT
  6232.         strcpy(endcur,pl -> npart);     /* (safe) Append next part. */
  6233.         endcur += (int)strlen(pl -> npart); /* Advance end pointer */
  6234. #else
  6235. /*
  6236.   strcpy() does not account for quoted metacharacters.
  6237.   We must remove the quotes before doing the stat().
  6238. */
  6239.     {
  6240.         int quote = 0;
  6241.         char c, * s;
  6242.         s = pl -> npart;
  6243.         while ((c = *s++)) {
  6244.         if (!quote) {
  6245.             if (c == CMDQ) {
  6246.             quote = 1;
  6247.             continue;
  6248.             }
  6249.         }
  6250.         *endcur++ = c;
  6251.         quote = 0;
  6252.         }
  6253.     }
  6254. #endif /* COMMENT */
  6255.         *endcur = '\0';                 /* End new current string. */
  6256.  
  6257.         if (stat(sofar,&statbuf) == 0) { /* If this piece exists... */
  6258.             debug(F110,"traverse exists",sofar,0);
  6259.             *endcur++ = DIRSEP;         /* add slash to end */
  6260.             *endcur = '\0';             /* and end the string again. */
  6261.             traverse(pl -> fwd, sofar, endcur);
  6262.         }
  6263. #ifdef DEBUG
  6264.         else debug(F110,"traverse not found", sofar, 0);
  6265. #endif /* DEBUG */
  6266.         return;
  6267.     }
  6268.  
  6269.     *endcur = '\0';                     /* End current string */
  6270.     debug(F111,"traverse sofar 3",sofar,0);
  6271.  
  6272.     if (!itsadir)
  6273.       return;
  6274.  
  6275.     /* Search is recursive or ... */
  6276.     /* path segment contains wildcards, have to open and search directory. */
  6277.  
  6278.   blah:
  6279.  
  6280.     debug(F110,"traverse opening directory", sofar, 0);
  6281.  
  6282. #ifdef OPENDIR
  6283.     debug(F110,"traverse opendir()",sofar,0);
  6284.     if ((fd = opendir(sofar)) == NULL) {        /* Can't open, fail. */
  6285.         debug(F101,"traverse opendir() failed","",errno);
  6286.         return;
  6287.     }
  6288.     while ((dirbuf = readdir(fd)))
  6289. #else /* !OPENDIR */
  6290.     debug(F110,"traverse directory open()",sofar,0);
  6291.     if ((fd = open(sofar,O_RDONLY)) < 0) {
  6292.         debug(F101,"traverse directory open() failed","",errno);
  6293.         return;
  6294.     }
  6295.     while (read(fd, (char *)dirbuf, sizeof dir_entry) > 0)
  6296. #endif /* OPENDIR */
  6297.       {                         /* Read each entry in this directory */
  6298.           int exists;
  6299.           char *eos, *s;
  6300.           exists = 0;
  6301.  
  6302.           /* On some platforms, the read[dir]() can return deleted files, */
  6303.           /* e.g. HP-UX 5.00.  There is no point in grinding through this */
  6304.           /* routine when the file doesn't exist... */
  6305.  
  6306.           if (          /* There  actually is an inode... */
  6307. #ifdef BSD42
  6308.                          dirbuf->d_ino != -1
  6309. #else
  6310. #ifdef unos
  6311.                          dirbuf->d_ino != -1
  6312. #else
  6313. #ifdef QNX
  6314.                          dirbuf->d_stat.st_ino != 0
  6315. #else
  6316. #ifdef SOLARIS
  6317.                          dirbuf->d_ino != 0
  6318. #else
  6319. #ifdef sun
  6320.                          dirbuf->d_fileno != 0
  6321. #else
  6322. #ifdef bsdi
  6323.                          dirbuf->d_fileno != 0
  6324. #else
  6325. #ifdef __386BSD__
  6326.                          dirbuf->d_fileno != 0
  6327. #else
  6328. #ifdef __FreeBSD__
  6329.                          dirbuf->d_fileno != 0
  6330. #else
  6331. #ifdef ultrix
  6332.                          dirbuf->gd_ino != 0
  6333. #else
  6334. #ifdef Plan9
  6335.                          1
  6336. #else
  6337.                          dirbuf->d_ino != 0
  6338. #endif /* Plan9 */
  6339. #endif /* ultrix */
  6340. #endif /* __FreeBSD__ */
  6341. #endif /* __386BSD__ */
  6342. #endif /* bsdi */
  6343. #endif /* sun */
  6344. #endif /* SOLARIS */
  6345. #endif /* QNX */
  6346. #endif /* unos */
  6347. #endif /* BSD42 */
  6348.               )
  6349.             exists = 1;
  6350.           if (!exists)
  6351.             continue;
  6352.  
  6353.           ckstrncpy(nambuf,             /* Copy the name */
  6354.                   dirbuf->d_name,
  6355.                   MAXNAMLEN
  6356.                   );
  6357.           if (nambuf[0] == '.') {
  6358.               if (!nambuf[1] || (nambuf[1] == '.' && !nambuf[2])) {
  6359.                   debug(F110,"traverse skipping",nambuf,0);
  6360.                   continue;             /* skip "." and ".." */
  6361.               }
  6362.           }
  6363.           s = nambuf;                   /* Copy name to end of sofar */
  6364.           eos = endcur;
  6365.           while ((*eos = *s)) {
  6366.               s++;
  6367.               eos++;
  6368.           }
  6369. /*
  6370.   Now we check the file for (a) whether it is a directory, and (b) whether
  6371.   its name matches our pattern.  If it is a directory, and if we have been
  6372.   told to build a recursive list, then we must descend regardless of whether
  6373.   it matches the pattern.  If it is not a directory and it does not match
  6374.   our pattern, we skip it.  Note: sofar is the full pathname, nambuf is
  6375.   the name only.
  6376. */
  6377.           /* Do this first to save pointless function calls */
  6378.           if (nambuf[0] == '.' && !xmatchdot) /* Dir name starts with '.' */
  6379.             continue;
  6380.       if (stathack) {
  6381.           if (xrecursive || xfilonly || xdironly || xpatslash) {
  6382.           itsadir = xisdir(sofar); /* See if it's a directory */
  6383.           debug(F101,"STAT","",19);
  6384.           } else {
  6385.           itsadir = 0;
  6386.           }
  6387.       } else {
  6388.           itsadir = xisdir(sofar);
  6389.           debug(F101,"STAT","",20);
  6390.       }
  6391.  
  6392. #ifdef CKSYMLINK
  6393. #ifdef USE_LSTAT
  6394.       if (itsadir && xnolinks) {        /* If not following symlinks */
  6395.           int x;
  6396.           struct stat buf;
  6397.           x = lstat(sofar,&buf);
  6398.           debug(F111,"traverse lstat 2",sofar,x);
  6399.           if (x > -1 &&
  6400. #ifdef S_ISLNK
  6401.           S_ISLNK(buf.st_mode)
  6402. #else
  6403. #ifdef _IFLNK
  6404.           ((_IFMT & buf.st_mode) == _IFLNK)
  6405. #endif /* _IFLNK */
  6406. #endif /* S_ISLNK */
  6407.           )
  6408.         itsadir = 0;
  6409.       }
  6410. #endif /* USE_LSTAT */
  6411. #endif /* CKSYMLINK */
  6412.  
  6413. #ifdef RECURSIVE
  6414.           if (xrecursive > 0 && itsadir &&
  6415.               (xpatlast[0] == '*') && !xpatlast[1]
  6416.               ) {
  6417.               debug(F110,
  6418.                     "traverse add: recursive && isdir && segisdir or match",
  6419.                     sofar,
  6420.                     segisdir
  6421.                     );
  6422.           addresult(sofar,itsadir);
  6423.           if (numfnd < 0) return;
  6424.           }
  6425. #endif /* RECURSIVE */
  6426.  
  6427.           debug(F111,"traverse mresult xpat",xpat,xrecursive);
  6428.           debug(F111,"traverse mresult pl -> npart",
  6429.                 pl -> npart,
  6430.                 ((pl -> fwd) ? 9999 : 0)
  6431.                 );
  6432.           debug(F111,"traverse mresult sofar segisdir",sofar,segisdir);
  6433.           debug(F111,"traverse mresult sofar itsadir",sofar,itsadir);
  6434.           debug(F101,"traverse mresult xmatchdot","",xmatchdot);
  6435. /*
  6436.   Match the path so far with the pattern after stripping any leading "./"
  6437.   from either or both.  The pattern chosen is the full original pattern if
  6438.   the match candidate (sofar) is not a directory, or else just the name part
  6439.   (pl->npart) if it is.
  6440. */
  6441.       {
  6442.           char * s1;        /* The pattern */
  6443.           char * s2 = sofar;    /* The path so far */
  6444.           char * s3;        /* Worker */
  6445.           int opts;            /* Match options */
  6446.  
  6447.           s1 = itsadir ? pl->npart : xpat;
  6448.  
  6449. #ifndef COMMENT
  6450.           /* I can't explain this but it unbreaks "cd blah/sub<Esc>" */
  6451.           if (itsadir && !xrecursive && xpatslash > 0 &&
  6452.           segisdir == 0 && itswild) {
  6453.           s1 = xpat;
  6454.           debug(F110,"traverse mresult s1 kludge",s1,0);
  6455.           }
  6456. #endif /* COMMENT */
  6457.  
  6458.           if (xrecursive && xpatslash == 0)
  6459.         s2 = nambuf;
  6460.           while ((s1[0] == '.') && (s1[1] == '/')) /* Strip "./" */
  6461.         s1 += 2;
  6462.           while ((s2[0] == '.') && (s2[1] == '/')) /* Ditto */
  6463.         s2 += 2;
  6464.           opts = mopts;        /* Match options */
  6465.           if (itsadir)         /* Current segment is a directory */
  6466.         opts = mopts & 1;    /* No fences */
  6467.           s3 = s2;            /* Get segment depth */
  6468.           depth = 0;
  6469.           while (*s3) { if (*s3++ == '/') depth++; }
  6470. #ifndef NOSKIPMATCH
  6471.           /* This speeds things up a bit. */
  6472.           /* If it causes trouble define NOSKIPMATCH and rebuild. */
  6473.           if (depth == 0 && (s1[0] == '*') && !s1[1])
  6474.         mresult = xmatchdot ? 1 : (s2[0] != '.');
  6475.           else
  6476. #endif /* NOSKIPMATCH */
  6477.         mresult = ckmatch(s1,s2,1,opts); /* Match */
  6478.       }
  6479. #ifdef DEBUG
  6480.       if (deblog) {
  6481.           debug(F111,"traverse mresult depth",sofar,depth);
  6482.           debug(F101,"traverse mresult xpatslash","",xpatslash);
  6483.           debug(F111,"traverse mresult nambuf",nambuf,mresult);
  6484.           debug(F111,"traverse mresult itswild",pl -> npart,itswild);
  6485.           debug(F111,"traverse mresult segisdir",pl -> npart,segisdir);
  6486.       }
  6487. #endif /* DEBUG */
  6488.           if (mresult ||        /* If match succeeded */
  6489.           xrecursive ||        /* Or search is recursive */
  6490.           depth < xpatslash        /* Or not deep enough to match... */
  6491.           ) {
  6492.               if (                      /* If it's not a directory... */
  6493. /*
  6494.   The problem here is that segisdir is apparently not set appropriately.
  6495.   If I leave in the !segisdir test, then "dir /recursive blah" (where blah is
  6496.   a directory name) misses some regular files because sometimes segisdir
  6497.   is set and sometimes it's not.  But if I comment it out, then
  6498.   "dir <star>/<star>.txt lists every file in * and does not even open up the
  6499.   subdirectories.  However, "dir /rec <star>/<star>.txt" works right.
  6500. */
  6501. #ifdef COMMENT
  6502.                   mresult && (!itsadir && !segisdir)
  6503. #else
  6504.                   mresult &&        /* Matched */
  6505.                   !itsadir &&        /* sofar is not a directory */
  6506.                   ((!xrecursive && !segisdir) || xrecursive)
  6507. #endif /* COMMENT */
  6508.                   ) {
  6509.           debug(F110,
  6510.             "traverse add: match && !itsadir",sofar,0);
  6511.           addresult(sofar,itsadir);
  6512.           if (numfnd < 0) return;
  6513.               } else if (itsadir && (xrecursive || mresult)) {
  6514.                   struct path * xx = NULL;
  6515.                   *eos++ = DIRSEP;      /* Add directory separator */
  6516.                   *eos = '\0';          /* to end of segment */
  6517. #ifdef RECURSIVE
  6518.                   /* Copy previous pattern segment to this new directory */
  6519.  
  6520.                   if (xrecursive > 0 && !(pl -> fwd)) {
  6521.                       xx = (struct path *) malloc(sizeof (struct path));
  6522.                       pl -> fwd = xx;
  6523.                       if (xx) {
  6524.                           xx -> fwd = NULL;
  6525.                           strcpy(xx -> npart, pl -> npart); /* safe */
  6526.                       }
  6527.                   }
  6528. #endif /* RECURSIVE */
  6529.                   traverse(pl -> fwd, sofar, eos); /* Traverse new directory */
  6530.               }
  6531.           }
  6532.       }
  6533. #ifdef OPENDIR
  6534.     closedir(fd);
  6535. #else /* !OPENDIR */
  6536.     close(fd);
  6537. #endif /* OPENDIR */
  6538. }
  6539.  
  6540. /*
  6541.  * addresult:
  6542.  *  Adds a result string to the result array.  Increments the number
  6543.  *  of matches found, copies the found string into our string
  6544.  *  buffer, and puts a pointer to the buffer into the caller's result
  6545.  *  array.  Our free buffer pointer is updated.  If there is no
  6546.  *  more room in the caller's array, the number of matches is set to -1.
  6547.  * Input: a result string.
  6548.  * Returns: nothing.
  6549.  */
  6550. static VOID
  6551. addresult(str,itsadir) char *str; int itsadir; {
  6552.     int len;
  6553.  
  6554.     if (!freeptr) {
  6555.     debug(F100,"addresult string space not init'd","",0);
  6556.     initspace(mtchs,ssplen);
  6557.     }
  6558.     if (!str) str = "";
  6559.     debug(F111,"addresult",str,itsadir);
  6560.     if (!*str)
  6561.       return;
  6562.  
  6563.     if (itsadir < 0) {
  6564.     itsadir = xisdir(str);
  6565.     }
  6566.     if ((xdironly && !itsadir) || (xfilonly && itsadir)) {
  6567.         debug(F111,"addresult skip",str,itsadir);
  6568.         return;
  6569.     }
  6570.     while (str[0] == '.' && ISDIRSEP(str[1])) /* Strip all "./" from front */
  6571.       str += 2;
  6572.     if (--remlen < 0) {                 /* Elements left in array of names */
  6573.         debug(F111,"addresult ARRAY FULL",str,numfnd);
  6574.         numfnd = -1;
  6575.         return;
  6576.     }
  6577.     len = (int)strlen(str);        /* Space this will use */
  6578.     debug(F111,"addresult len",str,len);
  6579.  
  6580.     if (len < 1)
  6581.       return;
  6582.  
  6583.     if ((freeptr + len + itsadir + 1) > (sspace + ssplen)) {
  6584.         debug(F111,"addresult OUT OF SPACE",str,numfnd);
  6585. #ifdef DYNAMIC
  6586.     printf(
  6587. "?String space %d exhausted - use SET FILE STRINGSPACE to increase\n",ssplen);
  6588. #else
  6589.     printf("?String space %d exhausted\n",ssplen);
  6590. #endif /* DYNAMIC */
  6591.         numfnd = -1;                    /* Do not record if not enough space */
  6592.         return;
  6593.     }
  6594.     strcpy(freeptr,str);        /* safe */
  6595.  
  6596.     /* Tag directory names by putting '/' at the end */
  6597.  
  6598.     if (itsadir && (freeptr[len-1] == '/')) {
  6599.         freeptr[len++] = DIRSEP;
  6600.         freeptr[len] = '\0';
  6601.     }
  6602.     if (numfnd >= maxnames) {
  6603. #ifdef DYNAMIC
  6604.     printf(
  6605. "?Too many files (%d max) - use SET FILE LISTSIZE to increase\n",maxnames);
  6606. #else
  6607.     printf("?Too many files - %d max\n",maxnames);
  6608. #endif /* DYNAMIC */
  6609.         numfnd = -1;
  6610.         return;
  6611.     }
  6612.     str = freeptr;
  6613.     *resptr++ = freeptr;
  6614.     freeptr += (len + 1);
  6615.     numfnd++;
  6616.     debug(F111,"addresult ADD",str,numfnd);
  6617. }
  6618.  
  6619. #ifdef COMMENT
  6620. /*
  6621.  * match(pattern,string):
  6622.  *  pattern matcher.  Takes a string and a pattern possibly containing
  6623.  *  the wildcard characters '*' and '?'.  Returns true if the pattern
  6624.  *  matches the string, false otherwise.
  6625.  * Orignally by: Jeff Damens, CUCCA, 1984
  6626.  * No longer used as of C-Kermit 7.0, now we use ckmatch() instead (ckclib.c).
  6627.  *
  6628.  * Input: a string and a wildcard pattern.
  6629.  * Returns: 1 if match, 0 if no match.
  6630.  */
  6631. static int
  6632. match(pattern, string) char *pattern, *string; {
  6633.     char *psave = NULL, *ssave = NULL;  /* Backup pointers for failure */
  6634.     int q = 0;                          /* Quote flag */
  6635.  
  6636.     if (*string == '.' && *pattern != '.' && !xmatchdot) {
  6637.         debug(F110,"match skip",string,0);
  6638.         return(0);
  6639.     }
  6640.     while (1) {
  6641.         for (; *pattern == *string; pattern++,string++) /* Skip first */
  6642.           if (*string == '\0') return(1); /* End of strings, succeed */
  6643.  
  6644.         if (*pattern == '\\' && q == 0) { /* Watch out for quoted */
  6645.             q = 1;                      /* metacharacters */
  6646.             pattern++;                  /* advance past quote */
  6647.             if (*pattern != *string) return(0);
  6648.             continue;
  6649.         } else q = 0;
  6650.  
  6651.         if (q) {
  6652.             return(0);
  6653.         } else {
  6654.             if (*string != '\0' && *pattern == '?') {
  6655.                 pattern++;              /* '?', let it match */
  6656.                 string++;
  6657.             } else if (*pattern == '*') { /* '*' ... */
  6658.                 psave = ++pattern;      /* remember where we saw it */
  6659.                 ssave = string;         /* let it match 0 chars */
  6660.             } else if (ssave != NULL && *ssave != '\0') { /* if not at end  */
  6661.                                         /* ...have seen a star */
  6662.                 string = ++ssave;       /* skip 1 char from string */
  6663.                 pattern = psave;        /* and back up pattern */
  6664.             } else return(0);           /* otherwise just fail */
  6665.         }
  6666.     }
  6667. }
  6668. #endif /* COMMENT */
  6669.  
  6670. /*
  6671.   The following two functions are for expanding tilde in filenames
  6672.   Contributed by Howie Kaye, CUCCA, developed for CCMD package.
  6673. */
  6674.  
  6675. /*  W H O A M I  --  Get user's username.  */
  6676.  
  6677. /*
  6678.   1) Get real uid
  6679.   2) See if the $USER environment variable is set ($LOGNAME on AT&T)
  6680.   3) If $USER's uid is the same as ruid, realname is $USER
  6681.   4) Otherwise get logged in user's name
  6682.   5) If that name has the same uid as the real uid realname is loginname
  6683.   6) Otherwise, get a name for ruid from /etc/passwd
  6684. */
  6685. char *
  6686. whoami() {
  6687. #ifdef DTILDE
  6688. #ifdef pdp11
  6689. #define WHOLEN 100
  6690. #else
  6691. #define WHOLEN 257
  6692. #endif /* pdp11 */
  6693.     static char realname[UIDBUFLEN+1];  /* user's name */
  6694.     static int ruid = -1;               /* user's real uid */
  6695.     char loginname[UIDBUFLEN+1], envname[256]; /* temp storage */
  6696.     char *c;
  6697.     struct passwd *p;
  6698.     _PROTOTYP(extern char * getlogin, (void) );
  6699.  
  6700.     debug(F111,"whoami ruid A",realname,ruid);
  6701.  
  6702.     if (ruid != -1)
  6703.       return(realname);
  6704.  
  6705.     ruid = real_uid();                  /* get our uid */
  6706.     debug(F101,"whoami ruid B","",ruid);
  6707.     if (ruid < 0) ruid = getuid();
  6708.     debug(F101,"whoami ruid C","",ruid);
  6709.  
  6710.   /* how about $USER or $LOGNAME? */
  6711.     if ((c = getenv(NAMEENV)) != NULL) { /* check the env variable */
  6712.         ckstrncpy(envname, c, 255);
  6713.     debug(F110,"whoami envname",envname,0);
  6714.         if ((p = getpwnam(envname)) != NULL) {
  6715.             if (p->pw_uid == ruid) {    /* get passwd entry for envname */
  6716.                 ckstrncpy(realname, envname, UIDBUFLEN); /* uid's are same */
  6717.         debug(F110,"whoami realname",realname,0);
  6718.                 return(realname);
  6719.             }
  6720.         }
  6721.     }
  6722.  
  6723.   /* can we use loginname() ? */
  6724.  
  6725.     if ((c =  getlogin()) != NULL) {    /* name from utmp file */
  6726.         ckstrncpy (loginname, c, UIDBUFLEN);
  6727.     debug(F110,"whoami loginname",loginname,0); 
  6728.         if ((p = getpwnam(loginname)) != NULL) /* get passwd entry */
  6729.           if (p->pw_uid == ruid)        /* for loginname */
  6730.             ckstrncpy(realname, envname, UIDBUFLEN); /* if uid's are same */
  6731.     }
  6732.  
  6733.   /* Use first name we get for ruid */
  6734.  
  6735.     if ((p = getpwuid(ruid)) == NULL) { /* name for uid */
  6736.     debug(F101,"whoami no username for ruid","",ruid); 
  6737.         realname[0] = '\0';             /* no user name */
  6738.         ruid = -1;
  6739.         return(NULL);
  6740.     }
  6741.     ckstrncpy(realname, p->pw_name, UIDBUFLEN);
  6742.     debug(F110,"whoami realname from getpwuid",realname,0);
  6743.     return(realname);
  6744. #else
  6745.     return(NULL);
  6746. #endif /* DTILDE */
  6747. }
  6748.  
  6749. /*  T I L D E _ E X P A N D  --  expand ~user to the user's home directory. */
  6750.  
  6751. char *
  6752. tilde_expand(dirname) char *dirname; {
  6753. #ifdef DTILDE
  6754. #ifdef pdp11
  6755. #define BUFLEN 100
  6756. #else
  6757. #define BUFLEN 257
  6758. #endif /* pdp11 */
  6759.     struct passwd *user;
  6760.     static char olddir[BUFLEN+1];
  6761.     static char oldrealdir[BUFLEN+1];
  6762.     static char temp[BUFLEN+1];
  6763.     int i, j;
  6764.  
  6765.     debug(F111,"tilde_expand",dirname,dirname[0]);
  6766.  
  6767.     if (dirname[0] != '~') {              /* Not a tilde...return param */
  6768.     debug(F000,"tilde_expand NOT TILDE","",dirname[0]);
  6769.     return(dirname);
  6770.     }
  6771.     if (!strcmp(olddir,dirname)) {      /* Same as last time */
  6772.     debug(F110,"tilde_expand same as previous",oldrealdir,0);
  6773.     return(oldrealdir);               /* so return old answer. */
  6774.     } else {
  6775.     debug(F110,"tilde_expand working...","",0);
  6776.         j = (int)strlen(dirname);
  6777.         for (i = 0; i < j; i++)         /* find username part of string */
  6778.           if (!ISDIRSEP(dirname[i]))
  6779.             temp[i] = dirname[i];
  6780.           else break;
  6781.         temp[i] = '\0';                 /* tie off with a NULL */
  6782.     debug(F111,"tilde_expand first part",temp,i);
  6783.         if (i == 1) {                   /* if just a "~" */
  6784. #ifdef IKSD
  6785.             if (inserver)
  6786.               user = getpwnam(uidbuf);  /* Get info on current user */
  6787.             else
  6788. #endif /* IKSD */
  6789.             {
  6790.                 char * p = whoami();
  6791.         debug(F110,"tilde_expand p",p,0);
  6792.                 if (p) {
  6793.             user = getpwnam(p);
  6794.             debug(F110,"tilde_expand getpwpam ~",user,0);
  6795.         } else {
  6796.             user = NULL;
  6797.         }
  6798.             }
  6799.         } else {
  6800.         debug(F110,"tilde_expand ~user",&temp[1],0);
  6801.             user = getpwnam(&temp[1]);  /* otherwise on the specified user */
  6802.         debug(F110,"tilde_expand getpwpam user",user,0);
  6803.         }
  6804.  
  6805.     }
  6806.     if (user != NULL) {                 /* valid user? */
  6807.         ckstrncpy(olddir, dirname, BUFLEN); /* remember the directory */
  6808.         ckstrncpy(oldrealdir,user->pw_dir, BUFLEN); /* and home directory */
  6809.         ckstrncat(oldrealdir,&dirname[i], BUFLEN);
  6810.         oldrealdir[BUFLEN] = '\0';
  6811.         return(oldrealdir);
  6812.     } else {                            /* invalid? */
  6813.         ckstrncpy(olddir, dirname, BUFLEN); /* remember for next time */
  6814.         ckstrncpy(oldrealdir, dirname, BUFLEN);
  6815.         return(oldrealdir);
  6816.     }
  6817. #else
  6818.     return(NULL);
  6819. #endif /* DTILDE */
  6820. }
  6821.  
  6822. /*
  6823.   Functions for executing system commands.
  6824.   zsyscmd() executes the system command in the normal, default way for
  6825.   the system.  In UNIX, it does what system() does.  Thus, its results
  6826.   are always predictable.
  6827.   zshcmd() executes the command using the user's preferred shell.
  6828. */
  6829. int
  6830. zsyscmd(s) char *s; {
  6831. #ifdef aegis
  6832.     if (nopush) return(-1);
  6833.     if (!priv_chk()) return(system(s));
  6834. #else
  6835.     PID_T shpid;
  6836. #ifdef COMMENT
  6837. /* This doesn't work... */
  6838.     WAIT_T status;
  6839. #else
  6840.     int status;
  6841. #endif /* COMMENT */
  6842.  
  6843.     if (nopush) return(-1);
  6844.     if ((shpid = fork())) {
  6845.         if (shpid < (PID_T)0) return(-1); /* Parent */
  6846.         while (shpid != (PID_T) wait(&status))
  6847.          ;
  6848.         return(status);
  6849.     }
  6850.     if (priv_can()) {                   /* Child: cancel any priv's */
  6851.         printf("?Privilege cancellation failure\n");
  6852.         _exit(255);
  6853.     }
  6854.     restorsigs();            /* Restore ignored signals */
  6855. #ifdef HPUX10
  6856.     execl("/usr/bin/sh","sh","-c",s,NULL);
  6857.     perror("/usr/bin/sh");
  6858. #else
  6859. #ifdef Plan9
  6860.     execl("/bin/rc", "rc", "-c", s, NULL);
  6861.     perror("/bin/rc");
  6862. #else
  6863.     execl("/bin/sh","sh","-c",s,NULL);
  6864.     perror("/bin/sh");
  6865. #endif /* Plan9 */
  6866. #endif /* HPUX10 */
  6867.     _exit(255);
  6868.     return(0);                          /* Shut up ANSI compilers. */
  6869. #endif /* aegis */
  6870. }
  6871.  
  6872.  
  6873. /*  Z _ E X E C  --  Overlay ourselves with another program  */
  6874.  
  6875. #ifndef NOZEXEC
  6876. #ifdef HPUX5
  6877. #define NOZEXEC
  6878. #else
  6879. #ifdef ATT7300
  6880. #define NOZEXEC
  6881. #endif /* ATT7300 */
  6882. #endif /* HPUX5 */
  6883. #endif /* NOZEXEC */
  6884.  
  6885. VOID
  6886. z_exec(p,s,t) char * p, ** s; int t; {  /* Overlay ourselves with "p s..." */
  6887. #ifdef NOZEXEC
  6888.     printf("EXEC /REDIRECT NOT IMPLEMENTED IN THIS VERSION OF C-KERMIT\n");
  6889.     debug(F110,"z_exec NOT IMPLEMENTED",p,0);
  6890. #else
  6891.     int x;
  6892.     extern int ttyfd;
  6893.     debug(F110,"z_exec command",p,0);
  6894.     debug(F110,"z_exec arg 0",s[0],0);
  6895.     debug(F110,"z_exec arg 1",s[1],0);
  6896.     debug(F101,"z_exec t","",t);
  6897.     errno = 0;
  6898.     if (t) {
  6899.         if (ttyfd > 2) {
  6900.             dup2(ttyfd, 0);
  6901.             dup2(ttyfd, 1);
  6902.             /* dup2(ttyfd, 2); */
  6903.             close(ttyfd);
  6904.         }
  6905.     }
  6906.     restorsigs();            /* Restore ignored signals */
  6907.     x = execvp(p,s);
  6908.     if (x < 0) debug(F101,"z_exec errno","",errno);
  6909. #endif /* NOZEXEC */
  6910. }
  6911.  
  6912. /*
  6913.   Z S H C M D  --  Execute a shell command (or program thru the shell).
  6914.  
  6915.   Original UNIX code by H. Fischer; copyright rights assigned to Columbia U.
  6916.   Adapted to use getpwuid to find login shell because many systems do not
  6917.   have SHELL in environment, and to use direct calling of shell rather
  6918.   than intermediate system() call. -- H. Fischer (1985); many changes since
  6919.   then.  Call with s pointing to command to execute.  Returns:
  6920.    -1 on failure to start the command (can't find, can't fork, can't run).
  6921.     1 if command ran and gave an exit status of 0.
  6922.     0 if command ran and gave a nonzero exit status.
  6923.   with pexitstatus containing the command's exit status.
  6924. */
  6925. int
  6926. zshcmd(s) char *s; {
  6927.     PID_T pid;
  6928.  
  6929. #ifdef NOPUSH
  6930.     return(0);
  6931. #else
  6932.     if (nopush) return(-1);
  6933.     if (!s) return(-1);
  6934.     while (*s == ' ') s++;
  6935.  
  6936.     debug(F110,"zshcmd command",s,0);
  6937.  
  6938. #ifdef aegis
  6939.     if ((pid = vfork()) == 0) {         /* Make child quickly */
  6940.         char *shpath, *shname, *shptr;  /* For finding desired shell */
  6941.  
  6942.         if (priv_can()) exit(1);        /* Turn off privs. */
  6943.         if ((shpath = getenv("SHELL")) == NULL) shpath = "/com/sh";
  6944.  
  6945. #else                                   /* All Unix systems */
  6946.     if ((pid = fork()) == 0) {          /* Make child */
  6947.         char *shpath, *shname, *shptr;  /* For finding desired shell */
  6948.         struct passwd *p;
  6949. #ifdef HPUX10                           /* Default */
  6950.         char *defshell = "/usr/bin/sh";
  6951. #else
  6952. #ifdef Plan9
  6953.         char *defshell = "/bin/rc";
  6954. #else
  6955.         char *defshell = "/bin/sh";
  6956. #endif /* Plan9 */
  6957. #endif /* HPUX10 */
  6958.         if (priv_can()) exit(1);        /* Turn off privs. */
  6959. #ifdef COMMENT
  6960. /* Old way always used /etc/passwd shell */
  6961.         p = getpwuid(real_uid());       /* Get login data */
  6962.         if (p == (struct passwd *) NULL || !*(p->pw_shell))
  6963.           shpath = defshell;
  6964.         else
  6965.           shpath = p->pw_shell;
  6966. #else
  6967. /* New way lets user override with SHELL variable, but does not rely on it. */
  6968. /* This allows user to specify a different shell. */
  6969.         shpath = getenv("SHELL");       /* What shell? */
  6970.     debug(F110,"zshcmd SHELL",shpath,0);
  6971.     {
  6972.         int x = 0;
  6973.         if (!shpath) {
  6974.         x++;
  6975.         } else if (!*shpath) {
  6976.         x++;
  6977.         }
  6978.         if (x) {
  6979.         debug(F100,"zshcmd SHELL not defined","",0);
  6980.         p = getpwuid( real_uid() ); /* Get login data */
  6981.         if (p == (struct passwd *)NULL || !*(p->pw_shell)) {
  6982.             shpath = defshell;
  6983.         } else {
  6984.             shpath = p->pw_shell;
  6985.         }
  6986.         debug(F110,"zshcmd shpath from getpwuid",shpath,0);
  6987.         }
  6988.         }
  6989. #endif /* COMMENT */
  6990. #endif /* aegis */
  6991.         shptr = shname = shpath;
  6992.         while (*shptr != '\0')
  6993.           if (*shptr++ == DIRSEP)
  6994.             shname = shptr;
  6995.     restorsigs();            /* Restore ignored signals */
  6996.     debug(F110,"zshcmd execl shpath",shpath,0);
  6997.     debug(F110,"zshcmd execl shname",shname,0);
  6998.         if (s == NULL || *s == '\0') {  /* Interactive shell requested? */
  6999.         debug(F100,"zshcmd execl interactive","",0);
  7000.             execl(shpath,shname,"-i",NULL); /* Yes, do that */
  7001.         } else {                        /* Otherwise, */
  7002.         debug(F110,"zshcmd execl command",s,0);
  7003.             execl(shpath,shname,"-c",s,NULL); /* exec the given command */
  7004.         }                               /* If execl() failed, */
  7005.         debug(F101,"zshcmd errno","",errno);
  7006.     perror(shpath);            /* print reason and */
  7007.         exit(BAD_EXIT);                 /* return bad return code. */
  7008.  
  7009.     } else {                            /* Parent */
  7010.  
  7011.         int wstat;                      /* ... must wait for child */
  7012. #ifdef CK_CHILD
  7013.         int child;                      /* Child's exit status */
  7014. #endif /* CK_CHILD */
  7015.         SIGTYP (*istat)(), (*qstat)();
  7016.  
  7017.         if (pid == (PID_T) -1) return(-1); /* fork() failed? */
  7018.  
  7019.         istat = signal(SIGINT,SIG_IGN); /* Let the fork handle keyboard */
  7020.         qstat = signal(SIGQUIT,SIG_IGN); /* interrupts itself... */
  7021.  
  7022.     debug(F110,"zshcmd parent waiting for child",s,0);
  7023. #ifdef CK_CHILD
  7024.         while (((wstat = wait(&child)) != pid) && (wstat != -1))
  7025. #else
  7026.         while (((wstat = wait((WAIT_T *)0)) != pid) && (wstat != -1))
  7027. #endif /* CK_CHILD */
  7028.           ;                             /* Wait for fork */
  7029.         signal(SIGINT,istat);           /* Restore interrupts */
  7030.         signal(SIGQUIT,qstat);
  7031. #ifdef CK_CHILD
  7032.         pexitstat = (child & 0xff) ? child : child >> 8;
  7033.     debug(F101,"zshcmd exit status","",pexitstat);
  7034.         return(child == 0 ? 1 : 0);     /* Return child's status */
  7035. #endif /* CK_CHILD */
  7036.     }
  7037.     return(1);
  7038. #endif /* NOPUSH */
  7039. }
  7040.  
  7041. /*  I S W I L D  --  Check if filespec is "wild"  */
  7042.  
  7043. /*
  7044.   Returns:
  7045.     0 wildcards disabled or argument is empty or is the name of a single file;
  7046.     1 if it contains wildcard characters.
  7047.   Note: must match the algorithm used by match(), hence no [a-z], etc.
  7048. */
  7049. int
  7050. iswild(filespec) char *filespec; {
  7051.     char c, *p, *f; int x;
  7052.     int quo = 0;
  7053.     if (!filespec)            /* Safety */
  7054.       return(0);
  7055.     if (!wildena)            /* Wildcards disabled - 12 Jun 2005 */
  7056.       return(0);
  7057.     f = filespec;
  7058.     if (wildxpand) {            /* Shell handles wildcarding */
  7059.         if ((x = nzxpand(filespec,0)) > 1)
  7060.           return(1);
  7061.         if (x == 0) return(0);          /* File does not exist */
  7062.         p = malloc(MAXNAMLEN + 20);
  7063.         znext(p);
  7064.         x = (strcmp(filespec,p) != 0);
  7065.         free(p);
  7066.         p = NULL;
  7067.         return(x);
  7068.     } else {                /* We do it ourselves */
  7069.         while ((c = *filespec++) != '\0') {
  7070.             if (c == '\\' && quo == 0) {
  7071.                 quo = 1;
  7072.                 continue;
  7073.             }
  7074.             if (!quo && (c == '*' || c == '?'
  7075. #ifdef CKREGEX
  7076. #ifndef VMS
  7077.                          || c == '['
  7078. #endif /* VMS */
  7079.              || c == '{'
  7080. #endif /* CKREGEX */
  7081.                          )) {
  7082.         debug(F111,"iswild",f,1);
  7083.         return(1);
  7084.         }
  7085.             quo = 0;
  7086.         }
  7087.     debug(F111,"iswild",f,0);
  7088.         return(0);
  7089.     }
  7090. }
  7091.  
  7092. /*
  7093.   I S D I R  --  Is a Directory.
  7094.  
  7095.   Tell if string pointer s is the name of an existing directory.  Returns 1 if
  7096.   directory, 0 if not a directory.
  7097.  
  7098.   The following no longer applies:
  7099.  
  7100.   If the file is a symlink, we return 1 if
  7101.   it is a directory OR if it is a link to a directory and the "xrecursive" flag
  7102.   is NOT set.  This is to allow parsing a link to a directory as if it were a
  7103.   directory (e.g. in the CD or IF DIRECTORY command) but still prevent
  7104.   recursive traversal from visiting the same directory twice.
  7105. */
  7106.  
  7107. #ifdef ISDIRCACHE
  7108. /* This turns out to be unsafe and gives little benefit anyway. */
  7109. /* See notes 28 Sep 2003.  Thus ISDIRCACHE is not defined. */
  7110.  
  7111. static char prevpath[CKMAXPATH+4] = { '\0', '\0' };
  7112. static int prevstat = -1;
  7113. int
  7114. clrdircache() {
  7115.     debug(F100,"CLEAR ISDIR CACHE","",0);
  7116.     prevstat = -1;
  7117.     prevpath[0] = NUL;
  7118. }
  7119. #endif /* ISDIRCACHE */
  7120.  
  7121. int
  7122. isalink(s) char *s; {
  7123. #ifndef CKSYMLINK
  7124.     return(0);
  7125. #else
  7126.     int r = 0;
  7127.     char filbuf[CKMAXPATH+4];
  7128.     if (readlink(s,filbuf,CKMAXPATH) > -1)
  7129.       r = 1;
  7130.     debug(F110,"isalink readlink",s,r);
  7131.     return(r);
  7132. #endif    /* CKSYMLINK */
  7133. }
  7134.  
  7135. int
  7136. isdir(s) char *s; {
  7137.     int x, needrlink = 0, islink = 0;
  7138.     struct stat statbuf;
  7139.     char fnam[CKMAXPATH+4];
  7140.  
  7141.     if (!s) return(0);
  7142.     debug(F110,"isdir entry",s,0);
  7143. #ifdef DTILDE                /* 2005-08-13 */
  7144.     if (*s == '~') {            /* Starts with tilde? */
  7145.         s = tilde_expand(s);        /* Attempt to expand tilde */
  7146.         if (!s) s = "";
  7147.     debug(F110,"isdir tilde_expand",s,0);
  7148.     }
  7149. #endif /* DTILDE */
  7150.     if (!*s) return(0);
  7151.  
  7152. #ifdef ISDIRCACHE
  7153.     if (prevstat > -1) {
  7154.     if (s[0] == prevpath[0]) {
  7155.         if (!strcmp(s,prevpath)) {
  7156.         debug(F111,"isdir cache hit",s,prevstat);
  7157.         return(prevstat);
  7158.         }
  7159.     }
  7160.     }
  7161. #endif /* ISDIRCACHE */
  7162.  
  7163. #ifdef CKSYMLINK
  7164. #ifdef COMMENT
  7165. /*
  7166.   The following over-clever bit has been commented out because it presumes
  7167.   to know when a symlink might be redundant, which it can't possibly know.
  7168.   Using plain old stat() gives Kermit the same results as ls and ls -R, which
  7169.   is just fine: no surprises.
  7170. */
  7171. #ifdef USE_LSTAT
  7172.     if (xrecursive) {
  7173.         x = lstat(s,&statbuf);
  7174.         debug(F111,"isdir lstat",s,x);
  7175.     } else {
  7176. #endif /* USE_LSTAT */
  7177.         x = stat(s,&statbuf);
  7178.         debug(F111,"isdir stat",s,x);
  7179. #ifdef USE_LSTAT
  7180.     }
  7181. #endif /* USE_LSTAT */
  7182. #else
  7183.     x = stat(s,&statbuf);
  7184.     debug(F111,"isdir stat",s,x);
  7185. #endif /* COMMENT */
  7186.     if (x == -1) {
  7187.         debug(F101,"isdir errno","",errno);
  7188.         return(0);
  7189.     }
  7190.     islink = 0;
  7191.     if (xrecursive) {
  7192. #ifdef NOLINKBITS
  7193.         needrlink = 1;
  7194. #else
  7195. #ifdef S_ISLNK
  7196.         islink = S_ISLNK(statbuf.st_mode);
  7197.         debug(F101,"isdir S_ISLNK islink","",islink);
  7198. #else
  7199. #ifdef _IFLNK
  7200.         islink = (_IFMT & statbuf.st_mode) == _IFLNK;
  7201.         debug(F101,"isdir _IFLNK islink","",islink);
  7202. #endif /* _IFLNK */
  7203. #endif /* S_ISLNK */
  7204. #endif /* NOLINKBITS */
  7205.         if (needrlink) {
  7206.             if (readlink(s,fnam,CKMAXPATH) > -1)
  7207.               islink = 1;
  7208.         }
  7209.     }
  7210. #else
  7211.     x = stat(s,&statbuf);
  7212.     if (x == -1) {
  7213.         debug(F101,"isdir errno","",errno);
  7214.         return(0);
  7215.     }
  7216.     debug(F111,"isdir stat",s,x);
  7217. #endif /* CKSYMLINK */
  7218.     debug(F101,"isdir islink","",islink);
  7219.     debug(F101,"isdir statbuf.st_mode","",statbuf.st_mode);
  7220.     x = islink ? 0 : (S_ISDIR (statbuf.st_mode) ? 1 : 0);
  7221. #ifdef ISDIRCACHE
  7222.     prevstat = x;
  7223.     ckstrncpy(prevpath,s,CKMAXPATH+1);
  7224. #endif /* ISDIRCACHE */
  7225.     return(x);
  7226. }
  7227.  
  7228. #ifdef CK_MKDIR
  7229. /* Some systems don't have mkdir(), e.g. Tandy Xenix 3.2.. */
  7230.  
  7231. /* Z M K D I R  --  Create directory(s) if necessary */
  7232. /*
  7233.    Call with:
  7234.     A pointer to a file specification that might contain directory
  7235.     information.  The filename is expected to be included.
  7236.     If the file specification does not include any directory separators,
  7237.     then it is assumed to be a plain file.
  7238.     If one or more directories are included in the file specification,
  7239.     this routine tries to create them if they don't already exist.
  7240.    Returns:
  7241.     0 or greater on success, i.e. the number of directories created.
  7242.    -1 on failure to create the directory
  7243. */
  7244. int
  7245. zmkdir(path) char *path; {
  7246.     char *xp, *tp, c;
  7247.     int x, count = 0;
  7248.  
  7249.     if (!path) path = "";
  7250.     if (!*path) return(-1);
  7251.  
  7252. #ifdef CKROOT
  7253.     debug(F111,"zmkdir setroot",ckroot,ckrootset);
  7254.     if (ckrootset) if (!zinroot(path)) {
  7255.     debug(F110,"zmkdir setroot violation",path,0);
  7256.     return(-1);
  7257.     }
  7258. #endif /* CKROOT */
  7259.  
  7260.     x = strlen(path);
  7261.     debug(F111,"zmkdir",path,x);
  7262.     if (x < 1 || x > MAXPATH)           /* Check length */
  7263.       return(-1);
  7264.     if (!(tp = malloc(x+1)))            /* Make a temporary copy */
  7265.       return(-1);
  7266.     strcpy(tp,path);            /* safe (prechecked) */
  7267. #ifdef DTILDE
  7268.     if (*tp == '~') {                   /* Starts with tilde? */
  7269.         xp = tilde_expand(tp);          /* Attempt to expand tilde */
  7270.         if (!xp) xp = "";
  7271.         if (*xp) {
  7272.             char *zp;
  7273.             debug(F110,"zmkdir tilde_expand",xp,0);
  7274.             if (!(zp = malloc(strlen(xp) + 1))) { /* Make a place for it */
  7275.                 free(tp);
  7276.                 tp = NULL;
  7277.                 return(-1);
  7278.             }
  7279.             free(tp);                   /* Free previous buffer */
  7280.             tp = zp;                    /* Point to new one */
  7281.             strcpy(tp,xp);              /* Copy expanded name to new buffer */
  7282.         }
  7283.     }
  7284. #endif /* DTILDE */
  7285.     debug(F110,"zmkdir tp after tilde_expansion",tp,0);
  7286.     xp = tp;
  7287.     if (ISDIRSEP(*xp))                  /* Don't create root directory! */
  7288.       xp++;
  7289.  
  7290.     /* Go thru filespec from left to right... */
  7291.  
  7292.     for (; *xp; xp++) {                 /* Create parts that don't exist */
  7293.         if (!ISDIRSEP(*xp))             /* Find next directory separator */
  7294.           continue;
  7295.         c = *xp;                        /* Got one. */
  7296.         *xp = NUL;                      /* Make this the end of the string. */
  7297.         if (!isdir(tp)) {               /* This directory exists already? */
  7298. #ifdef CK_LOGIN
  7299.             if (isguest)                    /* Not allowed for guests */
  7300.           return(-1);
  7301. #ifndef NOXFER
  7302.             /* Nor if MKDIR and/or CD are disabled */
  7303.             else
  7304. #endif /* CK_LOGIN */
  7305.           if ((server
  7306. #ifdef IKSD
  7307.            || inserver
  7308. #endif /* IKSD */
  7309.            ) && (!ENABLED(en_mkd) || !ENABLED(en_cwd)))
  7310.         return(-1);
  7311. #endif /* IKSD */
  7312.  
  7313.             debug(F110,"zmkdir making",tp,0);
  7314.             x =                         /* No, try to create it */
  7315. #ifdef NOMKDIR
  7316.                -1                       /* Systems without mkdir() */
  7317. #else
  7318.                mkdir(tp,0777)           /* UNIX */
  7319. #endif /* NOMKDIR */
  7320.                  ;
  7321.             if (x < 0) {
  7322.                 debug(F101,"zmkdir failed, errno","",errno);
  7323.                 free(tp);               /* Free temporary buffer. */
  7324.                 tp = NULL;
  7325.                 return(-1);             /* Return failure code. */
  7326.             } else
  7327.               count++;
  7328.         }
  7329.         *xp = c;                        /* Replace the separator. */
  7330.     }
  7331.     free(tp);                           /* Free temporary buffer. */
  7332.     return(count);                      /* Return success code. */
  7333. }
  7334. #endif /* CK_MKDIR */
  7335.  
  7336. int
  7337. zrmdir(path) char *path; {
  7338. #ifdef CK_LOGIN
  7339.     if (isguest)
  7340.       return(-1);
  7341. #endif /* CK_LOGIN */
  7342.  
  7343.     if (!path) path = "";
  7344.     if (!*path) return(-1);
  7345.  
  7346. #ifdef CKROOT
  7347.     debug(F111,"zrmdir setroot",ckroot,ckrootset);
  7348.     if (ckrootset) if (!zinroot(path)) {
  7349.     debug(F110,"zrmdir setroot violation",path,0);
  7350.     return(-1);
  7351.     }
  7352. #endif /* CKROOT */
  7353.  
  7354. #ifndef NOMKDIR
  7355.     return(rmdir(path));
  7356. #else
  7357.     return(-1);
  7358. #endif /* NOMKDIR */
  7359. }
  7360.  
  7361. /* Z F S E E K  --  Position input file pointer */
  7362. /*
  7363.    Call with:
  7364.     CK_OFF_T (32 or 64 bits), 0-based, indicating desired position.
  7365.    Returns:
  7366.     0 on success.
  7367.    -1 on failure.
  7368. */
  7369. #ifndef NORESEND
  7370. int
  7371. #ifdef CK_ANSIC
  7372. zfseek(CK_OFF_T pos)
  7373. #else
  7374. zfseek(pos) CK_OFF_T pos;
  7375. #endif /* CK_ANSIC */
  7376. /* zfseek */ {
  7377.     zincnt = -1;                        /* Must empty the input buffer */
  7378.     debug(F101,"zfseek","",pos);
  7379.     return(CKFSEEK(fp[ZIFILE], pos, 0)?-1:0);
  7380. }
  7381. #endif /* NORESEND */
  7382.  
  7383. /*  Z F N Q F P  --  Convert filename to fully qualified absolute pathname */
  7384.  
  7385. /*
  7386.   Given a possibly unqualified or relative file specification fn, zfnqfp()
  7387.   returns the fully qualified filespec for the same file, returning a struct
  7388.   that contains the length (len) of the result, a pointer (fpath) to the
  7389.   whole result, and a pointer (fname) to where the filename starts.
  7390. */
  7391. static struct zfnfp fnfp = { 0, NULL, NULL };
  7392.  
  7393. struct zfnfp *
  7394. zfnqfp(fname, buflen, buf)  char * fname; int buflen; char * buf; {
  7395.     char * s;
  7396.     int len;
  7397. #ifdef MAXPATHLEN
  7398.     char zfntmp[MAXPATHLEN+4];
  7399. #else
  7400.     char zfntmp[CKMAXPATH+4];
  7401. #endif /* MAXPATHLEN */
  7402.  
  7403.     char sb[32], * tmp;
  7404.     int i = 0, j = 0, k = 0, x = 0, y = 0;
  7405.     int itsadir = 0;
  7406.  
  7407.     s = fname;
  7408.     if (!s)
  7409.       return(NULL);
  7410.     if (!*s)
  7411.       return(NULL);
  7412.     if (!buf)
  7413.       return(NULL);
  7414.  
  7415.     /* Initialize the data structure */
  7416.  
  7417.     fnfp.len = ckstrncpy(buf,fname,buflen);
  7418.     fnfp.fpath = buf;
  7419.     fnfp.fname = NULL;
  7420.     len = buflen;
  7421.     debug(F111,"zfnqfp fname",fname,len);
  7422.  
  7423. #ifdef DTILDE
  7424.     if (*s == '~') {                    /* Starts with tilde? */
  7425.         char * xp;
  7426.         xp = tilde_expand(s);           /* Attempt to expand tilde */
  7427.         debug(F110,"zfnqfp xp",xp,0);   /* (realpath() doesn't do this) */
  7428.         if (!xp) xp = "";
  7429.         if (*xp)
  7430.           s = xp;
  7431.     }
  7432. #endif /* DTILDE */
  7433.  
  7434. #ifdef CKREALPATH
  7435.  
  7436. /* N.B.: The realpath() result buffer MUST be MAXPATHLEN bytes long */
  7437. /* otherwise we write over memory. */
  7438.  
  7439.     if (!realpath(s,zfntmp)) {
  7440.         debug(F111,"zfnqfp realpath fails",s,errno);
  7441. #ifdef COMMENT
  7442.     if (errno != ENOENT)
  7443.       return(NULL);
  7444. #else
  7445.     /* If realpath() fails use the do-it-yourself method */
  7446.     /* 16 Jan 2002 */
  7447.     goto norealpath;
  7448. #endif /* COMMENT */
  7449.     }
  7450.     len = strlen(zfntmp);
  7451.     if (len > buflen) {
  7452.     debug(F111,"zfnqfp result too long",ckitoa(buflen),len);
  7453.     return(NULL);
  7454.     } else {
  7455.     ckstrncpy(buf,zfntmp,buflen);
  7456.     }
  7457.     if (buf[len-1] != '/') {
  7458.     if ((itsadir = isdir(buf)) && len < (buflen - 1)) {
  7459.         buf[len++] = '/';
  7460.         buf[len] = NUL;
  7461.     }
  7462.     }
  7463.     fnfp.len = len;
  7464.     fnfp.fpath = buf;
  7465.     debug(F110,"zfnqfp realpath path",fnfp.fpath,0);
  7466.     tmp = buf + fnfp.len - 1;
  7467.     if (!itsadir) {
  7468.     while (tmp >= buf) {
  7469.         if (*tmp == '/') {
  7470.         fnfp.fname = tmp + 1;
  7471.         debug(F110,"zfnqfp realpath name",fnfp.fname,0);
  7472.         break;
  7473.         }
  7474.         tmp--;
  7475.     }
  7476.     }
  7477.     return(&fnfp);
  7478.  
  7479. #endif /* CKREALPATH */
  7480.  
  7481.   norealpath:
  7482.  
  7483.     tmp = zfntmp;
  7484.     while (*s) {                        /* Remove leading "./" (0 or more) */
  7485.         debug(F110,"zfnqfp while *s",s,0);
  7486.         if (*s == '.' && *(s+1) == '/') {
  7487.             s += 2;
  7488.             while (*s == '/') s++;
  7489.         } else
  7490.           break;
  7491.     }
  7492.     if (!*s) return(NULL);
  7493.     if (*s == '/') {                    /* Pathname is absolute */
  7494.         ckstrncpy(buf,s,len);
  7495.         x = strlen(buf);
  7496.         y = 0;
  7497.     } else {                            /* Pathname is relative */
  7498.         char * p;
  7499.         if (p = zgtdir()) {             /* So get current directory */
  7500.             debug(F110,"zfnqfp zgtdir",p,0);
  7501.             x = ckstrncpy(buf,p,len);
  7502.             buf[x++] = '/';
  7503.             debug(F110,"zfnqfp buf 1",buf,0);
  7504.             len -= x;                   /* How much room left in buffer */
  7505.             if ((y = (int)strlen(s)) > len) /* If enough room... */
  7506.               return(NULL);
  7507.             ckstrncpy(buf+x,s,len);     /* ... append the filename */
  7508.             debug(F110,"zfnqfp buf 2",buf,0);
  7509.         } else {
  7510.             return(NULL);
  7511.         }
  7512.     }
  7513.  
  7514.     /* Buf now holds full path but maybe containing some . or .. tricks */
  7515.  
  7516.     j = x + y;                          /* Length of what's in buf */
  7517.     len = j;
  7518.     debug(F101,"zfnqfp len","",len);
  7519.  
  7520.     /* Catch dangling "/." or "/.." */
  7521.     if ((j > 1 && buf[j-1] == '.' && buf[j-2] == '/') ||
  7522.         (j > 2 && buf[j-1] == '.' && buf[j-2] == '.' && buf[j-3] == '/')) {
  7523.         if (j < buflen - 2) {
  7524.             buf[j] = '/';
  7525.             buf[j+1] = NUL;
  7526.         }
  7527.     }
  7528.     j = -1;                             /* j = position of rightmost "/" */
  7529.     i = 0;                              /* i = destination index */
  7530.     tmp[i] = NUL;                       /* destination is temporary buffer  */
  7531.  
  7532.     for (x = 0; x < len; x++) {         /* x = source index */
  7533.         if (buf[x] == '/') {
  7534.             for (k = 0; k < 4; k++) {
  7535.                 sb[k] = buf[x+k];
  7536.                 sb[k+1] = '\0';
  7537.                 if (!sb[k]) break;
  7538.             }
  7539.             if (!strncmp(sb,"/./",3)) { /* Eliminate "./" in "/./" */
  7540.                 x += 1;
  7541.                 continue;
  7542.             } else if (!strncmp(sb,"//",2)) { /* Change "//" to "/" */
  7543.                 continue;
  7544.             } else if (!strncmp(sb,"/../",4)) { /* ".." in path */
  7545.                 for (k = i - 1; k >= 0; k--) { /* Back up one level */
  7546.                     if (tmp[k] == '/') {
  7547.                         i = k;
  7548.                         tmp[i] = NUL;
  7549.                         break;
  7550.                     }
  7551.                 }
  7552.                 x += 2;
  7553.                 continue;
  7554.             }
  7555.         }
  7556.         if (i >= (buflen - 1)) {
  7557.             debug(F111,"zfnqfp overflow",tmp,i);
  7558.             return(NULL);
  7559.         }
  7560.         tmp[i++] = buf[x];              /* Regular character, copy */
  7561.         tmp[i] = NUL;
  7562.         if (buf[x] == '/')              /* Remember rightmost "/" */
  7563.           j = i;
  7564.     }
  7565.     ckstrncpy(buf,tmp,buflen-1);        /* Copy the result back */
  7566.  
  7567.     buf[buflen-1] = NUL;
  7568.     if (!buf[0]) {                      /* If empty, say root */
  7569.         buf[0] = '/';
  7570.         buf[2] = NUL;
  7571.         j = 0;
  7572.         i = 1;
  7573.     }
  7574.     if ((itsadir = isdir(buf))) {
  7575.     if (buf[i-1] != '/' && i < (buflen - 1)) {
  7576.         buf[i++] = '/';
  7577.         buf[i] = NUL;
  7578.     }
  7579.     }
  7580.     if (!itsadir && (j > -1)) {        /* Set pointer to basename */
  7581.         fnfp.fname = (char *)(buf + j);
  7582.         fnfp.fpath = (char *)buf;
  7583.         fnfp.len = i;
  7584.         debug(F111,"zfnqfp path",fnfp.fpath,i);
  7585.         debug(F110,"zfnqfp name",fnfp.fname,0);
  7586.         return(&fnfp);
  7587.     }
  7588.     return(NULL);
  7589. }
  7590.  
  7591. /*  Z C M P F N  --  Compare two filenames  */
  7592.  
  7593. /*  Returns 1 if the two names refer to the same existing file, 0 otherwise. */
  7594.  
  7595. int
  7596. zcmpfn(s1,s2) char * s1, * s2; {
  7597.     char buf1[CKMAXPATH+1];
  7598.     char buf2[CKMAXPATH+1];
  7599.  
  7600. #ifdef USE_LSTAT
  7601.     char linkname[CKMAXPATH+1];
  7602.     struct stat buf;
  7603. #endif /* USE_LSTAT */
  7604.     int x, rc = 0;
  7605.  
  7606.     if (!s1) s1 = "";
  7607.     if (!s2) s2 = "";
  7608.     if (!*s1 || !*s2) return(0);
  7609.  
  7610. #ifdef CKSYMLINK                        /* We're doing symlinks? */
  7611. #ifdef USE_LSTAT                        /* OK to use lstat()? */
  7612.     x = lstat(s1,&buf);
  7613.     if (x > -1 &&            /* Now see if it's a symlink */
  7614. #ifdef S_ISLNK
  7615.         S_ISLNK(buf.st_mode)
  7616. #else
  7617. #ifdef _IFLNK
  7618.         ((_IFMT & buf.st_mode) == _IFLNK)
  7619. #endif /* _IFLNK */
  7620. #endif /* S_ISLNK */
  7621.         ) {
  7622.         linkname[0] = '\0';             /* Get the name */
  7623.         x = readlink(s1,linkname,CKMAXPATH);
  7624.         if (x > -1 && x < CKMAXPATH) {  /* It's a link */
  7625.             linkname[x] = '\0';
  7626.         s1 = linkname;
  7627.         }
  7628.     }
  7629. #endif /* USE_LSTAT */
  7630. #endif /* CKSYMLINK */
  7631.  
  7632.     if (zfnqfp(s1,CKMAXPATH,buf1)) {    /* Convert to full pathname */
  7633.  
  7634. #ifdef CKSYMLINK            /* Same deal for second name... */
  7635. #ifdef USE_LSTAT
  7636.     x = lstat(s2,&buf);
  7637.     if (x > -1 &&
  7638. #ifdef S_ISLNK
  7639.         S_ISLNK(buf.st_mode)
  7640. #else
  7641. #ifdef _IFLNK
  7642.         ((_IFMT & buf.st_mode) == _IFLNK)
  7643. #endif /* _IFLNK */
  7644. #endif /* S_ISLNK */
  7645.         ) {
  7646.         linkname[0] = '\0';
  7647.         x = readlink(s2,linkname,CKMAXPATH);
  7648.         if (x > -1 && x < CKMAXPATH) {
  7649.         linkname[x] = '\0';
  7650.         s2 = linkname;
  7651.         }
  7652.     }
  7653. #endif /* USE_LSTAT */
  7654. #endif /* CKSYMLINK */
  7655.     if (zfnqfp(s2,CKMAXPATH,buf2)) {
  7656.         debug(F110,"zcmpfn s1",buf1,0);
  7657.         debug(F110,"zcmpfn s2",buf2,0);
  7658.         if (!strncmp(buf1,buf2,CKMAXPATH))
  7659.           rc = 1;
  7660.     }
  7661.     }
  7662.     debug(F101,"zcmpfn result","",rc);
  7663.     return(rc);
  7664. }
  7665.  
  7666. #ifdef CKROOT
  7667.  
  7668. /* User-mode chroot() implementation */
  7669.  
  7670. int
  7671. zsetroot(s) char * s; {            /* Sets the root */
  7672.     char buf[CKMAXPATH+1];
  7673.     if (!s) return(-1);
  7674.     if (!*s) return(-1);
  7675.     debug(F110,"zsetroot",s,0);
  7676.     if (!isdir(s)) return(-2);
  7677.     if (!zfnqfp(s,CKMAXPATH,buf))    /* Get full, real path */
  7678.       return(-3);
  7679.     if (access(buf,R_OK) < 0) {        /* Check access */
  7680.     debug(F110,"zsetroot access denied",buf,0);
  7681.     return(-4);
  7682.     }
  7683.     s = buf;
  7684.     if (ckrootset) {            /* If root already set */
  7685.     if (!zinroot(s)) {        /* make sure new root is in it */
  7686.         debug(F110,"zsetroot new root not in root",ckroot,0);
  7687.         return(-5);
  7688.     }
  7689.     }
  7690.     if (zchdir(buf) < 1) return(-4);    /* Change directory to new root */
  7691.     ckrootset = ckstrncpy(ckroot,buf,CKMAXPATH); /* Now set the new root */
  7692.     if (ckroot[ckrootset-1] != '/') {
  7693.     ckroot[ckrootset++] = '/';
  7694.     ckroot[ckrootset] = '\0';
  7695.     }
  7696.     debug(F111,"zsetroot rootset",ckroot,ckrootset);
  7697.     ckrooterr = 0;            /* Reset error flag */
  7698.     return(1);
  7699. }
  7700.  
  7701. char *
  7702. zgetroot() {                /* Returns the root */
  7703.     if (!ckrootset)
  7704.       return(NULL);
  7705.     return((char *)ckroot);
  7706. }
  7707.  
  7708. int
  7709. zinroot(s) char * s; {            /* Checks if file s is in the root */
  7710.     int x, n;
  7711.     struct zfnfp * f = NULL;
  7712.     char buf[CKMAXPATH+2];
  7713.  
  7714.     debug(F111,"zinroot setroot",ckroot,ckrootset);
  7715.     ckrooterr = 0;            /* Reset global error flag */
  7716.     if (!ckrootset)            /* Root not set */
  7717.       return(1);            /* so it's ok - no need to check */
  7718.     if (!(f = zfnqfp(s,CKMAXPATH,buf)))    /* Get full and real pathname */
  7719.       return(0);            /* Fail if we can't  */
  7720.     n = f->len;                /* Length of full pathname */
  7721.     debug(F111,"zinroot n",buf,n);
  7722.     if (n < (ckrootset - 1) || n > CKMAXPATH) {    /* Bad length */
  7723.     ckrooterr = 1;                    /* Fail */
  7724.     return(0);
  7725.     }
  7726.     if (isdir(buf) && buf[n-1] != '/') {  /* If it's a directory name */
  7727.     buf[n++] = '/';              /* make sure it ends with '/' */
  7728.     buf[n] = '\0';
  7729.     }
  7730.     x = strncmp(buf,ckroot,ckrootset);    /* Compare, case-sensitive */
  7731.     debug(F111,"zinroot checked",buf,x);
  7732.     if (x == 0)                /* OK */
  7733.       return(1);
  7734.     ckrooterr = 1;            /* Not OK */
  7735.     return(0);
  7736. }
  7737. #endif /* CKROOT */
  7738.  
  7739. #ifdef CK_LOGIN
  7740. /*
  7741.   The following code provides support for user login and logout
  7742.   including anonymous accounts.  If this feature is to be supported
  7743.   outside of UNIX, it should be spread out among the ck?fio.c modules...
  7744. */
  7745. #ifndef _PATH_BSHELL
  7746. #define _PATH_BSHELL    "/usr/bin/bash"
  7747. #endif /* _PATH_BSHELL */
  7748. #ifndef _PATH_FTPUSERS
  7749. #define _PATH_FTPUSERS  "/etc/ftpusers"
  7750. #endif /* _PATH_FTPUSERS */
  7751.  
  7752. /*
  7753.  * Helper function for sgetpwnam().
  7754.  */
  7755. char *
  7756. sgetsave(s) char *s; {
  7757.     char *new = malloc((unsigned) strlen(s) + 1);
  7758.     if (new == NULL) {
  7759.         printf("?Local resource failure: malloc\n");
  7760.         exit(1);
  7761.         /* NOTREACHED */
  7762.     }
  7763.     (void) strcpy(new, s);        /* safe */
  7764.     return (new);
  7765. }
  7766.  
  7767. /*
  7768.  * Save the result of getpwnam().  Used for USER command, since
  7769.  * the data returned must not be clobbered by any other command
  7770.  * (e.g., globbing).
  7771.  */
  7772. struct passwd *
  7773. sgetpwnam(name) char *name; {
  7774.     static struct passwd save;
  7775.     register struct passwd *p;
  7776. #ifdef CK_SHADOW
  7777.     register struct spwd *sp;
  7778. #endif /* CK_SHADOW */
  7779.     char *sgetsave();
  7780.  
  7781. #ifdef HPUX10_TRUSTED
  7782.     struct pr_passwd *pr;
  7783. #endif /* HPUX10_TRUSTED */
  7784.  
  7785. #ifdef CK_SHADOW
  7786.     sp = getspnam(name);
  7787.     if (sp == NULL) {
  7788.         debug(F110,"sgetpwnam","getspnam() fails",0);
  7789.     return (NULL);
  7790.     }
  7791. #endif /* CK_SHADOW */
  7792.  
  7793. #ifdef HPUX10_TRUSTED
  7794.     if ((pr = getprpwnam(name)) == NULL)
  7795.       return(NULL);
  7796. #endif /* HPUX10_TRUSTED */
  7797.  
  7798.     p = getpwnam(name);
  7799.     /* debug(F111,"sgetpwnam","getpwnam()",p); */
  7800.     if (p == NULL)
  7801.       return(NULL);
  7802.     if (save.pw_name) {
  7803.         free(save.pw_name);
  7804.         free(save.pw_passwd);
  7805.         free(save.pw_gecos);
  7806.         free(save.pw_dir);
  7807.         free(save.pw_shell);
  7808.     }
  7809.     save = *p;
  7810.     save.pw_name = sgetsave(p->pw_name);
  7811. #ifdef CK_SHADOW
  7812.     save.pw_passwd = sgetsave(sp->sp_pwdp);
  7813. #else /* CK_SHADOW */
  7814. #ifdef HPUX10_TRUSTED
  7815.     if (pr->uflg.fg_encrypt && pr->ufld.fd_encrypt && *pr->ufld.fd_encrypt)
  7816.       save.pw_passwd = sgetsave(pr->ufld.fd_encrypt);
  7817.     else
  7818.       save.pw_passwd = sgetsave("");
  7819. #else /* HPUX10_TRUSTED */
  7820.     save.pw_passwd = sgetsave(p->pw_passwd);
  7821. #endif /* HPUX10_TRUSTED */
  7822. #endif /* CK_SHADOW */
  7823.     save.pw_gecos = sgetsave(p->pw_gecos);
  7824.     save.pw_dir = sgetsave(p->pw_dir);
  7825.     save.pw_shell = sgetsave(p->pw_shell);
  7826.     return(&save);
  7827. }
  7828.  
  7829. #define CKXLOGBSIZ 256
  7830.  
  7831. struct passwd * pw = NULL;
  7832. char * home = NULL;                     /* Home directory pointer for glob */
  7833. #ifdef CMASK
  7834. #undef CMASK
  7835. #endif /* CMASK */
  7836.  
  7837. #define CMASK 027
  7838.  
  7839. int defumask = CMASK;                   /* Default umask value */
  7840.  
  7841. /*  Z V U S E R  --  Verify user, Returns 1 if user OK, 0 otherwise.  */
  7842.  
  7843. /* Sets global passwd pointer pw if named account exists and is acceptable;
  7844.  * sets askpasswd if a PASS command is expected.  If logged in previously,
  7845.  * need to reset state.  If name is "ftp" or "anonymous", the name is not in
  7846.  * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
  7847.  * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
  7848.  * requesting login privileges.  Disallow anyone who does not have a standard
  7849.  * shell as returned by getusershell().  Disallow anyone mentioned in the file
  7850.  * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
  7851.  */
  7852. _PROTOTYP(static int checkuser, (char *) );
  7853.  
  7854. char zvuname[64] = { NUL, NUL };
  7855. char zvhome[CKMAXPATH+1] = { NUL, NUL };
  7856. #define ZENVUSER 70
  7857. #define ZENVHOME CKMAXPATH+12
  7858. #define ZENVLOGNAME 74
  7859. static char zenvuser[ZENVUSER];
  7860. static char zenvhome[ZENVHOME];
  7861. static char zenvlogname[ZENVLOGNAME];
  7862.  
  7863. #ifdef CK_PAM
  7864. static char pam_data[500];
  7865. struct pam_conv pam_conv = {pam_cb, pam_data}; /* PAM structure */
  7866. struct pam_handle * pamh = NULL;               /* PAM reference handle */
  7867. #endif /* CK_PAM */
  7868.  
  7869. int
  7870. zvuser(name) char *name; {
  7871.     register char *cp = NULL;
  7872.     int x;
  7873.     char *shell;
  7874. #ifdef GETUSERSHELL
  7875. _PROTOTYP(char * getusershell, (void) );
  7876. #endif /* GETUSERSHELL */
  7877. #ifndef NODCLENDUSERSHELL
  7878. _PROTOTYP(VOID endusershell, (void) );
  7879. #endif    /* NODCLENDUSERSHELL */
  7880.  
  7881. #ifdef CK_PAM
  7882.     int pam_status;
  7883.     const char * reply = NULL;
  7884. #endif /* CK_PAM */
  7885.  
  7886.     debug(F111,"user",name,logged_in);
  7887.  
  7888.     if (!name) name = "";
  7889.     zvuname[0] = NUL;
  7890.  
  7891.     debug(F101,"zvuser ckxsyslog","",ckxsyslog);
  7892.  
  7893. #ifdef CKSYSLOG
  7894.     debug(F100,"zvuser CKSYSLOG defined","",0);
  7895. #endif /* CKSYSLOG */
  7896.  
  7897.     if (logged_in)                      /* Should not be called if logged in */
  7898.       return(0);
  7899.  
  7900. #ifdef CKSYSLOG
  7901.     if (ckxsyslog && ckxlogging) {
  7902.         syslog(LOG_INFO,
  7903.                 "login: user %s",name
  7904.                 );
  7905.     }
  7906. #endif /* CKSYSLOG */
  7907.  
  7908.     guest = 0;                          /* Assume not guest */
  7909.     askpasswd = 0;
  7910.  
  7911.     if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
  7912.         debug(F101,"zvuser anonymous ckxanon","",ckxanon);
  7913.         if (!ckxanon) {                 /* Anonymous login not allowed */
  7914. #ifdef CKSYSLOG
  7915.             if (ckxsyslog && ckxlogging) {
  7916.                 syslog(LOG_INFO,
  7917.                        "login: anonymous login not allowed: %s",
  7918.                        clienthost ? clienthost : "(unknown host)"
  7919.                        );
  7920.             }
  7921. #endif /* CKSYSLOG */
  7922.             return(0);
  7923.         }
  7924.         if (checkuser("ftp") || checkuser("anonymous")) {
  7925.             debug(F100,"zvuser anon forbidden by ftpusers file","",0);
  7926. #ifdef CKSYSLOG
  7927.             if (ckxsyslog && ckxlogging) {
  7928.                 syslog(LOG_INFO,
  7929.                        "login: anonymous login forbidden by ftpusers file: %s",
  7930.                        clienthost ? clienthost : "(unknown host)"
  7931.                        );
  7932.             }
  7933. #endif /* CKSYSLOG */
  7934.             return(0);
  7935.     } else if ((pw = sgetpwnam("ftp")) != NULL) {
  7936.             debug(F100,"zvuser anon sgetpwnam(ftp) OK","",0);
  7937.             guest = 1;
  7938.             askpasswd = 1;
  7939.             ckstrncpy(zvuname,"anonymous",64);
  7940.             return(1);
  7941.         } else {
  7942.             debug(F100,"zvuser anon sgetpwnam(ftp) FAILED","",0);
  7943. #ifdef CKSYSLOG
  7944.             if (ckxsyslog && ckxlogging) {
  7945.                 syslog(LOG_INFO,
  7946.                        "login: anonymous getpwnam(ftp) failed: %s",
  7947.                        clienthost ? clienthost : "(unknown host)"
  7948.                        );
  7949.             }
  7950. #endif /* CKSYSLOG */
  7951.             return(0);
  7952.         }
  7953.     }
  7954.     pw = sgetpwnam(name);
  7955.     if (pw) {
  7956. /*
  7957.   Of course some UNIX platforms (like AIX) don't have getusershell().
  7958.   In that case we can't check if the user's account has been "turned off"
  7959.   or somesuch, e.g. by setting their shell to "/etc/nologin" or somesuch,
  7960.   which runs (usually just printing a message and exiting), but which is
  7961.   not listed in /etc/shells.  For that matter, if getusershell() is not
  7962.   available, then probably neither is /etc/shells.
  7963. */
  7964.         debug(F100,"zvuser sgetpwnam ok","",0);
  7965.         shell = pw->pw_shell;
  7966.         if (!shell) shell = "";
  7967.         if (!*shell)
  7968.           shell = _PATH_BSHELL;
  7969.         debug(F110,"zvuser shell",shell,0);
  7970. #ifdef GETUSERSHELL
  7971.         while ((cp = getusershell()) != NULL) {
  7972.             debug(F110,"zvuser getusershell",cp,0);
  7973.             if ((int)strcmp(cp, shell) == 0)
  7974.               break;
  7975.         }
  7976.         debug(F100,"zvuser endusershell 1","",0);
  7977. #ifndef NODCLENDUSERSHELL
  7978.         (VOID) endusershell();
  7979. #else
  7980.         endusershell();
  7981. #endif    /* NODCLENDUSERSHELL */
  7982.         debug(F100,"zvuser endusershell 2","",0);
  7983. #else /* GETUSERSHELL */
  7984.         cp = "";                        /* Do not refuse if we cannot check */
  7985. #endif /* GETUSERSHELL */
  7986.         x = checkuser(name);
  7987.         debug(F101,"zvuser checkuser","",x);
  7988.         if (cp == NULL) {
  7989.             debug(F100,"zvuser refused 1","",0);
  7990.             pw = (struct passwd *) NULL;
  7991. #ifdef CKSYSLOG
  7992.             if (ckxsyslog && ckxlogging) {
  7993.                 syslog(LOG_INFO,
  7994.                        "login: invalid shell %s for %s %s",shell, name,
  7995.                        clienthost ? clienthost : "(unknown host)"
  7996.                        );
  7997.             }
  7998. #endif /* CKSYSLOG */
  7999.             return(0);
  8000.         } else if (x) {
  8001.             debug(F100,"zvuser refused 2","",0);
  8002.             pw = (struct passwd *) NULL;
  8003. #ifdef CKSYSLOG
  8004.             if (ckxsyslog && ckxlogging) {
  8005.                 syslog(LOG_INFO,
  8006.                        "login: %s login forbidden by ftpusers file: %s",
  8007.                        name, clienthost ? clienthost : "(unknown host)"
  8008.                        );
  8009.             }
  8010. #endif /* CKSYSLOG */
  8011.             return(0);
  8012.         } else {
  8013.             x = 0;
  8014. #ifdef CK_PAM
  8015.             /* Get PAM authentication details */
  8016.             debug(F110,"zvuser","calling pam_start",0);
  8017.             if ((pam_status =
  8018.                  pam_start(PAM_SERVICE_TYPE,name,&pam_conv,&pamh))
  8019.                 != PAM_SUCCESS) {
  8020.                 reply = pam_strerror(NULL, pam_status);
  8021.                 debug(F110,"zvuser PAM failure",reply,0);
  8022.                 printf("%s\n",reply);
  8023. #ifdef CKSYSLOG
  8024.                 if (ckxsyslog && ckxlogging) {
  8025.                     syslog(LOG_INFO,
  8026.                            "login: %s refused by PAM \"%s\": %s",
  8027.                            name,reply,
  8028.                            clienthost ? clienthost : "(unknown host)"
  8029.                            );
  8030.                 }
  8031. #endif /* CKSYSLOG */
  8032.                 return(0);
  8033.             }
  8034. #endif /* CK_PAM */
  8035.             askpasswd = 1;
  8036.             ckstrncpy(zvuname,name,64);
  8037.             return(1);
  8038.         }
  8039.     } else {
  8040.         x = 0;
  8041.         debug(F100,"zvuser sgetpwnam NULL","",0);
  8042. #ifdef CKSYSLOG
  8043.         if (ckxsyslog && ckxlogging) {
  8044.             syslog(LOG_INFO,
  8045.                    "login: getpwnam(%s) failed: %s",name,
  8046.                    clienthost ? clienthost : "(unknown host)"
  8047.                    );
  8048.         }
  8049. #endif /* CKSYSLOG */
  8050.         return(0);
  8051.     }
  8052.  
  8053. #ifdef FTP_KERBEROS
  8054.     if (auth_type && strcmp(auth_type, "KERBEROS_V4") == 0) {
  8055. #ifdef COMMENT
  8056.     /* Why sprintf and then printf? */
  8057.     /* Also, what is kerb_ok?  And is the test on it right? */
  8058.         char buf[CKXLOGBSIZ];
  8059.         sprintf(buf, "Kerberos user %s%s%s@%s is%s authorized as %s%s",
  8060.                  kdata.pname, *kdata.pinst ? "." : "",
  8061.                  kdata.pinst, kdata.prealm,
  8062.                  (kerb_ok = kuserok(&kdata,name) == 0) ? "" : " not",
  8063.                  name, kerb_ok ? "" : "; Password required.");
  8064.         printf("%s", buf);
  8065. #else
  8066.         printf("Kerberos user %s%s%s@%s is%s authorized as %s%s",
  8067.                  kdata.pname, *kdata.pinst ? "." : "",
  8068.                  kdata.pinst, kdata.prealm,
  8069.                  (kerb_ok = kuserok(&kdata,name) == 0) ? "" : " not",
  8070.                  name, kerb_ok ? "" : "; Password required.");
  8071. #endif /* COMMENT */
  8072.         if (kerb_ok) return(1);
  8073.     } else
  8074.       return(0);
  8075. #endif /* FTP_KERBEROS */
  8076. }
  8077.  
  8078. /* Check if the given user is in the forbidden-user file */
  8079.  
  8080. static int
  8081. checkuser(name) char *name; {
  8082.     extern char * userfile;
  8083.     FILE *fd;
  8084.     int i;
  8085.     char line[CKXLOGBSIZ+1];
  8086.  
  8087.     if (!name)
  8088.       name = "";
  8089.     i = strlen(name);
  8090.     debug(F111,"checkuser name",name,i);
  8091.     if (!*name)
  8092.       return(1);
  8093.  
  8094.     fd = fopen(userfile ? userfile : _PATH_FTPUSERS, "r");
  8095.     /* debug(F111,"checkuser userfile",userfile,fd); */
  8096.     if (fd) {
  8097.         line[0] = '\0';
  8098.         while (fgets(line, sizeof(line), fd)) {
  8099.             debug(F110,"checkuser line",line,0);
  8100.             if (line[0] <= '#')
  8101.               continue;
  8102.             if (strncmp(line, name, i) == 0) {
  8103.                 debug(F110,"checkuser REFUSED",name,0);
  8104.                 return(1);
  8105.             }
  8106.             line[0] = '\0';
  8107.         }
  8108.         (VOID) fclose(fd);
  8109.     }
  8110.     debug(F110,"checkuser OK",name,0);
  8111.     return(0);
  8112. }
  8113.  
  8114. /*  Z V L O G O U T  --  Log out from Internet Kermit Service  */
  8115.  
  8116. VOID
  8117. zvlogout() {
  8118. #ifdef COMMENT
  8119.     /* This could be dangerous */
  8120.     if (setuid((UID_T)0) < 0) {
  8121.         debug(F100,"zvlogout setuid FAILED","",0);
  8122.         goto bad;
  8123.     }
  8124.     debug(F100,"zvlogout setuid OK","",0);
  8125. #endif /* COMMENT */
  8126. #ifdef CKSYSLOG
  8127.     if (ckxsyslog >= SYSLG_LI && ckxlogging) {
  8128.         cksyslog(SYSLG_LI, 1, "logout",(char *) uidbuf, clienthost);
  8129.     }
  8130. #endif /* CKSYSLOG */
  8131. #ifdef CKWTMP
  8132.     debug(F110,"WTMP logout",cksysline,logged_in);
  8133.     if (logged_in)
  8134.       logwtmp(cksysline, "", "");
  8135. #endif /* CKWTMP */
  8136.     pw = NULL;
  8137.     logged_in = 0;
  8138.     guest = 0;
  8139.     isguest = 0;
  8140. }
  8141.  
  8142. #ifdef FTP_KERBEROS
  8143. kpass(name, p) char *name, *p; {
  8144.     char instance[INST_SZ];
  8145.     char realm[REALM_SZ];
  8146.     char tkt_file[20];
  8147.     KTEXT_ST ticket;
  8148.     AUTH_DAT authdata;
  8149.     unsigned long faddr;
  8150.     struct hostent *hp;
  8151.  
  8152.     if (krb_get_lrealm(realm, 1) != KSUCCESS)
  8153.       return(0);
  8154.  
  8155.     ckstrncpy(tkt_file, TKT_ROOT, 20);
  8156.     ckstrncat(tkt_file, "_ftpdXXXXXX", 20);
  8157.     krb_set_tkt_string(mktemp(tkt_file));
  8158.  
  8159.     (VOID) ckstrncpy(instance, krb_get_phost(hostname), sizeof(instance));
  8160.  
  8161.     if ((hp = gethostbyname(instance)) == NULL)
  8162.       return(0);
  8163.  
  8164. #ifdef HADDRLIST
  8165.     hp = ck_copyhostent(hp);        /* safe copy that won't change */
  8166. #endif /* HADDRLIST */
  8167.     bcopy((char *)hp->h_addr, (char *) &faddr, sizeof(faddr));
  8168.  
  8169.     if (krb_get_pw_in_tkt(name, "", realm, "krbtgt", realm, 1, p) ||
  8170.         krb_mk_req(&ticket, "rcmd", instance, realm, 33) ||
  8171.         krb_rd_req(&ticket, "rcmd", instance, faddr, &authdata, "") ||
  8172.         kuserok(&authdata, name)) {
  8173.         dest_tkt();
  8174.         return(0);
  8175.     }
  8176.     dest_tkt();
  8177.     return(1);
  8178. }
  8179. #endif /* FTP_KERBEROS */
  8180.  
  8181. VOID
  8182. zsyslog() {
  8183. #ifdef CKSYSLOG
  8184.     if (ckxsyslog && !ckxlogging) {
  8185. #ifdef LOG_DAEMON
  8186.         openlog(inserver ? "iksd" : "ckermit", LOG_PID, LOG_DAEMON);
  8187. #else
  8188.         openlog(inserver ? "iksd" : "ckermit", LOG_PID);
  8189. #endif /* LOG_DAEMON */
  8190.         ckxlogging = 1;
  8191.         debug(F100,"zsyslog syslog opened","",0);
  8192.     }
  8193. #endif /* CKSYSLOG */
  8194. }
  8195.  
  8196. /*  Z V P A S S  --  Verify password; returns 1 if OK, 0 otherwise  */
  8197.  
  8198. #ifndef AUTH_USER
  8199. #define AUTH_USER 3
  8200. #endif /* AUTH_USER */
  8201. #ifndef AUTH_VALID
  8202. #define AUTH_VALID 4
  8203. #endif /* AUTH_VALID */
  8204.  
  8205. #ifdef __FreeBSD__            /* 299 This was necessary in */
  8206. #ifndef NODCLINITGROUPS            /* FreeBSD 4.4, don't know */
  8207. #define NODCLINITGROUPS            /* about other versions... */
  8208. #endif    /* NODCLINITGROUPS */            
  8209. #endif    /*  __FreeBSD__ */
  8210.  
  8211. int
  8212. zvpass(p) char *p; {
  8213. #ifndef NODCLINITGROUPS
  8214. _PROTOTYP(int initgroups, (const char *, gid_t) );
  8215. #endif    /* NODCLINITGROUPS */
  8216.  
  8217.     char *xpasswd, *salt;
  8218.     char * dir = NULL;
  8219. #ifdef CK_PAM
  8220.     int pam_status;
  8221.     const char * reply = NULL;
  8222. #endif /* CK_PAM */
  8223.  
  8224.     if (logged_in || askpasswd == 0) {
  8225.         return(0);
  8226.     }
  8227.     debug(F111,"zvpass",p ? (guest ? p : "xxxxxx") : "(null)",guest);
  8228.     if (!p) p = "";
  8229.     askpasswd = 0;
  8230.     if (guest && !*p) {                 /* Guests must specify a password */
  8231. #ifdef CKSYSLOG
  8232.         if (ckxsyslog && ckxlogging) {
  8233.             syslog(LOG_INFO,
  8234.                    "login: anonymous guests must specify a password"
  8235.                    );
  8236.         }
  8237. #endif /* CKSYSLOG */
  8238.         return(0);
  8239.     }
  8240.     if (!guest
  8241. #ifdef CK_AUTHENTICATION
  8242.         && ck_tn_auth_valid() != AUTH_VALID
  8243. #endif /* CK_AUTHENTICATION */
  8244.         ) {                     /* "ftp" is only account allowed no password */
  8245. #ifdef CK_PAM
  8246.         debug(F110,"zvpass","calling pam_set_item(AUTHTOK)",0);
  8247.         if ((pam_status = pam_set_item(pamh,PAM_AUTHTOK,p)) != PAM_SUCCESS) {
  8248.             reply = pam_strerror(pamh, pam_status);
  8249.             debug(F110,"zvpass PAM failure",reply,0);
  8250.             /* if no password given treat as non-fatal error */
  8251.             /* pam will prompt for password in pam_authenticate() */
  8252.             if (!p) {
  8253.                 printf("%s\n",reply);
  8254.                 pam_end(pamh, 0);
  8255.                 debug(F100,"zvpass denied","",0);
  8256.                 pw = NULL;
  8257.                 zvuname[0] = NUL;
  8258.                 return(0);
  8259.             }
  8260.         }
  8261.         debug(F110,"zvpass","calling pam_authenticate",0);
  8262. #ifdef COMMENT
  8263.         if (*p)
  8264.       pam_pw = p;
  8265. #else
  8266. /*
  8267.   Make IKSD authentication (using PAM) ask for a password when an
  8268.   invalid username has been given, to avoid disclosing which account
  8269.   names are valid. See #417247 (Debian).
  8270. */
  8271.         if (*p
  8272. #ifdef CK_LOGIN
  8273.         || gotemptypasswd
  8274. #endif /* CK_LOGIN */
  8275.         )
  8276.         pam_pw = p;
  8277. #endif    /* COMMENT */
  8278.         if ((pam_status = pam_authenticate(pamh, 0)) != PAM_SUCCESS) {
  8279.             reply = pam_strerror(pamh, pam_status);
  8280.             debug(F110,"zvpass PAM failure",reply,0);
  8281.             printf("%s\n",reply);
  8282.             pam_end(pamh, 0);
  8283.             debug(F100,"zvpass denied","",0);
  8284.             pam_pw = NULL;
  8285.             pw = NULL;
  8286.             zvuname[0] = NUL;
  8287.             return(0);
  8288.         }
  8289.         pam_pw = NULL;
  8290.         debug(F110,"zvpass","calling pam_acct_mgmt",0);
  8291.         if ((pam_status = pam_acct_mgmt(pamh, 0)) != PAM_SUCCESS) {
  8292.             reply = pam_strerror(pamh, pam_status);
  8293.             debug(F110,"zvpass PAM failure",reply,0);
  8294.             printf("%s\n",reply);
  8295.             pam_end(pamh, 0);
  8296.             debug(F100,"zvpass denied","",0);
  8297.             pw = NULL;
  8298.             zvuname[0] = NUL;
  8299.             return(0);
  8300.         }
  8301.         debug(F110,"zvpass","PAM validates OK",0);
  8302.         pam_end(pamh,0);
  8303. #else /* CK_PAM */
  8304.         if (pw == NULL)
  8305.           salt = "xx";
  8306.         else
  8307.           salt = pw->pw_passwd;
  8308.  
  8309. #ifdef HPUX10_TRUSTED
  8310.         xpasswd = bigcrypt(p, salt);
  8311. #else
  8312. /*
  8313.   On 64-bit platforms this can give "cast to pointer from integer of
  8314.   different size" warning, but I'm not sure what the effect is at runtime,
  8315.   or what to do about it.
  8316.  */
  8317.         xpasswd = (char *)crypt(p, salt);
  8318. #endif /* HPUX10_TRUSTED */
  8319.  
  8320.         if (
  8321. #ifdef FTP_KERBEROS
  8322.             /* null pw_passwd ok if Kerberos password ok */
  8323.             pw == NULL ||
  8324.             ((*pw->pw_passwd != '\0' ||
  8325.               strcmp(xpasswd, pw->pw_passwd))
  8326.              && !kpass(pw->pw_name, p))
  8327. #else
  8328. #ifdef CK_SRP
  8329.             /* check with tpasswd first if there */
  8330.             pw == NULL || *pw->pw_passwd == '\0' ||
  8331.             t_verifypw (pw->pw_name, p) == 0 ||
  8332.             (t_verifypw (pw->pw_name, p) < 0 &&
  8333.             strcmp (xpasswd, pw->pw_passwd))
  8334. #else /* CK_SRP */
  8335.             /* The strcmp does not catch null passwords! */
  8336.             (pw == NULL) || (*pw->pw_passwd == '\0') ||
  8337.             strcmp(xpasswd, pw->pw_passwd)
  8338. #endif /* CK_SRP */
  8339. #endif /* FTP_KERBEROS */
  8340.             ) {
  8341.             debug(F100,"zvpass denied","",0);
  8342.             pw = NULL;
  8343.             zvuname[0] = NUL;
  8344.             return(0);
  8345.         }
  8346. #endif /* CK_PAM */
  8347.     }
  8348.  
  8349.     (VOID) setgid((GID_T)pw->pw_gid);   /* Set group ID */
  8350.  
  8351. #ifndef NOINITGROUPS
  8352.     (VOID) initgroups(pw->pw_name, pw->pw_gid);
  8353. #endif /* NOINITGROUPS */
  8354.  
  8355.     logged_in = 1;
  8356.     dir = pw->pw_dir;
  8357.  
  8358. #ifdef CKWTMP
  8359.     /* Open wtmp before chroot */
  8360.     if (ckxwtmp) {
  8361.         sprintf(cksysline,"iks_%04x", getpid()); /* safe */
  8362.         logwtmp(cksysline, pw->pw_name,
  8363.                  clienthost ? clienthost : "(unknown host)"
  8364.                 );
  8365.         debug(F110,"WTMP login",cksysline,logged_in);
  8366.     }
  8367. #endif /* CKWTMP */
  8368. /*
  8369.   For anonymous users, we chroot to user ftp's home directory unless
  8370.   started with --anonroot:xxx, in which case we chroot to xxx.  We must
  8371.   immediately chdir() to the same directory we chroot() to or else the
  8372.   old current directory remains accessible as "." outside the new root.
  8373. */
  8374.     if (guest) {
  8375.         if (anonroot)                   /* Non-default anonymous root */
  8376.           dir = anonroot;
  8377.         else
  8378.           makestr(&anonroot,dir);
  8379.         errno = 0;
  8380.         debug(F110,"zvpass anon chroot",dir,0);
  8381.         if (chroot(dir) < 0) {
  8382.             debug(F111,"zvpass anon chroot FAILED",dir,errno);
  8383.             goto bad;
  8384.         }
  8385.         errno = 0;
  8386.         if (chdir("/") < 0) {
  8387.             debug(F111,"zvpass anon chdir FAILED",dir,errno);
  8388.             goto bad;
  8389.         }
  8390.         debug(F110,"zvpass anon chroot/chdir OK",dir,0);
  8391.     } else if (chdir(dir) < 0) {        /* Not guest */
  8392. #ifdef COMMENT
  8393.         if (chdir("/") < 0) {
  8394.             debug(F110,"Non-guest chdir FAILED",dir,0);
  8395.             goto bad;
  8396.         } else
  8397.           printf("?No directory! Logging in with home=/\n");
  8398. #else
  8399.         debug(F110,"zvpass non-guest chdir FAILED",dir,0);
  8400.         goto bad;                       /* Be conservative at first */
  8401. #endif /* COMMENT */
  8402.     }
  8403.     debug(F110,"zvpass non-guest chdir OK",dir,0);
  8404.     if (setuid((UID_T)pw->pw_uid) < 0) {
  8405.         debug(F101,"zvpass setuid FAILED","",pw->pw_uid);
  8406.         goto bad;
  8407.     }
  8408.     debug(F101,"zvpass setuid OK","",pw->pw_uid);
  8409.  
  8410.     guestpass[0] = '\0';
  8411.     if (guest) {
  8412.         extern int fncact;
  8413.         isguest = 1;
  8414.         fncact = XYFX_R;                /* FILE COLLISION = RENAME */
  8415.         debug(F110,"GUEST fncact=R",p,0);
  8416.         lset(guestpass,"anonymous:",10,32);
  8417.         ckstrncpy(&guestpass[10],p,GUESTPASS-10);
  8418.         home = "/";
  8419.         printf("Anonymous login.\r\n");
  8420.  
  8421. #ifdef SETPROCTITLE
  8422.     /* proctitle declared where?  Obviously this code is never compiled. */
  8423.         sprintf(proctitle, "%s: anonymous/%.*s",
  8424.                 clienthost ? clienthost : "(unk)",
  8425.                 sizeof(proctitle) - sizeof(clienthost) -
  8426.                 sizeof(": anonymous/"), p);
  8427.         setproctitle(proctitle);
  8428. #endif /* SETPROCTITLE */
  8429.  
  8430. #ifdef CKSYSLOG
  8431.         if (ckxsyslog && ckxlogging) {
  8432.             syslog(LOG_INFO,
  8433.                    "login: anonymous %s %s",
  8434.                    clienthost ? clienthost : "(unknown host)",
  8435.                    p
  8436.                    );
  8437.         }
  8438. #endif /* CKSYSLOG */
  8439.  
  8440.     } else {                            /* Real user */
  8441.         isguest = 0;
  8442.         home = dir;
  8443.         ckstrncpy(guestpass,zvuname,GUESTPASS);
  8444.  
  8445.         printf("User %s logged in.\r\n", pw->pw_name);
  8446. #ifdef SETPROCTITLE
  8447.     /* not used */
  8448.         sprintf(proctitle, "%s: %s",
  8449.                 clienthost ? clienthost : "(unk)",
  8450.                 pw->pw_name
  8451.                 );
  8452.         setproctitle(proctitle);
  8453. #endif /* SETPROCTITLE */
  8454.  
  8455. #ifdef CKSYSLOG
  8456.         if (ckxsyslog && ckxlogging)
  8457.           syslog(LOG_INFO, "login: %s %s",
  8458.                  pw->pw_name,
  8459.                  clienthost ? clienthost : "(unknown host)"
  8460.                  );
  8461. #endif /* CKSYSLOG */
  8462.     }
  8463.     ckstrncpy(zvhome,home,CKMAXPATH);   /* Set environment variables */
  8464. #ifndef NOPUTENV
  8465.  
  8466.     ckmakmsg(zenvuser,ZENVUSER,"USER=",zvuname,NULL,NULL);
  8467.     putenv((char *)zenvuser);
  8468.     ckmakmsg(zenvlogname,ZENVLOGNAME,"LOGNAME=",zvuname,NULL,NULL);
  8469.     putenv((char *)zenvlogname);
  8470.     ckmakmsg(zenvhome,ZENVHOME,"HOME=",zvhome,NULL,NULL);
  8471.     putenv((char *)zenvhome);
  8472. #endif /* NOPUTENV */
  8473.     /* homdir = (char *)zvhome; */
  8474.     ckstrncpy((char *)uidbuf,(char *)zvuname,64);
  8475.     (VOID) umask(defumask);
  8476. #ifdef IKSDB
  8477.     if (ikdbopen) {
  8478.         char * p2;
  8479.         int k;
  8480.         extern char dbrec[];
  8481.         extern unsigned long myflags;
  8482.         extern unsigned int mydbslot;
  8483.         extern struct iksdbfld dbfld[];
  8484. #ifdef CK_AUTHENTICATION
  8485.         extern unsigned long myamode, myatype;
  8486. #endif /* CK_AUTHENTICATION */
  8487.         myflags |= DBF_LOGGED;
  8488. #ifdef DEBUG
  8489.     if (deblog) {
  8490.         debug(F101,"zvpass guest","",guest);
  8491.         debug(F111,"zvpass zvuname",zvuname,0);
  8492.         debug(F110,"zvpass guestpass",guestpass,0);
  8493.         debug(F110,"zvpass dir",dir,0);
  8494.         debug(F110,"zvpass home",home,0);
  8495.         debug(F110,"zvpass anonroot",anonroot,0);
  8496.     }
  8497. #endif /* DEBUG */
  8498.         p2 = guest ? guestpass : zvuname;
  8499.         if (guest) {
  8500.             p2 = (char *)guestpass;
  8501.             myflags &= ~DBF_USER;
  8502.         } else {
  8503.             p2 = (char *)zvuname;
  8504.             myflags |= DBF_USER;
  8505.         }
  8506.         k = strlen(p2);
  8507.         strncpy(&dbrec[DB_ULEN],ulongtohex((unsigned long)k,4),4);
  8508.         lset(&dbrec[dbfld[db_USER].off],p2,1024,32);
  8509.         strncpy(&dbrec[DB_FLAGS],ulongtohex(myflags,4),4);
  8510. #ifdef CK_AUTHENTICATION
  8511.         myamode = ck_tn_auth_valid();
  8512.         strncpy(&dbrec[DB_AMODE],ulongtohex(myamode,4),4);
  8513.         myatype = ck_tn_authenticated();
  8514.         strncpy(&dbrec[DB_ATYPE],ulongtohex(myatype,4),4);
  8515. #endif /* CK_AUTHENTICATION */
  8516.         if (guest) {
  8517.             p2 = dir;
  8518.         } else {
  8519.             p2 = zgtdir();
  8520.             if (!p2) p2 = "";
  8521.             if (!*p2) p2 = home;
  8522.         }
  8523.         strncpy(&dbrec[DB_DLEN],
  8524.                 ulongtohex((unsigned long)strlen(p2),4),
  8525.                 4
  8526.                 );
  8527.         lset(&dbrec[dbfld[db_DIR].off],p2,1024,32);
  8528.         updslot(mydbslot);
  8529.     }
  8530. #endif /* IKSDB */
  8531.     return(1);
  8532.  
  8533. bad:                                    /* Common failure exit */
  8534.     zvuname[0] = NUL;
  8535.     zvlogout();
  8536.     return(0);
  8537. }
  8538. #endif /* CK_LOGIN */
  8539.  
  8540. /* Buggy Xenix 2.3.4 cc needs this line after the endif */
  8541.