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