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