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