Merge from vendor branch AWK:
[dragonfly.git] / contrib / lukemftpd / src / cmds.c
1 /*      $NetBSD: cmds.c,v 1.16 2002/02/13 15:15:23 lukem Exp $  */
2
3 /*
4  * Copyright (c) 1999-2001 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Luke Mewburn.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38
39 /*
40  * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
41  *      The Regents of the University of California.  All rights reserved.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. All advertising materials mentioning features or use of this software
52  *    must display the following acknowledgement:
53  *      This product includes software developed by the University of
54  *      California, Berkeley and its contributors.
55  * 4. Neither the name of the University nor the names of its contributors
56  *    may be used to endorse or promote products derived from this software
57  *    without specific prior written permission.
58  *
59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69  * SUCH DAMAGE.
70  */
71
72 /*
73  * Copyright (C) 1997 and 1998 WIDE Project.
74  * All rights reserved.
75  * 
76  * Redistribution and use in source and binary forms, with or without
77  * modification, are permitted provided that the following conditions
78  * are met:
79  * 1. Redistributions of source code must retain the above copyright
80  *    notice, this list of conditions and the following disclaimer.
81  * 2. Redistributions in binary form must reproduce the above copyright
82  *    notice, this list of conditions and the following disclaimer in the
83  *    documentation and/or other materials provided with the distribution.
84  * 3. Neither the name of the project nor the names of its contributors
85  *    may be used to endorse or promote products derived from this software
86  *    without specific prior written permission.
87  * 
88  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
89  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
90  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
91  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
92  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
93  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
94  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
95  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
96  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
97  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
98  * SUCH DAMAGE.
99  */
100
101 #include "lukemftpd.h"
102
103 #include "extern.h"
104
105 typedef enum {
106         FE_MLSD         = 1<<0,         /* if op is MLSD (MLST otherwise ) */
107         FE_ISCURDIR     = 1<<1,         /* if name is the current directory */
108 } factflag_t;
109
110 typedef struct {
111         const char      *path;          /* full pathname */
112         const char      *display;       /* name to display */
113         struct stat     *stat;          /* stat of path */
114         struct stat     *pdirstat;      /* stat of path's parent dir */
115         factflag_t       flags;         /* flags */
116 } factelem;
117
118 static void     ack(const char *);
119 static void     base64_encode(const char *, size_t, char *, int);
120 static void     fact_type(const char *, FILE *, factelem *);
121 static void     fact_size(const char *, FILE *, factelem *);
122 static void     fact_modify(const char *, FILE *, factelem *);
123 static void     fact_perm(const char *, FILE *, factelem *);
124 static void     fact_unique(const char *, FILE *, factelem *);
125 static int      matchgroup(gid_t);
126 static void     mlsname(FILE *, factelem *);
127 static void     replydirname(const char *, const char *);
128
129 struct ftpfact {
130         const char       *name;         /* name of fact */
131         int               enabled;      /* if fact is enabled */
132         void            (*display)(const char *, FILE *, factelem *);
133                                         /* function to display fact */
134 };
135
136 struct ftpfact facttab[] = {
137         { "Type",       1, fact_type },
138 #define FACT_TYPE 0
139         { "Size",       1, fact_size },
140         { "Modify",     1, fact_modify },
141         { "Perm",       1, fact_perm },
142         { "Unique",     1, fact_unique },
143         /* "Create" */
144         /* "Lang" */
145         /* "Media-Type" */
146         /* "CharSet" */
147 };
148
149 #define FACTTABSIZE     (sizeof(facttab) / sizeof(struct ftpfact))
150
151
152 void
153 cwd(const char *path)
154 {
155
156         if (chdir(path) < 0)
157                 perror_reply(550, path);
158         else {
159                 show_chdir_messages(250);
160                 ack("CWD");
161         }
162 }
163
164 void
165 delete(const char *name)
166 {
167         char *p = NULL;
168
169         if (remove(name) < 0) {
170                 p = strerror(errno);
171                 perror_reply(550, name);
172         } else
173                 ack("DELE");
174         logxfer("delete", -1, name, NULL, NULL, p);
175 }
176
177 void
178 feat(void)
179 {
180         int i;
181
182         reply(-211, "Features supported");
183         cprintf(stdout, " MDTM\r\n");
184         cprintf(stdout, " MLST ");
185         for (i = 0; i < FACTTABSIZE; i++)
186                 cprintf(stdout, "%s%s;", facttab[i].name,
187                     facttab[i].enabled ? "*" : "");
188         cprintf(stdout, "\r\n");
189         cprintf(stdout, " REST STREAM\r\n");
190         cprintf(stdout, " SIZE\r\n");
191         cprintf(stdout, " TVFS\r\n");
192         reply(211,  "End");
193 }
194
195 void
196 makedir(const char *name)
197 {
198         char *p = NULL;
199
200         if (mkdir(name, 0777) < 0) {
201                 p = strerror(errno);
202                 perror_reply(550, name);
203         } else
204                 replydirname(name, "directory created.");
205         logxfer("mkdir", -1, name, NULL, NULL, p);
206 }
207
208 void
209 mlsd(const char *path)
210 {
211         struct dirent   *dp;
212         struct stat      sb, pdirstat;
213         factelem f;
214         FILE    *dout;
215         DIR     *dirp;
216         char    name[MAXPATHLEN];
217         int     hastypefact;
218
219         hastypefact = facttab[FACT_TYPE].enabled;
220         if (path == NULL)
221                 path = ".";
222         if (stat(path, &pdirstat) == -1) {
223  mlsdperror:
224                 perror_reply(550, path);
225                 return;
226         }
227         if (! S_ISDIR(pdirstat.st_mode)) {
228                 errno = ENOTDIR;
229                 perror_reply(501, path);
230                 return;
231         }
232         if ((dirp = opendir(path)) == NULL)
233                 goto mlsdperror;
234
235         dout = dataconn("MLSD", (off_t)-1, "w");
236         if (dout == NULL)
237                 return;
238
239         memset(&f, 0, sizeof(f));
240         f.stat = &sb;
241         f.flags |= FE_MLSD;
242         while ((dp = readdir(dirp)) != NULL) {
243                 snprintf(name, sizeof(name), "%s/%s", path, dp->d_name);
244                 if (ISDOTDIR(dp->d_name)) {     /* special case curdir: */
245                         if (! hastypefact)
246                                 continue;
247                         f.pdirstat = NULL;      /*   require stat of parent */
248                         f.display = path;       /*   set name to real name */
249                         f.flags |= FE_ISCURDIR; /*   flag name is curdir */
250                 } else {
251                         if (ISDOTDOTDIR(dp->d_name)) {
252                                 if (! hastypefact)
253                                         continue;
254                                 f.pdirstat = NULL;
255                         } else
256                                 f.pdirstat = &pdirstat; /* cache parent stat */
257                         f.display = dp->d_name;
258                         f.flags &= ~FE_ISCURDIR;
259                 }
260                 if (stat(name, &sb) == -1)
261                         continue;
262                 f.path = name;
263                 mlsname(dout, &f);
264         }
265         (void)closedir(dirp);
266
267         if (ferror(dout) != 0)
268                 perror_reply(550, "Data connection");
269         else
270                 reply(226, "MLSD complete.");
271         closedataconn(dout);
272         total_xfers_out++;
273         total_xfers++;
274 }
275
276 void
277 mlst(const char *path)
278 {
279         struct stat sb;
280         factelem f;
281
282         if (path == NULL)
283                 path = ".";
284         if (stat(path, &sb) == -1) {
285                 perror_reply(550, path);
286                 return;
287         }
288         reply(-250, "MLST %s", path);
289         memset(&f, 0, sizeof(f));
290         f.path = path;
291         f.display = path;
292         f.stat = &sb;
293         f.pdirstat = NULL;
294         CPUTC(' ', stdout);
295         mlsname(stdout, &f);
296         reply(250, "End");
297 }
298
299
300 void
301 opts(const char *command)
302 {
303         struct tab *c;
304         char *ep;
305
306         if ((ep = strchr(command, ' ')) != NULL)
307                 *ep++ = '\0';
308         c = lookup(cmdtab, command);
309         if (c == NULL) {
310                 reply(502, "Unknown command %s.", command);
311                 return;
312         }
313         if (! CMD_IMPLEMENTED(c)) {
314                 reply(501, "%s command not implemented.", c->name);
315                 return;
316         }
317         if (! CMD_HAS_OPTIONS(c)) {
318                 reply(501, "%s command does not support persistent options.",
319                     c->name);
320                 return;
321         }
322
323                         /* special case: MLST */
324         if (strcasecmp(command, "MLST") == 0) {
325                 int      enabled[FACTTABSIZE];
326                 int      i, onedone;
327                 size_t   len;
328                 char    *p;
329
330                 for (i = 0; i < sizeof(enabled) / sizeof(int); i++)
331                         enabled[i] = 0;
332                 if (ep == NULL || *ep == '\0')
333                         goto displaymlstopts;
334
335                                 /* don't like spaces, and need trailing ; */
336                 len = strlen(ep);
337                 if (strchr(ep, ' ') != NULL || ep[len - 1] != ';') {
338  badmlstopt:
339                         reply(501, "Invalid MLST options");
340                         return;
341                 }
342                 ep[len - 1] = '\0';
343                 while ((p = strsep(&ep, ";")) != NULL) {
344                         if (*p == '\0')
345                                 goto badmlstopt;
346                         for (i = 0; i < FACTTABSIZE; i++)
347                                 if (strcasecmp(p, facttab[i].name) == 0) {
348                                         enabled[i] = 1;
349                                         break;
350                                 }
351                 }
352
353  displaymlstopts:
354                 for (i = 0; i < FACTTABSIZE; i++)
355                         facttab[i].enabled = enabled[i];
356                 cprintf(stdout, "200 MLST OPTS");
357                 for (i = onedone = 0; i < FACTTABSIZE; i++) {
358                         if (facttab[i].enabled) {
359                                 cprintf(stdout, "%s%s;", onedone ? "" : " ",
360                                     facttab[i].name);
361                                 onedone++;
362                         }
363                 }
364                 cprintf(stdout, "\r\n");
365                 fflush(stdout);
366                 return;
367         }
368
369                         /* default cases */
370         if (ep != NULL && *ep != '\0')
371                 REASSIGN(c->options, xstrdup(ep));
372         if (c->options != NULL)
373                 reply(200, "Options for %s are '%s'.", c->name,
374                     c->options);
375         else
376                 reply(200, "No options defined for %s.", c->name);
377 }
378
379 void
380 pwd(void)
381 {
382         char path[MAXPATHLEN];
383
384         if (getcwd(path, sizeof(path) - 1) == NULL)
385                 reply(550, "Can't get the current directory: %s.",
386                     strerror(errno));
387         else
388                 replydirname(path, "is the current directory.");
389 }
390
391 void
392 removedir(const char *name)
393 {
394         char *p = NULL;
395
396         if (rmdir(name) < 0) {
397                 p = strerror(errno);
398                 perror_reply(550, name);
399         } else
400                 ack("RMD");
401         logxfer("rmdir", -1, name, NULL, NULL, p);
402 }
403
404 char *
405 renamefrom(const char *name)
406 {
407         struct stat st;
408
409         if (stat(name, &st) < 0) {
410                 perror_reply(550, name);
411                 return (NULL);
412         }
413         reply(350, "File exists, ready for destination name");
414         return (xstrdup(name));
415 }
416
417 void
418 renamecmd(const char *from, const char *to)
419 {
420         char *p = NULL;
421
422         if (rename(from, to) < 0) {
423                 p = strerror(errno);
424                 perror_reply(550, "rename");
425         } else
426                 ack("RNTO");
427         logxfer("rename", -1, from, to, NULL, p);
428 }
429
430 void
431 sizecmd(const char *filename)
432 {
433         switch (type) {
434         case TYPE_L:
435         case TYPE_I:
436             {
437                 struct stat stbuf;
438                 if (stat(filename, &stbuf) < 0 || !S_ISREG(stbuf.st_mode))
439                         reply(550, "%s: not a plain file.", filename);
440                 else
441                         reply(213, ULLF, (ULLT)stbuf.st_size);
442                 break;
443             }
444         case TYPE_A:
445             {
446                 FILE *fin;
447                 int c;
448                 off_t count;
449                 struct stat stbuf;
450                 fin = fopen(filename, "r");
451                 if (fin == NULL) {
452                         perror_reply(550, filename);
453                         return;
454                 }
455                 if (fstat(fileno(fin), &stbuf) < 0 || !S_ISREG(stbuf.st_mode)) {
456                         reply(550, "%s: not a plain file.", filename);
457                         (void) fclose(fin);
458                         return;
459                 }
460                 if (stbuf.st_size > 10240) {
461                         reply(550, "%s: file too large for SIZE.", filename);
462                         (void) fclose(fin);
463                         return;
464                 }
465
466                 count = 0;
467                 while((c = getc(fin)) != EOF) {
468                         if (c == '\n')  /* will get expanded to \r\n */
469                                 count++;
470                         count++;
471                 }
472                 (void) fclose(fin);
473
474                 reply(213, LLF, (LLT)count);
475                 break;
476             }
477         default:
478                 reply(504, "SIZE not implemented for Type %c.", "?AEIL"[type]);
479         }
480 }
481
482 void
483 statfilecmd(const char *filename)
484 {
485         FILE *fin;
486         int c;
487         char *argv[] = { INTERNAL_LS, "-lgA", "", NULL };
488
489         argv[2] = (char *)filename;
490         fin = ftpd_popen(argv, "r", STDOUT_FILENO);
491         reply(-211, "status of %s:", filename);
492 /* XXX: use fgetln() or fparseln() here? */
493         while ((c = getc(fin)) != EOF) {
494                 if (c == '\n') {
495                         if (ferror(stdout)){
496                                 perror_reply(421, "control connection");
497                                 (void) ftpd_pclose(fin);
498                                 dologout(1);
499                                 /* NOTREACHED */
500                         }
501                         if (ferror(fin)) {
502                                 perror_reply(551, filename);
503                                 (void) ftpd_pclose(fin);
504                                 return;
505                         }
506                         CPUTC('\r', stdout);
507                 }
508                 CPUTC(c, stdout);
509         }
510         (void) ftpd_pclose(fin);
511         reply(211, "End of Status");
512 }
513
514 /* -- */
515
516 static void
517 ack(const char *s)
518 {
519
520         reply(250, "%s command successful.", s);
521 }
522
523 /*
524  * Encode len bytes starting at clear using base64 encoding into encoded,
525  * which should be at least ((len + 2) * 4 / 3 + 1) in size.
526  * If nulterm is non-zero, terminate with \0 otherwise pad to 3 byte boundary
527  * with `='.
528  */
529 static void
530 base64_encode(const char *clear, size_t len, char *encoded, int nulterm)
531 {
532         static const char base64[] =
533             "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
534         const char *c;
535         char    *e, termchar;
536         int      i;
537
538                         /* determine whether to pad with '=' or NUL terminate */
539         termchar = nulterm ? '\0' : '=';
540         c = clear;
541         e = encoded;
542                         /* convert all but last 2 bytes */
543         for (i = len; i > 2; i -= 3, c += 3) {
544                 *e++ = base64[(c[0] >> 2) & 0x3f];
545                 *e++ = base64[((c[0] << 4) & 0x30) | ((c[1] >> 4) & 0x0f)];
546                 *e++ = base64[((c[1] << 2) & 0x3c) | ((c[2] >> 6) & 0x03)];
547                 *e++ = base64[(c[2]) & 0x3f];
548         }
549                         /* handle slop at end */
550         if (i > 0) {
551                 *e++ = base64[(c[0] >> 2) & 0x3f];
552                 *e++ = base64[((c[0] << 4) & 0x30) |
553                      (i > 1 ? ((c[1] >> 4) & 0x0f) : 0)];
554                 *e++ = (i > 1) ? base64[(c[1] << 2) & 0x3c] : termchar;
555                 *e++ = termchar;
556         }
557         *e = '\0';
558 }
559
560 static void
561 fact_modify(const char *fact, FILE *fd, factelem *fe)
562 {
563         struct tm *t;
564
565         t = gmtime(&(fe->stat->st_mtime));
566         cprintf(fd, "%s=%04d%02d%02d%02d%02d%02d;", fact,
567             TM_YEAR_BASE + t->tm_year,
568             t->tm_mon+1, t->tm_mday,
569             t->tm_hour, t->tm_min, t->tm_sec);
570 }
571
572 static void
573 fact_perm(const char *fact, FILE *fd, factelem *fe)
574 {
575         int             rok, wok, xok, pdirwok;
576         struct stat     *pdir;
577
578         if (fe->stat->st_uid == geteuid()) {
579                 rok = ((fe->stat->st_mode & S_IRUSR) != 0);
580                 wok = ((fe->stat->st_mode & S_IWUSR) != 0);
581                 xok = ((fe->stat->st_mode & S_IXUSR) != 0);
582         } else if (matchgroup(fe->stat->st_gid)) {
583                 rok = ((fe->stat->st_mode & S_IRGRP) != 0);
584                 wok = ((fe->stat->st_mode & S_IWGRP) != 0);
585                 xok = ((fe->stat->st_mode & S_IXGRP) != 0);
586         } else {
587                 rok = ((fe->stat->st_mode & S_IROTH) != 0);
588                 wok = ((fe->stat->st_mode & S_IWOTH) != 0);
589                 xok = ((fe->stat->st_mode & S_IXOTH) != 0);
590         }
591
592         cprintf(fd, "%s=", fact);
593
594                         /*
595                          * if parent info not provided, look it up, but
596                          * only if the current class has modify rights,
597                          * since we only need this info in such a case.
598                          */
599         pdir = fe->pdirstat;
600         if (pdir == NULL && CURCLASS_FLAGS_ISSET(modify)) {
601                 size_t          len;
602                 char            realdir[MAXPATHLEN], *p;
603                 struct stat     dir;
604
605                 len = strlcpy(realdir, fe->path, sizeof(realdir));
606                 if (len < sizeof(realdir) - 4) {
607                         if (S_ISDIR(fe->stat->st_mode))
608                                 strlcat(realdir, "/..", sizeof(realdir));
609                         else {
610                                         /* if has a /, move back to it */
611                                         /* otherwise use '..' */
612                                 if ((p = strrchr(realdir, '/')) != NULL) {
613                                         if (p == realdir)
614                                                 p++;
615                                         *p = '\0';
616                                 } else
617                                         strlcpy(realdir, "..", sizeof(realdir));
618                         }
619                         if (stat(realdir, &dir) == 0)
620                                 pdir = &dir;
621                 }
622         }
623         pdirwok = 0;
624         if (pdir != NULL) {
625                 if (pdir->st_uid == geteuid())
626                         pdirwok = ((pdir->st_mode & S_IWUSR) != 0);
627                 else if (matchgroup(pdir->st_gid))
628                         pdirwok = ((pdir->st_mode & S_IWGRP) != 0);
629                 else
630                         pdirwok = ((pdir->st_mode & S_IWOTH) != 0);
631         }
632
633                         /* 'a': can APPE to file */
634         if (wok && CURCLASS_FLAGS_ISSET(upload) && S_ISREG(fe->stat->st_mode))
635                 CPUTC('a', fd);
636
637                         /* 'c': can create or append to files in directory */
638         if (wok && CURCLASS_FLAGS_ISSET(modify) && S_ISDIR(fe->stat->st_mode))
639                 CPUTC('c', fd);
640
641                         /* 'd': can delete file or directory */
642         if (pdirwok && CURCLASS_FLAGS_ISSET(modify)) {
643                 int candel;
644
645                 candel = 1;
646                 if (S_ISDIR(fe->stat->st_mode)) {
647                         DIR *dirp;
648                         struct dirent *dp;
649
650                         if ((dirp = opendir(fe->display)) == NULL)
651                                 candel = 0;
652                         else {
653                                 while ((dp = readdir(dirp)) != NULL) {
654                                         if (ISDOTDIR(dp->d_name) ||
655                                             ISDOTDOTDIR(dp->d_name))
656                                                 continue;
657                                         candel = 0;
658                                         break;
659                                 }
660                                 closedir(dirp);
661                         }
662                 }
663                 if (candel)
664                         CPUTC('d', fd);
665         }
666
667                         /* 'e': can enter directory */
668         if (xok && S_ISDIR(fe->stat->st_mode))
669                 CPUTC('e', fd);
670
671                         /* 'f': can rename file or directory */
672         if (pdirwok && CURCLASS_FLAGS_ISSET(modify))
673                 CPUTC('f', fd);
674
675                         /* 'l': can list directory */
676         if (rok && xok && S_ISDIR(fe->stat->st_mode))
677                 CPUTC('l', fd);
678
679                         /* 'm': can create directory */
680         if (wok && CURCLASS_FLAGS_ISSET(modify) && S_ISDIR(fe->stat->st_mode))
681                 CPUTC('m', fd);
682
683                         /* 'p': can remove files in directory */
684         if (wok && CURCLASS_FLAGS_ISSET(modify) && S_ISDIR(fe->stat->st_mode))
685                 CPUTC('p', fd);
686
687                         /* 'r': can RETR file */
688         if (rok && S_ISREG(fe->stat->st_mode))
689                 CPUTC('r', fd);
690
691                         /* 'w': can STOR file */
692         if (wok && CURCLASS_FLAGS_ISSET(upload) && S_ISREG(fe->stat->st_mode))
693                 CPUTC('w', fd);
694
695         CPUTC(';', fd);
696 }
697
698 static void
699 fact_size(const char *fact, FILE *fd, factelem *fe)
700 {
701
702         if (S_ISREG(fe->stat->st_mode))
703                 cprintf(fd, "%s=" LLF ";", fact, (LLT)fe->stat->st_size);
704 }
705
706 static void
707 fact_type(const char *fact, FILE *fd, factelem *fe)
708 {
709
710         cprintf(fd, "%s=", fact);
711         switch (fe->stat->st_mode & S_IFMT) {
712         case S_IFDIR:
713                 if (fe->flags & FE_MLSD) {
714                         if ((fe->flags & FE_ISCURDIR) || ISDOTDIR(fe->display))
715                                 cprintf(fd, "cdir");
716                         else if (ISDOTDOTDIR(fe->display))
717                                 cprintf(fd, "pdir");
718                         else
719                                 cprintf(fd, "dir");
720                 } else {
721                         cprintf(fd, "dir");
722                 }
723                 break;
724         case S_IFREG:
725                 cprintf(fd, "file");
726                 break;
727         case S_IFIFO:
728                 cprintf(fd, "OS.unix=fifo");
729                 break;
730         case S_IFLNK:           /* XXX: probably a NO-OP with stat() */
731                 cprintf(fd, "OS.unix=slink");
732                 break;
733         case S_IFSOCK:
734                 cprintf(fd, "OS.unix=socket");
735                 break;
736         case S_IFBLK:
737         case S_IFCHR:
738                 cprintf(fd, "OS.unix=%s-%d/%d",
739                     S_ISBLK(fe->stat->st_mode) ? "blk" : "chr",
740                     major(fe->stat->st_rdev), minor(fe->stat->st_rdev));
741                 break;
742         default:
743                 cprintf(fd, "OS.unix=UNKNOWN(0%o)", fe->stat->st_mode & S_IFMT);
744                 break;
745         }
746         CPUTC(';', fd);
747 }
748
749 static void
750 fact_unique(const char *fact, FILE *fd, factelem *fe)
751 {
752         char obuf[(sizeof(dev_t) + sizeof(ino_t) + 2) * 4 / 3 + 2];
753         char tbuf[sizeof(dev_t) + sizeof(ino_t)];
754
755         memcpy(tbuf,
756             (char *)&(fe->stat->st_dev), sizeof(dev_t));
757         memcpy(tbuf + sizeof(dev_t),
758             (char *)&(fe->stat->st_ino), sizeof(ino_t));
759         base64_encode(tbuf, sizeof(dev_t) + sizeof(ino_t), obuf, 1);
760         cprintf(fd, "%s=%s;", fact, obuf);
761 }
762
763 static int
764 matchgroup(gid_t gid)
765 {
766         int     i;
767
768         for (i = 0; i < gidcount; i++)
769                 if (gid == gidlist[i])
770                         return(1);
771         return (0);
772 }
773
774 static void
775 mlsname(FILE *fp, factelem *fe)
776 {
777         char realfile[MAXPATHLEN];
778         int i, userf;
779
780         for (i = 0; i < FACTTABSIZE; i++) {
781                 if (facttab[i].enabled)
782                         (facttab[i].display)(facttab[i].name, fp, fe);
783         }
784         if ((fe->flags & FE_MLSD) &&
785             !(fe->flags & FE_ISCURDIR) && !ISDOTDIR(fe->display)) {
786                         /* if MLSD and not "." entry, display as-is */
787                 userf = 0;
788         } else {
789                         /* if MLST, or MLSD and "." entry, realpath(3) it */
790                 if (realpath(fe->display, realfile) != NULL)
791                         userf = 1;
792         }
793         cprintf(fp, " %s\r\n", userf ? realfile : fe->display);
794 }
795
796 static void
797 replydirname(const char *name, const char *message)
798 {
799         char *p, *ep;
800         char npath[MAXPATHLEN * 2];
801
802         p = npath;
803         ep = &npath[sizeof(npath) - 1];
804         while (*name) {
805                 if (*name == '"') {
806                         if (ep - p < 2)
807                                 break;
808                         *p++ = *name++;
809                         *p++ = '"';
810                 } else {
811                         if (ep - p < 1)
812                                 break;
813                         *p++ = *name++;
814                 }
815         }
816         *p = '\0';
817         reply(257, "\"%s\" %s", npath, message);
818 }