Coverage Report

Created: 2025-07-11 06:08

/src/proftpd/modules/mod_ls.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * ProFTPD - FTP server daemon
3
 * Copyright (c) 1997, 1998 Public Flood Software
4
 * Copyright (c) 1999, 2000 MacGyver aka Habeeb J. Dihu <macgyver@tos.net>
5
 * Copyright (c) 2001-2025 The ProFTPD Project
6
 *
7
 * This program is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 2 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
20
 *
21
 * As a special exemption, Public Flood Software/MacGyver aka Habeeb J. Dihu
22
 * and other respective copyright holders give permission to link this program
23
 * with OpenSSL, and distribute the resulting executable, without including
24
 * the source code for OpenSSL in the source distribution.
25
 */
26
27
/* Directory listing module for ProFTPD. */
28
29
#include "conf.h"
30
31
#ifndef GLOB_ABORTED
32
#define GLOB_ABORTED GLOB_ABEND
33
#endif
34
35
#define MAP_UID(x) \
36
0
  (fakeuser ? fakeuser : pr_auth_uid2name(cmd->tmp_pool, (x)))
37
38
#define MAP_GID(x) \
39
0
  (fakegroup ? fakegroup : pr_auth_gid2name(cmd->tmp_pool, (x)))
40
41
static void addfile(cmd_rec *, const char *, const char *, time_t, off_t);
42
static int outputfiles(cmd_rec *);
43
44
static int listfile(cmd_rec *, pool *, const char *, const char *);
45
static int listdir(cmd_rec *, pool *, const char *, const char *);
46
47
static int sendline(int flags, char *fmt, ...)
48
#ifdef __GNUC__
49
       __attribute__ ((format (printf, 2, 3)));
50
#else
51
       ;
52
#endif
53
0
#define LS_SENDLINE_FL_FLUSH  0x0001
54
55
0
#define LS_FL_NO_ERROR_IF_ABSENT  0x0001
56
0
#define LS_FL_LIST_ONLY     0x0002
57
0
#define LS_FL_NLST_ONLY     0x0004
58
0
#define LS_FL_ADJUSTED_SYMLINKS   0x0008
59
0
#define LS_FL_SORTED_NLST   0x0010
60
static unsigned long list_flags = 0UL;
61
62
0
#define LS_LIST_STYLE_UNIX    1
63
0
#define LS_LIST_STYLE_WINDOWS   2
64
static int list_style = LS_LIST_STYLE_UNIX;
65
66
/* Maximum size of the "dsize" directory block we'll allocate for all of the
67
 * entries in a directory (Bug#4247).
68
 */
69
0
#define LS_MAX_DSIZE      (1024 * 1024 * 8)
70
71
static unsigned char list_strict_opts = FALSE;
72
static char *list_options = NULL;
73
static unsigned char list_show_symlinks = TRUE, list_times_gmt = TRUE;
74
static unsigned char show_symlinks_hold;
75
static const char *fakeuser = NULL, *fakegroup = NULL;
76
static mode_t fakemode;
77
static unsigned char have_fake_mode = FALSE;
78
static int ls_errno = 0;
79
static time_t ls_curtime = 0;
80
81
static unsigned char use_globbing = TRUE;
82
83
/* Directory listing limits */
84
struct list_limit_rec {
85
  unsigned int curr, max;
86
  unsigned char logged;
87
};
88
89
static struct list_limit_rec list_ndepth;
90
static struct list_limit_rec list_ndirs;
91
static struct list_limit_rec list_nfiles;
92
93
/* ls options */
94
static int
95
    opt_1 = 0,
96
    opt_a = 0,
97
    opt_A = 0,
98
    opt_B = 0,
99
    opt_C = 0,
100
    opt_c = 0,
101
    opt_d = 0,
102
    opt_F = 0,
103
    opt_h = 0,
104
    opt_l = 0,
105
    opt_L = 0,
106
    opt_n = 0,
107
    opt_R = 0,
108
    opt_r = 0,
109
    opt_S = 0,
110
    opt_t = 0,
111
    opt_U = 0,
112
    opt_u = 0,
113
    opt_STAT = 0;
114
115
/* Determines which struct st timestamp is used for sorting, if any. */
116
static int ls_sort_by = 0;
117
0
#define LS_SORT_BY_MTIME  100
118
0
#define LS_SORT_BY_CTIME  101
119
0
#define LS_SORT_BY_ATIME  102
120
121
static char cwd[PR_TUNABLE_PATH_MAX+1] = "";
122
123
/* Find a <Limit> block that limits the given command (which will probably
124
 * be LIST).  This code borrowed for src/dirtree.c's dir_check_limit().
125
 * Note that this function is targeted specifically for ls commands (eg
126
 * LIST, NLST, DIRS, and ALL) that might be <Limit>'ed.
127
 */
128
0
static config_rec *find_ls_limit(char *cmd_name) {
129
0
  config_rec *c = NULL, *limit_c = NULL;
130
131
0
  if (cmd_name == NULL) {
132
0
    return NULL;
133
0
  }
134
135
0
  if (session.dir_config == NULL) {
136
0
    return NULL;
137
0
  }
138
139
  /* Determine whether this command is <Limit>'ed. */
140
0
  for (c = session.dir_config; c; c = c->parent) {
141
0
    pr_signals_handle();
142
143
0
    if (c->subset) {
144
0
      for (limit_c = (config_rec *) (c->subset->xas_list); limit_c;
145
0
          limit_c = limit_c->next) {
146
147
0
        if (limit_c->config_type == CONF_LIMIT) {
148
0
          register unsigned int i = 0;
149
150
0
          for (i = 0; i < limit_c->argc; i++) {
151
152
            /* match any of the appropriate <Limit> arguments
153
             */
154
0
            if (strcasecmp(cmd_name, (char *) (limit_c->argv[i])) == 0 ||
155
0
                strcasecmp("DIRS", (char *) (limit_c->argv[i])) == 0 ||
156
0
                strcasecmp("ALL", (char *) (limit_c->argv[i])) == 0) {
157
0
              break;
158
0
            }
159
0
          }
160
161
0
          if (i == limit_c->argc) {
162
0
            continue;
163
0
          }
164
165
          /* Found a <Limit> directive associated with the current command. */
166
0
          return limit_c;
167
0
        }
168
0
      }
169
0
    }
170
0
  }
171
172
0
  return NULL;
173
0
}
174
175
0
static int is_safe_symlink(pool *p, const char *path, size_t pathlen) {
176
177
  /* First, check the most common cases: '.', './', '..', and '../'. */
178
0
  if ((pathlen == 1 && path[0] == '.') ||
179
0
      (pathlen == 2 && path[0] == '.' && (path[1] == '.' || path[1] == '/')) ||
180
0
      (pathlen == 3 && path[0] == '.' && path[1] == '.' && path[2] == '/')) {
181
0
    return FALSE;
182
0
  }
183
184
  /* Next, paranoidly check for uncommon occurrences, e.g. './///', '../////',
185
   * etc.
186
   */
187
0
  if (pathlen >= 2 &&
188
0
      path[0] == '.' &&
189
0
      (path[pathlen-1] == '/' || path[pathlen-1] == '.')) {
190
0
    char buf[PR_TUNABLE_PATH_MAX + 1], *full_path;
191
0
    size_t buflen;
192
193
0
    full_path = pdircat(p, pr_fs_getcwd(), path, NULL);
194
195
0
    buf[sizeof(buf)-1] = '\0';
196
0
    pr_fs_clean_path(full_path, buf, sizeof(buf)-1);
197
0
    buflen = strlen(buf);
198
199
    /* If the cleaned path appears in the current working directory, we
200
     * have an "unsafe" symlink pointing to the current directory (or higher
201
     * up the path).
202
     */
203
0
    if (strncmp(pr_fs_getcwd(), buf, buflen) == 0) {
204
0
      return FALSE;
205
0
    }
206
0
  }
207
208
0
  return TRUE;
209
0
}
210
211
0
static void push_cwd(char *_cwd, unsigned char *symhold) {
212
0
  if (_cwd == NULL) {
213
0
    _cwd = cwd;
214
0
  }
215
216
0
  sstrncpy(_cwd, pr_fs_getcwd(), PR_TUNABLE_PATH_MAX + 1);
217
0
  *symhold = show_symlinks_hold = list_show_symlinks;
218
0
}
219
220
0
static void pop_cwd(char *_cwd, unsigned char *symhold) {
221
0
  if (_cwd == NULL) {
222
0
    _cwd = cwd;
223
0
  }
224
225
0
  *symhold = show_symlinks_hold;
226
0
  pr_fsio_chdir(_cwd, *symhold);
227
0
  list_show_symlinks = *symhold;
228
0
}
229
230
0
static int ls_perms_full(pool *p, cmd_rec *cmd, const char *path, int *hidden) {
231
0
  int res, use_canon = FALSE;
232
0
  char *fullpath;
233
0
  mode_t *fake_mode = NULL;
234
235
0
  fullpath = dir_realpath(p, path);
236
0
  if (fullpath == NULL) {
237
0
    fullpath = dir_canonical_path(p, path);
238
0
    use_canon = TRUE;
239
0
  }
240
241
0
  if (fullpath == NULL) {
242
0
    fullpath = pstrdup(p, path);
243
0
  }
244
245
0
  if (use_canon == TRUE) {
246
0
    res = dir_check_canon(p, cmd, cmd->group, fullpath, hidden);
247
248
0
  } else {
249
0
    res = dir_check(p, cmd, cmd->group, fullpath, hidden);
250
0
  }
251
252
0
  if (session.dir_config) {
253
0
    unsigned char *ptr;
254
255
0
    ptr = get_param_ptr(session.dir_config->subset, "ShowSymlinks", FALSE);
256
0
    if (ptr != NULL) {
257
0
      list_show_symlinks = *ptr;
258
0
    }
259
0
  }
260
261
0
  fake_mode = get_param_ptr(CURRENT_CONF, "DirFakeMode", FALSE);
262
0
  if (fake_mode) {
263
0
    fakemode = *fake_mode;
264
0
    have_fake_mode = TRUE;
265
266
0
  } else {
267
0
    have_fake_mode = FALSE;
268
0
  }
269
270
0
  return res;
271
0
}
272
273
0
static int ls_perms(pool *p, cmd_rec *cmd, const char *path, int *hidden) {
274
0
  int res = 0;
275
0
  char fullpath[PR_TUNABLE_PATH_MAX + 1] = {'\0'};
276
0
  mode_t *fake_mode = NULL;
277
278
  /* No need to process dotdirs. */
279
0
  if (is_dotdir(path)) {
280
0
    return 1;
281
0
  }
282
283
0
  if (*path == '~') {
284
0
    return ls_perms_full(p, cmd, path, hidden);
285
0
  }
286
287
0
  if (*path != '/') {
288
0
    pr_fs_clean_path(pdircat(p, pr_fs_getcwd(), path, NULL), fullpath,
289
0
      PR_TUNABLE_PATH_MAX);
290
291
0
  } else {
292
0
    pr_fs_clean_path(path, fullpath, PR_TUNABLE_PATH_MAX);
293
0
  }
294
295
0
  res = dir_check(p, cmd, cmd->group, fullpath, hidden);
296
297
0
  if (session.dir_config) {
298
0
    unsigned char *ptr;
299
300
0
    ptr = get_param_ptr(session.dir_config->subset, "ShowSymlinks", FALSE);
301
0
    if (ptr != NULL) {
302
0
      list_show_symlinks = *ptr;
303
0
    }
304
0
  }
305
306
0
  fake_mode = get_param_ptr(CURRENT_CONF, "DirFakeMode", FALSE);
307
0
  if (fake_mode) {
308
0
    fakemode = *fake_mode;
309
0
    have_fake_mode = TRUE;
310
311
0
  } else {
312
0
    have_fake_mode = FALSE;
313
0
  }
314
315
0
  return res;
316
0
}
317
318
/* sendline() now has an internal buffer, to help speed up LIST output.
319
 * This buffer is allocated once, the first time sendline() is called.
320
 * By using a runtime allocation, we can use pr_config_get_server_xfer_bufsz()
321
 * to get the optimal buffer size for network transfers.
322
 */
323
static char *listbuf = NULL, *listbuf_ptr = NULL;
324
static size_t listbufsz = 0;
325
326
0
static int sendline(int flags, char *fmt, ...) {
327
0
  va_list msg;
328
0
  char buf[PR_TUNABLE_BUFFER_SIZE+1];
329
0
  int res = 0;
330
0
  size_t buflen, listbuflen;
331
332
0
  memset(buf, '\0', sizeof(buf));
333
334
0
  if (listbuf == NULL) {
335
0
    listbufsz = pr_config_get_server_xfer_bufsz(PR_NETIO_IO_WR);
336
0
    listbuf = listbuf_ptr = pcalloc(session.pool, listbufsz);
337
0
    pr_trace_msg("data", 8, "allocated list buffer of %lu bytes",
338
0
      (unsigned long) listbufsz);
339
0
  }
340
341
0
  if (flags & LS_SENDLINE_FL_FLUSH) {
342
0
    listbuflen = (listbuf_ptr - listbuf) + strlen(listbuf_ptr);
343
344
0
    if (listbuflen > 0) {
345
0
      int using_ascii = FALSE;
346
347
      /* Make sure the ASCII flags are cleared from the session flags,
348
       * so that the pr_data_xfer() function does not try to perform
349
       * ASCII translation on this data.
350
       */
351
0
      if (session.sf_flags & SF_ASCII) {
352
0
        using_ascii = TRUE;
353
0
      }
354
355
0
      session.sf_flags &= ~SF_ASCII;
356
0
      session.sf_flags &= ~SF_ASCII_OVERRIDE;
357
358
0
      res = pr_data_xfer(listbuf, listbuflen);
359
0
      if (res < 0 &&
360
0
          errno != 0) {
361
0
        int xerrno = errno;
362
363
0
        if (session.d != NULL &&
364
0
            session.d->outstrm != NULL) {
365
0
          xerrno = PR_NETIO_ERRNO(session.d->outstrm);
366
0
        }
367
368
0
        pr_log_debug(DEBUG3, "pr_data_xfer returned %d, error = %s", res,
369
0
          strerror(xerrno));
370
0
      }
371
372
0
      if (using_ascii) {
373
0
        session.sf_flags |= SF_ASCII;
374
0
      }
375
0
      session.sf_flags |= SF_ASCII_OVERRIDE;
376
377
0
      memset(listbuf, '\0', listbufsz);
378
0
      listbuf_ptr = listbuf;
379
0
      pr_trace_msg("data", 8, "flushed %lu bytes of list buffer",
380
0
        (unsigned long) listbuflen);
381
0
      listbuflen = 0;
382
0
    }
383
384
0
    return res;
385
0
  }
386
387
0
  va_start(msg, fmt);
388
0
  pr_vsnprintf(buf, sizeof(buf), fmt, msg);
389
0
  va_end(msg);
390
391
0
  buf[sizeof(buf)-1] = '\0';
392
393
  /* If buf won't fit completely into listbuf, flush listbuf */
394
0
  listbuflen = (listbuf_ptr - listbuf) + strlen(listbuf_ptr);
395
396
0
  buflen = strlen(buf);
397
0
  if (buflen >= (listbufsz - listbuflen)) {
398
    /* Make sure the ASCII flags are cleared from the session flags,
399
     * so that the pr_data_xfer() function does not try to perform
400
     * ASCII translation on this data.
401
     */
402
0
    session.sf_flags &= ~SF_ASCII_OVERRIDE;
403
404
0
    res = pr_data_xfer(listbuf, listbuflen);
405
0
    if (res < 0 &&
406
0
        errno != 0) {
407
0
      int xerrno = errno;
408
409
0
      if (session.d != NULL &&
410
0
          session.d->outstrm) {
411
0
        xerrno = PR_NETIO_ERRNO(session.d->outstrm);
412
0
      }
413
414
0
      pr_log_debug(DEBUG3, "pr_data_xfer returned %d, error = %s", res,
415
0
        strerror(xerrno));
416
0
    }
417
418
0
    session.sf_flags |= SF_ASCII_OVERRIDE;
419
420
0
    memset(listbuf, '\0', listbufsz);
421
0
    listbuf_ptr = listbuf;
422
0
    pr_trace_msg("data", 8, "flushed %lu bytes of list buffer",
423
0
      (unsigned long) listbuflen);
424
0
    listbuflen = 0;
425
0
  }
426
427
0
  sstrcat(listbuf_ptr, buf, listbufsz - listbuflen);
428
0
  listbuf_ptr += buflen;
429
430
0
  return res;
431
0
}
432
433
0
static void ls_done(cmd_rec *cmd) {
434
0
  pr_data_close2();
435
436
0
  if (!(session.sf_flags & SF_ABORT)) {
437
    /* If the transfer was not aborted, consider it a success. */
438
0
    pr_response_add(R_226, _("Transfer complete"));
439
0
  }
440
0
}
441
442
static char units[6][2] = { "", "k", "M", "G", "T", "P" };
443
444
0
static void ls_fmt_filesize(char *buf, size_t buflen, off_t sz) {
445
0
  if (!opt_h || sz < 1000) {
446
0
    pr_snprintf(buf, buflen, "%8" PR_LU, (pr_off_t) sz);
447
448
0
  } else {
449
0
    register unsigned int i = 0;
450
0
    float size = sz;
451
452
    /* Determine the appropriate units label to use. */
453
0
    while (size >= 1024.0) {
454
0
      size /= 1024.0;
455
0
      i++;
456
0
    }
457
458
0
    pr_snprintf(buf, buflen, "%7.1f%s", size, units[i]);
459
0
  }
460
0
}
461
462
static char months[12][4] =
463
  { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
464
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
465
466
static int listfile(cmd_rec *cmd, pool *p, const char *resp_code,
467
0
    const char *name) {
468
0
  register unsigned int i;
469
0
  int rval = 0, len;
470
0
  time_t sort_time;
471
0
  char m[PR_TUNABLE_PATH_MAX+1] = {'\0'}, l[PR_TUNABLE_PATH_MAX+1] = {'\0'}, s[16] = {'\0'};
472
0
  struct stat st;
473
0
  struct tm *t = NULL;
474
0
  char suffix[2];
475
0
  int hidden = 0;
476
0
  char *filename, *ptr;
477
0
  size_t namelen;
478
479
  /* Note that listfile() expects to be given the file name, NOT the path.
480
   * So strip off any path elements, watching out for any trailing slashes
481
   * (Bug#4259).
482
   */
483
0
  namelen = strlen(name);
484
0
  for (i = namelen-1; i > 0; i--) {
485
0
    if (name[i] != '/') {
486
0
      break;
487
0
    }
488
489
0
    namelen--;
490
0
  }
491
492
0
  filename = pstrndup(p, name, namelen);
493
494
0
  ptr = strrchr(filename, '/');
495
0
  if (ptr != NULL) {
496
    /* Advance past that path separator to get just the filename. */
497
0
    filename = ptr + 1;
498
0
  }
499
500
0
  if (list_nfiles.curr && list_nfiles.max &&
501
0
      list_nfiles.curr >= list_nfiles.max) {
502
503
0
    if (!list_nfiles.logged) {
504
0
      pr_log_debug(DEBUG8, "ListOptions maxfiles (%u) reached",
505
0
        list_nfiles.max);
506
0
      list_nfiles.logged = TRUE;
507
0
    }
508
509
0
    return 2;
510
0
  }
511
0
  list_nfiles.curr++;
512
513
0
  if (p == NULL) {
514
0
    p = cmd->tmp_pool;
515
0
  }
516
517
0
  pr_fs_clear_cache2(name);
518
0
  if (pr_fsio_lstat(name, &st) == 0) {
519
0
    char *display_name = NULL;
520
521
0
    suffix[0] = suffix[1] = '\0';
522
523
0
    display_name = pstrdup(p, name);
524
525
0
#ifndef PR_USE_NLS
526
0
    if (opt_B) {
527
0
      register unsigned int j;
528
0
      size_t display_namelen, printable_namelen;
529
0
      char *printable_name = NULL;
530
531
0
      display_namelen = strlen(display_name);
532
533
      /* Allocate 4 times as much space as necessary, in case every single
534
       * character is non-printable.
535
       */
536
0
      printable_namelen = (display_namelen * 4);
537
0
      printable_name = pcalloc(p, printable_namelen + 1);
538
539
      /* Check for any non-printable characters, and replace them with the
540
       * octal escape sequence equivalent.
541
       */
542
0
      for (i = 0, j = 0; i < display_namelen && j < printable_namelen; i++) {
543
0
        if (!PR_ISPRINT(display_name[i])) {
544
0
          register int k;
545
0
          int replace_len = 0;
546
0
          char replace[32];
547
548
0
          memset(replace, '\0', sizeof(replace));
549
0
          replace_len = pr_snprintf(replace, sizeof(replace)-1, "\\%03o",
550
0
            display_name[i]);
551
552
0
          for (k = 0; k < replace_len; k++) {
553
0
            printable_name[j++] = replace[k];
554
0
          }
555
556
0
        } else {
557
0
          printable_name[j++] = display_name[i];
558
0
        }
559
0
      }
560
561
0
      display_name = pstrdup(p, printable_name);
562
0
    }
563
0
#endif /* PR_USE_NLS */
564
565
0
    if (S_ISLNK(st.st_mode) &&
566
0
        (opt_L || !list_show_symlinks)) {
567
      /* Attempt to fully dereference symlink */
568
0
      struct stat l_st;
569
570
0
      if (pr_fsio_stat(name, &l_st) != -1) {
571
0
        memcpy(&st, &l_st, sizeof(struct stat));
572
573
        /* First see if the symlink itself is hidden e.g. by HideFiles
574
         * (see Bug#3924).
575
         */
576
0
        if (!ls_perms_full(p, cmd, name, &hidden)) {
577
0
          return 0;
578
0
        }
579
580
0
        if (hidden) {
581
0
          return 0;
582
0
        }
583
584
0
        if (list_flags & LS_FL_ADJUSTED_SYMLINKS) {
585
0
          len = dir_readlink(p, name, m, sizeof(m) - 1,
586
0
            PR_DIR_READLINK_FL_HANDLE_REL_PATH);
587
588
0
        } else {
589
0
          len = pr_fsio_readlink(name, m, sizeof(m) - 1);
590
0
        }
591
592
0
        if (len < 0) {
593
0
          return 0;
594
0
        }
595
596
0
        if ((size_t) len >= sizeof(m)) {
597
0
          return 0;
598
0
        }
599
600
0
        m[len] = '\0';
601
602
        /* If the symlink points to either '.' or '..', skip it (Bug#3719). */
603
0
        if (is_safe_symlink(p, m, len) == FALSE) {
604
0
          return 0;
605
0
        }
606
607
0
        if (!ls_perms_full(p, cmd, m, NULL)) {
608
0
          return 0;
609
0
        }
610
611
0
      } else {
612
0
        return 0;
613
0
      }
614
615
0
    } else if (S_ISLNK(st.st_mode)) {
616
      /* First see if the symlink itself is hidden e.g. by HideFiles
617
       * (see Bug#3924).
618
       */
619
0
      if (!ls_perms(p, cmd, name, &hidden)) {
620
0
        return 0;
621
0
      }
622
623
0
      if (hidden) {
624
0
        return 0;
625
0
      }
626
627
0
      if (list_flags & LS_FL_ADJUSTED_SYMLINKS) {
628
0
        len = dir_readlink(p, name, l, sizeof(l) - 1,
629
0
          PR_DIR_READLINK_FL_HANDLE_REL_PATH);
630
631
0
      } else {
632
0
        len = pr_fsio_readlink(name, l, sizeof(l) - 1);
633
0
      }
634
635
0
      if (len < 0) {
636
0
        return 0;
637
0
      }
638
639
0
      if ((size_t) len >= sizeof(l)) {
640
0
        return 0;
641
0
      }
642
643
0
      l[len] = '\0';
644
645
      /* If the symlink points to either '.' or '..', skip it (Bug#3719). */
646
0
      if (is_safe_symlink(p, l, len) == FALSE) {
647
0
        return 0;
648
0
      }
649
650
0
      if (!ls_perms_full(p, cmd, l, &hidden)) {
651
0
        return 0;
652
0
      }
653
654
0
    } else if (!ls_perms(p, cmd, name, &hidden)) {
655
0
      return 0;
656
0
    }
657
658
    /* Skip dotfiles, unless requested not to via -a or -A, or if Windows
659
     * ListStyle is in effect.
660
     */
661
0
    if (*filename == '.' &&
662
0
        ((!opt_a && (!opt_A || is_dotdir(filename))) ||
663
0
         list_style == LS_LIST_STYLE_WINDOWS)) {
664
0
      if (list_style == LS_LIST_STYLE_WINDOWS) {
665
0
        pr_log_debug(DEBUG10,
666
0
          "skipping listing of hidden file '%s' (ListStyle Windows in effect)",
667
0
          filename);
668
669
0
      } else {
670
0
        pr_log_debug(DEBUG10,
671
0
          "skipping listing of hidden file '%s' (no -A/-a options in effect)",
672
0
          filename);
673
0
      }
674
675
0
      return 0;
676
0
    }
677
678
0
    if (hidden) {
679
0
      return 0;
680
0
    }
681
682
0
    switch (ls_sort_by) {
683
0
      case LS_SORT_BY_MTIME:
684
0
        sort_time = st.st_mtime;
685
0
        break;
686
687
0
      case LS_SORT_BY_CTIME:
688
0
        sort_time = st.st_ctime;
689
0
        break;
690
691
0
      case LS_SORT_BY_ATIME:
692
0
        sort_time = st.st_atime;
693
0
        break;
694
695
0
      default:
696
0
        sort_time = st.st_mtime;
697
0
        break;
698
0
    }
699
700
0
    if (list_times_gmt) {
701
0
      t = pr_gmtime(p, (const time_t *) &sort_time);
702
703
0
    } else {
704
0
      t = pr_localtime(p, (const time_t *) &sort_time);
705
0
    }
706
707
0
    if (list_style == LS_LIST_STYLE_WINDOWS) {
708
0
      char line_text[(PR_TUNABLE_PATH_MAX * 2) + 128] = {'\0'};
709
0
      char ts_text[18];
710
711
0
      memset(ts_text, '\0', sizeof(ts_text));
712
0
      strftime(ts_text, sizeof(ts_text)-1, "%m-%d-%y  %I:%M%p", t);
713
714
0
      if (S_ISDIR(st.st_mode)) {
715
0
        char dir_text[8];
716
717
0
        memset(dir_text, '\0', sizeof(dir_text));
718
0
        sstrncpy(dir_text, "<DIR>", sizeof(dir_text)-1);
719
720
        /* For Windows directories, we do not include the st.st_size. */
721
0
        pr_snprintf(line_text, sizeof(line_text)-1, "%s%12s%9s %s", ts_text,
722
0
          dir_text, "", display_name);
723
724
0
        rval = 1;
725
726
0
      } else {
727
0
        pr_snprintf(line_text, sizeof(line_text)-1, "%s%12s%9" PR_LU " %s",
728
0
          ts_text, "", (pr_off_t) st.st_size, display_name);
729
0
      }
730
731
0
      addfile(cmd, line_text, suffix, sort_time, st.st_size);
732
0
      return rval;
733
0
    }
734
735
0
    if (opt_F) {
736
0
      if (S_ISLNK(st.st_mode)) {
737
0
        suffix[0] = '@';
738
739
0
      } else if (S_ISDIR(st.st_mode)) {
740
0
        suffix[0] = '/';
741
0
        rval = 1;
742
743
0
      } else if (st.st_mode & 0111) {
744
0
        suffix[0] = '*';
745
0
      }
746
0
    }
747
748
0
    if (opt_l) {
749
0
      sstrncpy(m, " ---------", sizeof(m));
750
0
      switch (st.st_mode & S_IFMT) {
751
0
        case S_IFREG:
752
0
          m[0] = '-';
753
0
          break;
754
755
0
        case S_IFLNK:
756
0
          m[0] = 'l';
757
0
          break;
758
759
0
#ifdef S_IFSOCK
760
0
        case S_IFSOCK:
761
0
          m[0] = 's';
762
0
          break;
763
0
#endif /* S_IFSOCK */
764
765
0
        case S_IFBLK:
766
0
          m[0] = 'b';
767
0
          break;
768
769
0
        case S_IFCHR:
770
0
          m[0] = 'c';
771
0
          break;
772
773
0
        case S_IFIFO:
774
0
          m[0] = 'p';
775
0
          break;
776
777
0
        case S_IFDIR:
778
0
          m[0] = 'd';
779
0
          rval = 1;
780
0
          break;
781
0
      }
782
783
0
      if (m[0] != ' ') {
784
0
        char nameline[(PR_TUNABLE_PATH_MAX * 2) + 128] = {'\0'};
785
0
        char timeline[6] = {'\0'};
786
0
        mode_t mode = st.st_mode;
787
788
0
        if (have_fake_mode) {
789
0
          mode = fakemode;
790
791
0
          if (S_ISDIR(st.st_mode)) {
792
0
            if (mode & S_IROTH) {
793
0
              mode |= S_IXOTH;
794
0
            }
795
796
0
            if (mode & S_IRGRP) {
797
0
              mode |= S_IXGRP;
798
0
            }
799
800
0
            if (mode & S_IRUSR) {
801
0
              mode |= S_IXUSR;
802
0
            }
803
0
          }
804
0
        }
805
806
0
        m[9] = (mode & S_IXOTH)
807
0
                ? ((mode & S_ISVTX) ? 't' : 'x')
808
0
                : ((mode & S_ISVTX) ? 'T' : '-');
809
0
        m[8] = (mode & S_IWOTH) ? 'w' : '-';
810
0
        m[7] = (mode & S_IROTH) ? 'r' : '-';
811
0
        m[6] = (mode & S_IXGRP)
812
0
                ? ((mode & S_ISGID) ? 's' : 'x')
813
0
                : ((mode & S_ISGID) ? 'S' : '-');
814
0
        m[5] = (mode & S_IWGRP) ? 'w' : '-';
815
0
        m[4] = (mode & S_IRGRP) ? 'r' : '-';
816
0
        m[3] = (mode & S_IXUSR) ? ((mode & S_ISUID)
817
0
                ? 's' : 'x')
818
0
                :  ((mode & S_ISUID) ? 'S' : '-');
819
0
        m[2] = (mode & S_IWUSR) ? 'w' : '-';
820
0
        m[1] = (mode & S_IRUSR) ? 'r' : '-';
821
822
0
        if (ls_curtime - sort_time > 180 * 24 * 60 * 60) {
823
0
          pr_snprintf(timeline, sizeof(timeline), "%5d", t->tm_year+1900);
824
825
0
        } else {
826
0
          pr_snprintf(timeline, sizeof(timeline), "%02d:%02d", t->tm_hour,
827
0
            t->tm_min);
828
0
        }
829
830
0
        ls_fmt_filesize(s, sizeof(s), st.st_size);
831
832
0
        if (opt_1) {
833
          /* One file per line, with no info other than the file name.  Easy. */
834
0
          pr_snprintf(nameline, sizeof(nameline)-1, "%s",
835
0
            pr_fs_encode_path(cmd->tmp_pool, display_name));
836
837
0
        } else {
838
0
          if (!opt_n) {
839
            /* Format nameline using user/group names. */
840
0
            pr_snprintf(nameline, sizeof(nameline)-1,
841
0
              "%s %3d %-8s %-8s %s %s %2d %s %s", m, (int) st.st_nlink,
842
0
              MAP_UID(st.st_uid), MAP_GID(st.st_gid), s,
843
0
              months[t->tm_mon], t->tm_mday, timeline,
844
0
              pr_fs_encode_path(cmd->tmp_pool, display_name));
845
846
0
          } else {
847
            /* Format nameline using user/group IDs. */
848
0
            pr_snprintf(nameline, sizeof(nameline)-1,
849
0
              "%s %3d %-8u %-8u %s %s %2d %s %s", m, (int) st.st_nlink,
850
0
              (unsigned) st.st_uid, (unsigned) st.st_gid, s,
851
0
              months[t->tm_mon], t->tm_mday, timeline,
852
0
              pr_fs_encode_path(cmd->tmp_pool, name));
853
0
          }
854
0
        }
855
856
0
        nameline[sizeof(nameline)-1] = '\0';
857
858
0
        if (S_ISLNK(st.st_mode)) {
859
0
          char *buf = nameline + strlen(nameline);
860
861
0
          suffix[0] = '\0';
862
0
          if (opt_F) {
863
0
            if (pr_fsio_stat(name, &st) == 0) {
864
0
              if (S_ISLNK(st.st_mode)) {
865
0
                suffix[0] = '@';
866
867
0
              } else if (S_ISDIR(st.st_mode)) {
868
0
                suffix[0] = '/';
869
870
0
              } else if (st.st_mode & 0111) {
871
0
                suffix[0] = '*';
872
0
              }
873
0
           }
874
0
          }
875
876
0
          if (!opt_L && list_show_symlinks) {
877
0
            if (sizeof(nameline) - strlen(nameline) > 4) {
878
0
              pr_snprintf(buf, sizeof(nameline) - strlen(nameline) - 4,
879
0
                " -> %s", l);
880
0
            } else {
881
0
              pr_log_pri(PR_LOG_NOTICE, "notice: symlink '%s' yields an "
882
0
                "excessive string, ignoring", name);
883
0
            }
884
0
          }
885
886
0
          nameline[sizeof(nameline)-1] = '\0';
887
0
        }
888
889
0
        if (opt_STAT) {
890
0
          pr_response_add(resp_code, "%s%s", nameline, suffix);
891
892
0
        } else {
893
0
          addfile(cmd, nameline, suffix, sort_time, st.st_size);
894
0
        }
895
0
      }
896
897
0
    } else {
898
0
      if (S_ISREG(st.st_mode) ||
899
0
          S_ISDIR(st.st_mode) ||
900
0
          S_ISLNK(st.st_mode)) {
901
0
        addfile(cmd, pr_fs_encode_path(cmd->tmp_pool, name), suffix, sort_time,
902
0
          st.st_size);
903
0
      }
904
0
    }
905
0
  }
906
907
0
  return rval;
908
0
}
909
910
static size_t colwidth = 0;
911
static unsigned int filenames = 0;
912
913
struct filename {
914
  struct filename *down;
915
  struct filename *right;
916
  char *line;
917
  int top;
918
};
919
920
struct sort_filename {
921
  time_t sort_time;
922
  off_t size;
923
  char *name;
924
  char *suffix;
925
};
926
927
static struct filename *head = NULL;
928
static struct filename *tail = NULL;
929
static array_header *sort_arr = NULL;
930
static pool *fpool = NULL;
931
932
static void addfile(cmd_rec *cmd, const char *name, const char *suffix,
933
0
    time_t sort_time, off_t size) {
934
0
  struct filename *p;
935
0
  size_t l;
936
937
0
  if (name == NULL ||
938
0
      suffix == NULL) {
939
0
    return;
940
0
  }
941
942
  /* If we are not sorting (-U is in effect), then we have no need to buffer
943
   * up the line, and can send it immediately.  This can provide quite a bit
944
   * of memory/CPU savings, especially for LIST commands on wide/deep
945
   * directories (Bug#4060).
946
   */
947
0
  if (opt_U == 1) {
948
0
    (void) sendline(0, "%s%s\r\n", name, suffix);
949
0
    return;
950
0
  }
951
952
0
  if (fpool == NULL) {
953
0
    fpool = make_sub_pool(cmd->tmp_pool);
954
0
    pr_pool_tag(fpool, "mod_ls addfile pool");
955
0
  }
956
957
0
  if (opt_S || opt_t) {
958
0
    struct sort_filename *s;
959
960
0
    if (sort_arr == NULL) {
961
0
      sort_arr = make_array(fpool, 50, sizeof(struct sort_filename));
962
0
    }
963
964
0
    s = (struct sort_filename *) push_array(sort_arr);
965
0
    s->sort_time = sort_time;
966
0
    s->size = size;
967
0
    s->name = pstrdup(fpool, name);
968
0
    s->suffix = pstrdup(fpool, suffix);
969
970
0
    return;
971
0
  }
972
973
0
  l = strlen(name) + strlen(suffix);
974
0
  if (l > colwidth) {
975
0
    colwidth = l;
976
0
  }
977
978
0
  p = (struct filename *) pcalloc(fpool, sizeof(struct filename));
979
0
  p->line = pcalloc(fpool, l + 2);
980
0
  pr_snprintf(p->line, l + 1, "%s%s", name, suffix);
981
982
0
  if (tail) {
983
0
    tail->down = p;
984
985
0
  } else {
986
0
    head = p;
987
0
  }
988
989
0
  tail = p;
990
0
  filenames++;
991
0
}
992
993
static int file_time_cmp(const struct sort_filename *f1,
994
0
    const struct sort_filename *f2) {
995
996
0
  if (f1->sort_time > f2->sort_time) {
997
0
    return -1;
998
0
  }
999
1000
0
  if (f1->sort_time < f2->sort_time) {
1001
0
    return 1;
1002
0
  }
1003
1004
0
  return 0;
1005
0
}
1006
1007
static int file_time_reverse_cmp(const struct sort_filename *f1,
1008
0
    const struct sort_filename *f2) {
1009
0
  return -file_time_cmp(f1, f2);
1010
0
}
1011
1012
static int file_size_cmp(const struct sort_filename *f1,
1013
0
    const struct sort_filename *f2) {
1014
1015
0
  if (f1->size > f2->size) {
1016
0
    return -1;
1017
0
  }
1018
1019
0
  if (f1->size < f2->size) {
1020
0
    return 1;
1021
0
  }
1022
1023
0
  return 0;
1024
0
}
1025
1026
static int file_size_reverse_cmp(const struct sort_filename *f1,
1027
0
    const struct sort_filename *f2) {
1028
0
  return -file_size_cmp(f1, f2);
1029
0
}
1030
1031
0
static void sortfiles(cmd_rec *cmd) {
1032
1033
0
  if (sort_arr) {
1034
1035
    /* Sort by time? */
1036
0
    if (opt_t) {
1037
0
      register unsigned int i = 0;
1038
0
      int setting = opt_S;
1039
0
      struct sort_filename *elts = sort_arr->elts;
1040
1041
0
      qsort(sort_arr->elts, sort_arr->nelts, sizeof(struct sort_filename),
1042
0
        (int (*)(const void *, const void *))
1043
0
          (opt_r ? file_time_reverse_cmp : file_time_cmp));
1044
1045
0
      opt_S = opt_t = 0;
1046
1047
0
      for (i = 0; i < sort_arr->nelts; i++) {
1048
0
        addfile(cmd, elts[i].name, elts[i].suffix, elts[i].sort_time,
1049
0
          elts[i].size);
1050
0
      }
1051
1052
0
      opt_S = setting;
1053
0
      opt_t = 1;
1054
1055
    /* Sort by file size? */
1056
0
    } else if (opt_S) {
1057
0
      register unsigned int i = 0;
1058
0
      int setting = opt_t;
1059
0
      struct sort_filename *elts = sort_arr->elts;
1060
1061
0
      qsort(sort_arr->elts, sort_arr->nelts, sizeof(struct sort_filename),
1062
0
        (int (*)(const void *, const void *))
1063
0
          (opt_r ? file_size_reverse_cmp : file_size_cmp));
1064
1065
0
      opt_S = opt_t = 0;
1066
1067
0
      for (i = 0; i < sort_arr->nelts; i++) {
1068
0
        addfile(cmd, elts[i].name, elts[i].suffix, elts[i].sort_time,
1069
0
          elts[i].size);
1070
0
      }
1071
1072
0
      opt_S = 1;
1073
0
      opt_t = setting;
1074
0
    }
1075
0
  }
1076
1077
0
  sort_arr = NULL;
1078
0
}
1079
1080
0
static int outputfiles(cmd_rec *cmd) {
1081
0
  int n, res = 0;
1082
0
  struct filename *p = NULL, *q = NULL;
1083
1084
0
  if (opt_S || opt_t) {
1085
0
    sortfiles(cmd);
1086
0
  }
1087
1088
0
  if (head == NULL) {
1089
    /* Nothing to display. */
1090
0
    if (sendline(LS_SENDLINE_FL_FLUSH, " ") < 0) {
1091
0
      res = -1;
1092
0
    }
1093
1094
0
    destroy_pool(fpool);
1095
0
    fpool = NULL;
1096
0
    sort_arr = NULL;
1097
0
    head = tail = NULL;
1098
0
    colwidth = 0;
1099
0
    filenames = 0;
1100
1101
0
    return res;
1102
0
  }
1103
1104
0
  if (tail != NULL) {
1105
0
    tail->down = NULL;
1106
0
  }
1107
0
  tail = NULL;
1108
0
  colwidth = (colwidth | 7) + 1;
1109
0
  if (opt_l || !opt_C) {
1110
0
    colwidth = 75;
1111
0
  }
1112
1113
  /* avoid division by 0 if colwidth > 75 */
1114
0
  if (colwidth > 75) {
1115
0
    colwidth = 75;
1116
0
  }
1117
1118
0
  if (opt_C) {
1119
0
    p = head;
1120
0
    p->top = 1;
1121
0
    n = (filenames + (75 / colwidth)-1) / (75 / colwidth);
1122
1123
0
    while (n && p) {
1124
0
      pr_signals_handle();
1125
1126
0
      p = p->down;
1127
0
      if (p) {
1128
0
        p->top = 0;
1129
0
      }
1130
0
      n--;
1131
0
    }
1132
1133
0
    q = head;
1134
0
    while (p) {
1135
0
      pr_signals_handle();
1136
1137
0
      p->top = q->top;
1138
0
      q->right = p;
1139
0
      q = q->down;
1140
0
      p = p->down;
1141
0
    }
1142
1143
0
    while (q) {
1144
0
      pr_signals_handle();
1145
1146
0
      q->right = NULL;
1147
0
      q = q->down;
1148
0
    }
1149
1150
0
    p = head;
1151
0
    while (p && p->down && !p->down->top) {
1152
0
      pr_signals_handle();
1153
0
      p = p->down;
1154
0
    }
1155
1156
0
    if (p && p->down) {
1157
0
      p->down = NULL;
1158
0
    }
1159
0
  }
1160
1161
0
  p = head;
1162
0
  while (p) {
1163
0
    pr_signals_handle();
1164
1165
0
    q = p;
1166
0
    p = p->down;
1167
0
    while (q) {
1168
0
      char pad[6] = {'\0'};
1169
1170
0
      pr_signals_handle();
1171
1172
0
      if (!q->right) {
1173
0
        sstrncpy(pad, "\r\n", sizeof(pad));
1174
1175
0
      } else {
1176
0
        unsigned int idx = 0;
1177
1178
0
        sstrncpy(pad, "\t\t\t\t\t", sizeof(pad));
1179
1180
0
        idx = (colwidth + 7 - strlen(q->line)) / 8;
1181
0
        if (idx >= sizeof(pad)) {
1182
0
          idx = sizeof(pad)-1;
1183
0
        }
1184
1185
0
        pad[idx] = '\0';
1186
0
      }
1187
1188
0
      if (sendline(0, "%s%s", q->line, pad) < 0) {
1189
0
        return -1;
1190
0
      }
1191
1192
0
      q = q->right;
1193
0
    }
1194
0
  }
1195
1196
0
  if (sendline(LS_SENDLINE_FL_FLUSH, " ") < 0) {
1197
0
    res = -1;
1198
0
  }
1199
1200
0
  destroy_pool(fpool);
1201
0
  fpool = NULL;
1202
0
  sort_arr = NULL;
1203
0
  head = tail = NULL;
1204
0
  colwidth = 0;
1205
0
  filenames = 0;
1206
1207
0
  return res;
1208
0
}
1209
1210
0
static void discard_output(void) {
1211
0
  if (fpool) {
1212
0
    destroy_pool(fpool);
1213
0
  }
1214
0
  fpool = NULL;
1215
1216
0
  head = tail = NULL;
1217
0
  colwidth = 0;
1218
0
  filenames = 0;
1219
0
}
1220
1221
0
static int dircmp(const void *a, const void *b) {
1222
#if defined(PR_USE_NLS) && defined(HAVE_STRCOLL)
1223
  return strcoll(*(const char **)a, *(const char **)b);
1224
#else
1225
0
  return strcmp(*(const char **)a, *(const char **)b);
1226
0
#endif /* !PR_USE_NLS or !HAVE_STRCOLL */
1227
0
}
1228
1229
0
static char **sreaddir(const char *dirname, const int sort) {
1230
0
  DIR *d;
1231
0
  struct dirent *de;
1232
0
  struct stat st;
1233
0
  int i;
1234
0
  char **p;
1235
0
  size_t dsize;
1236
1237
0
  pr_fs_clear_cache2(dirname);
1238
0
  if (pr_fsio_stat(dirname, &st) < 0) {
1239
0
    return NULL;
1240
0
  }
1241
1242
0
  if (!S_ISDIR(st.st_mode)) {
1243
0
    errno = ENOTDIR;
1244
0
    return NULL;
1245
0
  }
1246
1247
0
  d = pr_fsio_opendir(dirname);
1248
0
  if (d == NULL) {
1249
0
    return NULL;
1250
0
  }
1251
1252
  /* It doesn't matter if the following guesses are wrong, but it slows
1253
   * the system a bit and wastes some memory if they are wrong, so
1254
   * don't guess *too* naively!
1255
   *
1256
   * 'dsize' must be greater than zero or we loop forever.
1257
   */
1258
1259
  /* Guess the number of entries in the directory. */
1260
0
  dsize = (((size_t) st.st_size) / 4) + 10;
1261
0
  if (dsize > LS_MAX_DSIZE) {
1262
0
    dsize = LS_MAX_DSIZE;
1263
0
  }
1264
1265
  /* Allocate first block for holding filenames.  Yes, we are explicitly using
1266
   * malloc (and realloc, and calloc, later) rather than the memory pools.
1267
   * Recursive directory listings would eat up a lot of pool memory that is
1268
   * only freed when the _entire_ directory structure has been parsed.  Also,
1269
   * this helps to keep the memory footprint a little smaller.
1270
   */
1271
0
  pr_trace_msg("data", 8, "allocating readdir buffer of %lu bytes",
1272
0
    (unsigned long) (dsize * sizeof(char *)));
1273
1274
0
  p = malloc(dsize * sizeof(char *));
1275
0
  if (p == NULL) {
1276
0
    pr_log_pri(PR_LOG_ALERT, "Out of memory!");
1277
0
    exit(1);
1278
0
  }
1279
1280
0
  i = 0;
1281
1282
0
  while ((de = pr_fsio_readdir(d)) != NULL) {
1283
0
    pr_signals_handle();
1284
1285
0
    if ((size_t) i >= dsize - 1) {
1286
0
      char **newp;
1287
1288
      /* The test above goes off one item early in case this is the last item
1289
       * in the directory and thus next time we will want to NULL-terminate
1290
       * the array.
1291
       */
1292
0
      pr_log_debug(DEBUG0, "Reallocating sreaddir buffer from %lu entries to "
1293
0
        "%lu entries", (unsigned long) dsize, (unsigned long) dsize * 2);
1294
1295
      /* Allocate bigger array for pointers to filenames */
1296
0
      pr_trace_msg("data", 8, "allocating readdir buffer of %lu bytes",
1297
0
        (unsigned long) (2 * dsize * sizeof(char *)));
1298
1299
0
      newp = (char **) realloc(p, 2 * dsize * sizeof(char *));
1300
0
      if (newp == NULL) {
1301
0
        pr_log_pri(PR_LOG_ALERT, "Out of memory!");
1302
0
        exit(1);
1303
0
      }
1304
0
      p = newp;
1305
0
      dsize *= 2;
1306
0
    }
1307
1308
    /* Append the filename to the block. */
1309
0
    p[i] = (char *) calloc(strlen(de->d_name) + 1, sizeof(char));
1310
0
    if (p[i] == NULL) {
1311
0
      pr_log_pri(PR_LOG_ALERT, "Out of memory!");
1312
0
      exit(1);
1313
0
    }
1314
0
    sstrncpy(p[i++], de->d_name, strlen(de->d_name) + 1);
1315
0
  }
1316
1317
0
  pr_fsio_closedir(d);
1318
1319
  /* This is correct, since the above is off by one element.
1320
   */
1321
0
  p[i] = NULL;
1322
1323
0
  if (sort) {
1324
0
    PR_DEVEL_CLOCK(qsort(p, i, sizeof(char *), dircmp));
1325
0
  }
1326
1327
0
  return p;
1328
0
}
1329
1330
/* This listdir() requires a chdir() first. */
1331
static int listdir(cmd_rec *cmd, pool *workp, const char *resp_code,
1332
0
    const char *name) {
1333
0
  char **dir;
1334
0
  int dest_workp = 0;
1335
0
  register unsigned int i = 0;
1336
1337
0
  if (list_ndepth.curr && list_ndepth.max &&
1338
0
      list_ndepth.curr >= list_ndepth.max) {
1339
1340
0
    if (!list_ndepth.logged) {
1341
      /* Don't forget to take away the one we add to maxdepth internally. */
1342
0
      pr_log_debug(DEBUG8, "ListOptions maxdepth (%u) reached",
1343
0
        list_ndepth.max - 1);
1344
0
      list_ndepth.logged = TRUE;
1345
0
    }
1346
1347
0
    return 1;
1348
0
  }
1349
1350
0
  if (list_ndirs.curr && list_ndirs.max &&
1351
0
      list_ndirs.curr >= list_ndirs.max) {
1352
1353
0
    if (!list_ndirs.logged) {
1354
0
      pr_log_debug(DEBUG8, "ListOptions maxdirs (%u) reached", list_ndirs.max);
1355
0
      list_ndirs.logged = TRUE;
1356
0
    }
1357
1358
0
    return 1;
1359
0
  }
1360
0
  list_ndirs.curr++;
1361
1362
0
  if (XFER_ABORTED) {
1363
0
    return -1;
1364
0
  }
1365
1366
0
  if (workp == NULL) {
1367
0
    workp = make_sub_pool(cmd->tmp_pool);
1368
0
    pr_pool_tag(workp, "mod_ls: listdir(): workp (from cmd->tmp_pool)");
1369
0
    dest_workp++;
1370
1371
0
  } else {
1372
0
    workp = make_sub_pool(workp);
1373
0
    pr_pool_tag(workp, "mod_ls: listdir(): workp (from workp)");
1374
0
    dest_workp++;
1375
0
  }
1376
1377
0
  PR_DEVEL_CLOCK(dir = sreaddir(".", opt_U ? FALSE : TRUE));
1378
0
  if (dir != NULL) {
1379
0
    char **s;
1380
0
    char **r;
1381
1382
0
    int d = 0;
1383
1384
0
    s = dir;
1385
0
    while (*s) {
1386
0
      pr_signals_handle();
1387
1388
0
      if (**s == '.') {
1389
0
        if (!opt_a && (!opt_A || is_dotdir(*s))) {
1390
0
          d = 0;
1391
1392
0
        } else {
1393
0
          d = listfile(cmd, workp, resp_code, *s);
1394
0
        }
1395
1396
0
      } else {
1397
0
        d = listfile(cmd, workp, resp_code, *s);
1398
0
      }
1399
1400
0
      if (opt_R && d == 0) {
1401
1402
        /* This is a nasty hack.  If listfile() returns a zero, and we
1403
         * will be recursing (-R option), make sure we don't try to list
1404
         * this file again by changing the first character of the path
1405
         * to ".".  Such files are skipped later.
1406
         */
1407
0
        **s = '.';
1408
0
        *(*s + 1) = '\0';
1409
1410
0
      } else if (d == 2) {
1411
0
        break;
1412
0
      }
1413
1414
0
      s++;
1415
0
    }
1416
1417
0
    if (outputfiles(cmd) < 0) {
1418
0
      if (dest_workp) {
1419
0
        destroy_pool(workp);
1420
0
      }
1421
1422
      /* Explicitly free the memory allocated for containing the list of
1423
       * filenames.
1424
       */
1425
0
      i = 0;
1426
0
      while (dir[i] != NULL) {
1427
0
        pr_signals_handle();
1428
0
        free(dir[i++]);
1429
0
      }
1430
0
      free(dir);
1431
1432
0
      return -1;
1433
0
    }
1434
1435
0
    r = dir;
1436
0
    while (opt_R && r != s) {
1437
0
      char cwd_buf[PR_TUNABLE_PATH_MAX + 1] = {'\0'};
1438
0
      unsigned char symhold;
1439
1440
0
      if (*r && (strcmp(*r, ".") == 0 || strcmp(*r, "..") == 0)) {
1441
0
        r++;
1442
0
        continue;
1443
0
      }
1444
1445
      /* Add some signal processing to this while loop, as it can
1446
       * potentially recurse deeply.
1447
       */
1448
0
      pr_signals_handle();
1449
1450
0
      if (list_ndirs.curr && list_ndirs.max &&
1451
0
          list_ndirs.curr >= list_ndirs.max) {
1452
1453
0
        if (!list_ndirs.logged) {
1454
0
          pr_log_debug(DEBUG8, "ListOptions maxdirs (%u) reached",
1455
0
            list_ndirs.max);
1456
0
          list_ndirs.logged = TRUE;
1457
0
        }
1458
1459
0
        break;
1460
0
      }
1461
1462
0
      if (list_nfiles.curr && list_nfiles.max &&
1463
0
          list_nfiles.curr >= list_nfiles.max) {
1464
1465
0
        if (!list_nfiles.logged) {
1466
0
          pr_log_debug(DEBUG8, "ListOptions maxfiles (%u) reached",
1467
0
            list_nfiles.max);
1468
0
          list_nfiles.logged = TRUE;
1469
0
        }
1470
1471
0
        break;
1472
0
      }
1473
1474
0
      push_cwd(cwd_buf, &symhold);
1475
1476
0
      if (*r && ls_perms_full(workp, cmd, (char *) *r, NULL) &&
1477
0
          !pr_fsio_chdir_canon(*r, !opt_L && list_show_symlinks)) {
1478
0
        char *subdir;
1479
0
        int res = 0;
1480
1481
0
        if (strcmp(name, ".") == 0) {
1482
0
          subdir = *r;
1483
1484
0
        } else {
1485
0
          subdir = pdircat(workp, name, *r, NULL);
1486
0
        }
1487
1488
0
        if (opt_STAT) {
1489
0
          pr_response_add(resp_code, "%s", "");
1490
0
          pr_response_add(resp_code, "%s:",
1491
0
            pr_fs_encode_path(cmd->tmp_pool, subdir));
1492
1493
0
        } else if (sendline(0, "\r\n%s:\r\n",
1494
0
                   pr_fs_encode_path(cmd->tmp_pool, subdir)) < 0 ||
1495
0
            sendline(LS_SENDLINE_FL_FLUSH, " ") < 0) {
1496
0
          pop_cwd(cwd_buf, &symhold);
1497
1498
0
          if (dest_workp) {
1499
0
            destroy_pool(workp);
1500
0
          }
1501
1502
          /* Explicitly free the memory allocated for containing the list of
1503
           * filenames.
1504
           */
1505
0
          i = 0;
1506
0
          while (dir[i] != NULL) {
1507
0
            pr_signals_handle();
1508
0
            free(dir[i++]);
1509
0
          }
1510
0
          free(dir);
1511
1512
0
          return -1;
1513
0
        }
1514
1515
0
        list_ndepth.curr++;
1516
0
        res = listdir(cmd, workp, resp_code, subdir);
1517
0
        list_ndepth.curr--;
1518
0
        pop_cwd(cwd_buf, &symhold);
1519
1520
0
        if (res > 0) {
1521
0
          break;
1522
0
        }
1523
1524
0
        if (res < 0) {
1525
0
          if (dest_workp) {
1526
0
            destroy_pool(workp);
1527
0
          }
1528
1529
          /* Explicitly free the memory allocated for containing the list of
1530
           * filenames.
1531
           */
1532
0
          i = 0;
1533
0
          while (dir[i] != NULL) {
1534
0
            pr_signals_handle();
1535
0
            free(dir[i++]);
1536
0
          }
1537
0
          free(dir);
1538
1539
0
          return -1;
1540
0
        }
1541
0
      }
1542
0
      r++;
1543
0
    }
1544
1545
0
  } else {
1546
0
    pr_trace_msg("fsio", 9,
1547
0
      "sreaddir() error on '.': %s", strerror(errno));
1548
0
  }
1549
1550
0
  if (dest_workp) {
1551
0
    destroy_pool(workp);
1552
0
  }
1553
1554
  /* Explicitly free the memory allocated for containing the list of
1555
   * filenames.
1556
   */
1557
0
  if (dir != NULL) {
1558
0
    i = 0;
1559
0
    while (dir[i] != NULL) {
1560
0
      pr_signals_handle();
1561
0
      free(dir[i++]);
1562
0
    }
1563
0
    free(dir);
1564
0
  }
1565
1566
0
  return 0;
1567
0
}
1568
1569
0
static void ls_terminate(void) {
1570
0
  if (!opt_STAT) {
1571
0
    discard_output();
1572
1573
0
    if (!XFER_ABORTED) {
1574
      /* An error has occurred, other than client ABOR */
1575
0
      if (ls_errno) {
1576
0
        pr_data_abort(ls_errno,FALSE);
1577
1578
0
      } else {
1579
0
        pr_data_abort((session.d && session.d->outstrm ?
1580
0
                      PR_NETIO_ERRNO(session.d->outstrm) : errno), FALSE);
1581
0
      }
1582
0
    }
1583
0
    ls_errno = 0;
1584
1585
0
  } else if (ls_errno) {
1586
0
    pr_response_add(R_211, _("ERROR: %s"), strerror(ls_errno));
1587
0
    ls_errno = 0;
1588
0
  }
1589
0
}
1590
1591
0
static void parse_list_opts(char **opt, int *glob_flags, int handle_plus_opts) {
1592
0
  char *ptr;
1593
1594
  /* First, scan for options.  Any leading whitespace before options can
1595
   * be skipped, as long as there ARE options.
1596
   */
1597
0
  ptr = *opt;
1598
1599
0
  while (PR_ISSPACE(*ptr)) {
1600
0
    pr_signals_handle();
1601
0
    ptr++;
1602
0
  }
1603
1604
0
  if (*ptr == '-') {
1605
    /* Options are found; skip past the leading whitespace. */
1606
0
    *opt = ptr;
1607
0
  }
1608
1609
  /* Check for standard /bin/ls options */
1610
0
  while (*opt && **opt == '-') {
1611
0
    pr_signals_handle();
1612
1613
0
    while ((*opt)++ && PR_ISALNUM(**opt)) {
1614
0
      switch (**opt) {
1615
0
        case '1':
1616
0
          if (session.curr_cmd_id != PR_CMD_STAT_ID) {
1617
0
            opt_1 = 1;
1618
0
            opt_l = opt_C = 0;
1619
0
          }
1620
0
          break;
1621
1622
0
        case 'A':
1623
0
          opt_A = 1;
1624
0
          break;
1625
1626
0
        case 'a':
1627
0
          opt_a = 1;
1628
0
          break;
1629
1630
0
        case 'B':
1631
0
          opt_B = 1;
1632
0
          break;
1633
1634
0
        case 'C':
1635
0
          if (session.curr_cmd_id != PR_CMD_NLST_ID) {
1636
0
            opt_l = 0;
1637
0
            opt_C = 1;
1638
0
          }
1639
0
          break;
1640
1641
0
        case 'c':
1642
0
          opt_c = 1;
1643
0
          ls_sort_by = LS_SORT_BY_CTIME;
1644
0
          break;
1645
1646
0
        case 'd':
1647
0
          opt_d = 1;
1648
0
          break;
1649
1650
0
        case 'F':
1651
0
          if (session.curr_cmd_id != PR_CMD_NLST_ID) {
1652
0
            opt_F = 1;
1653
0
          }
1654
0
          break;
1655
1656
0
        case 'h':
1657
0
          if (session.curr_cmd_id != PR_CMD_NLST_ID) {
1658
0
            opt_h = 1;
1659
0
          }
1660
0
          break;
1661
1662
0
        case 'L':
1663
0
          opt_L = 1;
1664
0
          break;
1665
1666
0
        case 'l':
1667
0
          if (session.curr_cmd_id != PR_CMD_NLST_ID) {
1668
0
            opt_l = 1;
1669
0
            opt_C = 0;
1670
0
            opt_1 = 0;
1671
0
          }
1672
0
          break;
1673
1674
0
        case 'n':
1675
0
          if (session.curr_cmd_id != PR_CMD_NLST_ID) {
1676
0
            opt_n = 1;
1677
0
          }
1678
0
          break;
1679
1680
0
        case 'R':
1681
0
          opt_R = 1;
1682
0
          break;
1683
1684
0
        case 'r':
1685
0
          opt_r = 1;
1686
0
          break;
1687
1688
0
        case 'S':
1689
0
          opt_S = 1;
1690
0
          break;
1691
1692
0
        case 't':
1693
0
          opt_t = 1;
1694
0
          if (glob_flags) {
1695
0
            *glob_flags |= GLOB_NOSORT;
1696
0
          }
1697
0
          break;
1698
1699
0
        case 'U':
1700
0
          opt_U = 1;
1701
0
          opt_c = opt_S = opt_t = 0;
1702
0
          break;
1703
1704
0
        case 'u':
1705
0
          opt_u = 1;
1706
0
          ls_sort_by = LS_SORT_BY_ATIME;
1707
0
          break;
1708
0
      }
1709
0
    }
1710
1711
0
    ptr = *opt;
1712
1713
0
    while (*ptr &&
1714
0
           PR_ISSPACE(*ptr)) {
1715
0
      pr_signals_handle();
1716
0
      ptr++;
1717
0
    }
1718
1719
0
    if (*ptr == '-') {
1720
      /* Options are found; skip past the leading whitespace. */
1721
0
      *opt = ptr;
1722
1723
0
    } else if (**opt && *(*opt + 1) == ' ') {
1724
      /* If the next character is a blank space, advance just one character. */
1725
0
      (*opt)++;
1726
0
      break;
1727
1728
0
    } else {
1729
0
      *opt = ptr;
1730
0
      break;
1731
0
    }
1732
0
  }
1733
1734
0
  if (!handle_plus_opts) {
1735
0
    return;
1736
0
  }
1737
1738
  /* Check for non-standard options */
1739
0
  while (*opt && **opt == '+') {
1740
0
    pr_signals_handle();
1741
1742
0
    while ((*opt)++ && PR_ISALNUM(**opt)) {
1743
0
      switch (**opt) {
1744
0
        case '1':
1745
0
          opt_1 = opt_l = opt_C = 0;
1746
0
          break;
1747
1748
0
        case 'A':
1749
0
          opt_A = 0;
1750
0
          break;
1751
1752
0
        case 'a':
1753
0
          opt_a = 0;
1754
0
          break;
1755
1756
0
        case 'B':
1757
0
          opt_B = 0;
1758
0
          break;
1759
1760
0
        case 'C':
1761
0
          opt_l = opt_C = 0;
1762
0
          break;
1763
1764
0
        case 'c':
1765
0
          opt_c = 0;
1766
1767
          /* -u is still in effect, sort by that, otherwise use the default. */
1768
0
          ls_sort_by = opt_u ? LS_SORT_BY_ATIME : LS_SORT_BY_MTIME;
1769
0
          break;
1770
1771
0
        case 'd':
1772
0
          opt_d = 0;
1773
0
          break;
1774
1775
0
        case 'F':
1776
0
          opt_F = 0;
1777
0
          break;
1778
1779
0
        case 'h':
1780
0
          opt_h = 0;
1781
0
          break;
1782
1783
0
        case 'L':
1784
0
          opt_L = 0;
1785
0
          break;
1786
1787
0
        case 'l':
1788
0
          opt_l = opt_C = 0;
1789
0
          break;
1790
1791
0
        case 'n':
1792
0
          opt_n = 0;
1793
0
          break;
1794
1795
0
        case 'R':
1796
0
          opt_R = 0;
1797
0
          break;
1798
1799
0
        case 'r':
1800
0
          opt_r = 0;
1801
0
          break;
1802
1803
0
        case 'S':
1804
0
          opt_S = 0;
1805
0
          break;
1806
1807
0
        case 't':
1808
0
          opt_t = 0;
1809
0
          if (glob_flags) {
1810
0
            *glob_flags &= GLOB_NOSORT;
1811
0
          }
1812
0
          break;
1813
1814
0
        case 'U':
1815
0
          opt_U = 0;
1816
0
          break;
1817
1818
0
        case 'u':
1819
0
          opt_u = 0;
1820
1821
          /* -c is still in effect, sort by that, otherwise use the default. */
1822
0
          ls_sort_by = opt_c ? LS_SORT_BY_CTIME : LS_SORT_BY_MTIME;
1823
0
          break;
1824
0
      }
1825
0
    }
1826
1827
0
    ptr = *opt;
1828
1829
0
    while (*ptr &&
1830
0
           PR_ISSPACE(*ptr)) {
1831
0
      pr_signals_handle();
1832
0
      ptr++;
1833
0
    }
1834
1835
0
    if (*ptr == '+') {
1836
      /* Options are found; skip past the leading whitespace. */
1837
0
      *opt = ptr;
1838
1839
0
    } else if (**opt && *(*opt + 1) == ' ') {
1840
      /* If the next character is a blank space, advance just one character. */
1841
0
      (*opt)++;
1842
0
      break;
1843
1844
0
    } else {
1845
0
      *opt = ptr;
1846
0
      break;
1847
0
    }
1848
0
  }
1849
0
}
1850
1851
/* Only look for and parse options if there are more than two arguments.
1852
 * This will avoid trying to handle the file/path in a command like:
1853
 *
1854
 *  LIST -filename
1855
 *
1856
 * as if it were options.
1857
 *
1858
 * Returns TRUE if the given command has options that should be parsed,
1859
 * FALSE otherwise.
1860
 */
1861
0
static int have_options(cmd_rec *cmd, const char *arg) {
1862
0
  struct stat st;
1863
0
  int res;
1864
1865
  /* If we have more than 2 arguments, then we definitely have parseable
1866
   * options.
1867
   */
1868
1869
0
  if (cmd->argc > 2) {
1870
0
    return TRUE;
1871
0
  }
1872
1873
  /* Now we need to determine if the given string (arg) should be handled
1874
   * as options (as when the target path is implied, e.g. "LIST -al") or
1875
   * as a real path.  We'll simply do a stat on the string; if it exists,
1876
   * then it's a path.
1877
   */
1878
1879
0
  pr_fs_clear_cache2(arg);
1880
0
  res = pr_fsio_stat(arg, &st);
1881
1882
0
  if (res == 0) {
1883
0
    return FALSE;
1884
0
  }
1885
1886
0
  return TRUE;
1887
0
}
1888
1889
/* The main work for LIST and STAT (not NLST).  Returns -1 on error, 0 if
1890
 * successful.
1891
 */
1892
static int dolist(cmd_rec *cmd, const char *opt, const char *resp_code,
1893
0
    int clear_flags) {
1894
0
  int skiparg = 0;
1895
0
  int glob_flags = 0;
1896
1897
0
  char *arg = (char*) opt;
1898
1899
0
  ls_curtime = time(NULL);
1900
1901
0
  if (clear_flags) {
1902
0
    opt_1 = opt_A = opt_a = opt_B = opt_C = opt_d = opt_F = opt_h = opt_n =
1903
0
      opt_r = opt_R = opt_S = opt_t = opt_STAT = opt_L = 0;
1904
0
  }
1905
1906
0
  if (have_options(cmd, arg)) {
1907
0
    if (!list_strict_opts) {
1908
0
      parse_list_opts(&arg, &glob_flags, FALSE);
1909
1910
0
    } else {
1911
0
      char *ptr;
1912
1913
      /* Even if the user-given options are ignored, they still need to
1914
       * "processed" (i.e. skip past options) in order to get to the paths.
1915
       *
1916
       * First, scan for options.  Any leading whitespace before options can
1917
       * be skipped, as long as there ARE options.
1918
       */
1919
0
      ptr = arg;
1920
1921
0
      while (PR_ISSPACE(*ptr)) {
1922
0
        pr_signals_handle();
1923
0
        ptr++;
1924
0
      }
1925
1926
0
      if (*ptr == '-') {
1927
        /* Options are found; skip past the leading whitespace. */
1928
0
        arg = ptr;
1929
0
      }
1930
1931
0
      while (arg && *arg == '-') {
1932
        /* Advance to the next whitespace */
1933
0
        while (*arg != '\0' && !PR_ISSPACE(*arg)) {
1934
0
          arg++;
1935
0
        }
1936
1937
0
        ptr = arg;
1938
1939
0
        while (*ptr &&
1940
0
               PR_ISSPACE(*ptr)) {
1941
0
          pr_signals_handle();
1942
0
          ptr++;
1943
0
        }
1944
1945
0
        if (*ptr == '-') {
1946
          /* Options are found; skip past the leading whitespace. */
1947
0
          arg = ptr;
1948
1949
0
        } else if (*(arg + 1) == ' ') {
1950
          /* If the next character is a blank space, advance just one
1951
           * character.
1952
           */
1953
0
          arg++;
1954
0
          break;
1955
1956
0
        } else {
1957
0
          arg = ptr;
1958
0
          break;
1959
0
        }
1960
0
      }
1961
0
    }
1962
0
  }
1963
1964
0
  if (list_options) {
1965
0
    parse_list_opts(&list_options, &glob_flags, TRUE);
1966
0
  }
1967
1968
0
  if (arg && *arg) {
1969
0
    int justone = 1;
1970
0
    glob_t g;
1971
0
    int globbed = FALSE;
1972
0
    int a;
1973
0
    char pbuffer[PR_TUNABLE_PATH_MAX + 1] = "";
1974
0
    char *target;
1975
1976
    /* Make sure the glob_t is initialized. */
1977
0
    memset(&g, '\0', sizeof(g));
1978
1979
0
    if (*arg == '~') {
1980
0
      struct passwd *pw;
1981
0
      int i;
1982
0
      const char *p;
1983
1984
0
      for (i = 0, p = arg + 1;
1985
0
          ((size_t) i < sizeof(pbuffer) - 1) && p && *p && *p != '/';
1986
0
          pbuffer[i++] = *p++) {
1987
0
      }
1988
1989
0
      pbuffer[i] = '\0';
1990
1991
0
      pw = pr_auth_getpwnam(cmd->tmp_pool, i ? pbuffer : session.user);
1992
0
      if (pw) {
1993
0
        pr_snprintf(pbuffer, sizeof(pbuffer), "%s%s", pw->pw_dir, p);
1994
1995
0
      } else {
1996
0
        pbuffer[0] = '\0';
1997
0
      }
1998
0
    }
1999
2000
0
    target = *pbuffer ? pbuffer : arg;
2001
2002
    /* Open data connection */
2003
0
    if (!opt_STAT) {
2004
0
      if (pr_data_open(NULL, "file list", PR_NETIO_IO_WR, 0) < 0) {
2005
0
        int xerrno = errno;
2006
2007
0
        pr_cmd_set_errno(cmd, xerrno);
2008
0
        errno = xerrno;
2009
0
        return -1;
2010
0
      }
2011
2012
0
      session.sf_flags |= SF_ASCII_OVERRIDE;
2013
0
    }
2014
2015
    /* If there are no globbing characters in the given target,
2016
     * we can check to see if it even exists.
2017
     */
2018
0
    if (pr_str_is_fnmatch(target) == FALSE) {
2019
0
      struct stat st;
2020
2021
0
      pr_fs_clear_cache2(target);
2022
0
      if (pr_fsio_stat(target, &st) < 0) {
2023
0
        int xerrno = errno;
2024
2025
0
        if (xerrno == ENOENT &&
2026
0
            (list_flags & LS_FL_NO_ERROR_IF_ABSENT)) {
2027
0
          return 0;
2028
0
        }
2029
0
        pr_log_debug(DEBUG8,
2030
0
          "error checking %s: %s", target, strerror(xerrno));
2031
0
        pr_response_add_err(R_450, "%s: %s",
2032
0
          pr_fs_encode_path(cmd->tmp_pool, target), strerror(xerrno));
2033
2034
0
        errno = xerrno;
2035
0
        return -1;
2036
0
      }
2037
0
    }
2038
2039
    /* Check perms on the directory/file we are about to scan. */
2040
0
    if (!ls_perms_full(cmd->tmp_pool, cmd, target, NULL)) {
2041
0
      a = -1;
2042
0
      skiparg = TRUE;
2043
2044
0
    } else {
2045
0
      skiparg = FALSE;
2046
2047
0
      if (use_globbing == TRUE &&
2048
0
          pr_str_is_fnmatch(target)) {
2049
0
        a = pr_fs_glob(target, glob_flags, NULL, &g);
2050
0
        if (a == 0) {
2051
0
          pr_log_debug(DEBUG8, "LIST: glob(3) returned %lu %s",
2052
0
            (unsigned long) g.gl_pathc, g.gl_pathc != 1 ? "paths" : "path");
2053
0
          globbed = TRUE;
2054
2055
0
        } else {
2056
0
          if (a == GLOB_NOMATCH) {
2057
0
            pr_log_debug(DEBUG10, "LIST: glob(3) returned GLOB_NOMATCH "
2058
0
              "for '%s', handling as literal path", target);
2059
2060
            /* Trick the following code into using the non-glob() processed
2061
             * path.
2062
             */
2063
0
            a = 0;
2064
0
            g.gl_pathv = (char **) pcalloc(cmd->tmp_pool, 2 * sizeof(char *));
2065
0
            g.gl_pathv[0] = (char *) pstrdup(cmd->tmp_pool, target);
2066
0
            g.gl_pathv[1] = NULL;
2067
0
          }
2068
0
        }
2069
2070
0
      } else {
2071
        /* Trick the following code into using the non-glob() processed path */
2072
0
        a = 0;
2073
0
        g.gl_pathv = (char **) pcalloc(cmd->tmp_pool, 2 * sizeof(char *));
2074
0
        g.gl_pathv[0] = (char *) pstrdup(cmd->tmp_pool, target);
2075
0
        g.gl_pathv[1] = NULL;
2076
0
      }
2077
0
    }
2078
2079
0
    if (!a) {
2080
0
      char **path;
2081
2082
0
      path = g.gl_pathv;
2083
2084
0
      if (path && path[0] && path[1]) {
2085
0
        justone = 0;
2086
0
      }
2087
2088
0
      while (path &&
2089
0
             *path) {
2090
0
        struct stat st;
2091
2092
0
        pr_signals_handle();
2093
2094
0
        pr_fs_clear_cache2(*path);
2095
0
        if (pr_fsio_lstat(*path, &st) == 0) {
2096
0
          mode_t target_mode, lmode;
2097
0
          target_mode = st.st_mode;
2098
2099
0
          if (S_ISLNK(st.st_mode) &&
2100
0
              (lmode = symlink_mode2(cmd->tmp_pool, (char *) *path)) != 0) {
2101
0
            if (opt_L || !list_show_symlinks) {
2102
0
              st.st_mode = lmode;
2103
0
            }
2104
2105
0
            if (lmode != 0) {
2106
0
              target_mode = lmode;
2107
0
            }
2108
0
          }
2109
2110
          /* If the -d option is used or the file is not a directory, OR
2111
           * if the -R option is NOT used AND the file IS a directory AND
2112
           * the file is NOT the target/given parameter, then list the file
2113
           * as is.
2114
           */
2115
0
          if (opt_d ||
2116
0
              !(S_ISDIR(target_mode)) ||
2117
0
              (!opt_R && S_ISDIR(target_mode) && strcmp(*path, target) != 0)) {
2118
2119
0
            if (listfile(cmd, cmd->tmp_pool, resp_code, *path) < 0) {
2120
0
              ls_terminate();
2121
0
              if (use_globbing == TRUE &&
2122
0
                  globbed == TRUE) {
2123
0
                pr_fs_globfree(&g);
2124
0
              }
2125
0
              return -1;
2126
0
            }
2127
2128
0
            **path = '\0';
2129
0
          }
2130
2131
0
        } else {
2132
0
          **path = '\0';
2133
0
        }
2134
2135
0
        path++;
2136
0
      }
2137
2138
0
      if (outputfiles(cmd) < 0) {
2139
0
        ls_terminate();
2140
0
        if (use_globbing == TRUE &&
2141
0
            globbed == TRUE) {
2142
0
          pr_fs_globfree(&g);
2143
0
        }
2144
0
        return -1;
2145
0
      }
2146
2147
      /* At this point, the only paths left in g.gl_pathv should be
2148
       * directories; anything else should have been listed/handled
2149
       * above.
2150
       */
2151
2152
0
      path = g.gl_pathv;
2153
0
      while (path &&
2154
0
             *path) {
2155
0
        pr_signals_handle();
2156
2157
0
        if (**path &&
2158
0
            ls_perms_full(cmd->tmp_pool, cmd, *path, NULL)) {
2159
0
          char cwd_buf[PR_TUNABLE_PATH_MAX + 1] = {'\0'};
2160
0
          unsigned char symhold;
2161
2162
0
          if (!justone) {
2163
0
            if (opt_STAT) {
2164
0
              pr_response_add(resp_code, "%s", "");
2165
0
              pr_response_add(resp_code, "%s:",
2166
0
                pr_fs_encode_path(cmd->tmp_pool, *path));
2167
2168
0
            } else {
2169
0
              sendline(0, "\r\n%s:\r\n",
2170
0
                pr_fs_encode_path(cmd->tmp_pool, *path));
2171
0
              sendline(LS_SENDLINE_FL_FLUSH, " ");
2172
0
            }
2173
0
          }
2174
2175
          /* Recurse into the directory. */
2176
0
          push_cwd(cwd_buf, &symhold);
2177
2178
0
          if (pr_fsio_chdir_canon(*path, !opt_L && list_show_symlinks) == 0) {
2179
0
            int res = 0;
2180
2181
0
            list_ndepth.curr++;
2182
0
            res = listdir(cmd, cmd->tmp_pool, resp_code, *path);
2183
0
            list_ndepth.curr--;
2184
2185
0
            pop_cwd(cwd_buf, &symhold);
2186
2187
0
            if (res > 0) {
2188
0
              break;
2189
0
            }
2190
2191
0
            if (res < 0) {
2192
0
              ls_terminate();
2193
0
              if (use_globbing == TRUE &&
2194
0
                  globbed == TRUE) {
2195
0
                pr_fs_globfree(&g);
2196
0
              }
2197
0
              return -1;
2198
0
            }
2199
2200
0
          } else {
2201
0
            pop_cwd(cwd_buf, &symhold);
2202
0
          }
2203
0
        }
2204
2205
0
        if (XFER_ABORTED) {
2206
0
          discard_output();
2207
0
          if (use_globbing == TRUE &&
2208
0
              globbed == TRUE) {
2209
0
            pr_fs_globfree(&g);
2210
0
          }
2211
0
          return -1;
2212
0
        }
2213
2214
0
        path++;
2215
0
      }
2216
2217
0
      if (outputfiles(cmd) < 0) {
2218
0
        ls_terminate();
2219
0
        if (use_globbing == TRUE &&
2220
0
            globbed == TRUE) {
2221
0
          pr_fs_globfree(&g);
2222
0
        }
2223
0
        return -1;
2224
0
      }
2225
2226
0
    } else if (!skiparg) {
2227
0
      if (a == GLOB_NOSPACE) {
2228
0
        pr_response_add(R_226, _("Out of memory during globbing of %s"),
2229
0
          pr_fs_encode_path(cmd->tmp_pool, arg));
2230
2231
0
      } else if (a == GLOB_ABORTED) {
2232
0
        pr_response_add(R_226, _("Read error during globbing of %s"),
2233
0
          pr_fs_encode_path(cmd->tmp_pool, arg));
2234
2235
0
      } else if (a != GLOB_NOMATCH) {
2236
0
        pr_response_add(R_226, _("Unknown error during globbing of %s"),
2237
0
          pr_fs_encode_path(cmd->tmp_pool, arg));
2238
0
      }
2239
0
    }
2240
2241
0
    if (!skiparg &&
2242
0
        use_globbing == TRUE &&
2243
0
        globbed == TRUE) {
2244
0
      pr_fs_globfree(&g);
2245
0
    }
2246
2247
0
    if (XFER_ABORTED) {
2248
0
      discard_output();
2249
0
      return -1;
2250
0
    }
2251
2252
0
  } else {
2253
2254
    /* Open data connection */
2255
0
    if (!opt_STAT) {
2256
0
      if (pr_data_open(NULL, "file list", PR_NETIO_IO_WR, 0) < 0) {
2257
0
        int xerrno = errno;
2258
2259
0
        pr_cmd_set_errno(cmd, xerrno);
2260
0
        errno = xerrno;
2261
0
        return -1;
2262
0
      }
2263
2264
0
      session.sf_flags |= SF_ASCII_OVERRIDE;
2265
0
    }
2266
2267
0
    if (ls_perms_full(cmd->tmp_pool, cmd, ".", NULL)) {
2268
2269
0
      if (opt_d) {
2270
0
        if (listfile(cmd, NULL, resp_code, ".") < 0) {
2271
0
          ls_terminate();
2272
0
          return -1;
2273
0
        }
2274
2275
0
      } else {
2276
0
        list_ndepth.curr++;
2277
0
        if (listdir(cmd, NULL, resp_code, ".") < 0) {
2278
0
          ls_terminate();
2279
0
          return -1;
2280
0
        }
2281
2282
0
        list_ndepth.curr--;
2283
0
      }
2284
0
    }
2285
2286
0
    if (outputfiles(cmd) < 0) {
2287
0
      ls_terminate();
2288
0
      return -1;
2289
0
    }
2290
0
  }
2291
2292
0
  return 0;
2293
0
}
2294
2295
/* Display listing of a single file, no permission checking is done.
2296
 * An error is only returned if the data connection cannot be opened or is
2297
 * aborted.
2298
 */
2299
0
static int nlstfile(cmd_rec *cmd, const char *file) {
2300
0
  int res = 0;
2301
0
  char *display_name;
2302
2303
  /* If the data connection isn't open, return an error */
2304
0
  if ((session.sf_flags & SF_XFER) == 0) {
2305
0
    errno = EPERM;
2306
0
    return -1;
2307
0
  }
2308
2309
  /* XXX Note that "NLST <glob>" was sent, we might be receiving paths
2310
   * here, not just file names.  And that is not what dir_hide_file() is
2311
   * expecting.
2312
   */
2313
0
  if (dir_hide_file(file)) {
2314
0
    return 1;
2315
0
  }
2316
2317
0
  display_name = pstrdup(cmd->tmp_pool, file);
2318
2319
0
#ifndef PR_USE_NLS
2320
0
  if (opt_B) {
2321
0
    register unsigned int i, j;
2322
0
    size_t display_namelen, printable_namelen;
2323
0
    char *printable_name = NULL;
2324
2325
0
    display_namelen = strlen(display_name);
2326
2327
    /* Allocate 4 times as much space as necessary, in case every single
2328
     * character is non-printable.
2329
     */
2330
0
    printable_namelen = (display_namelen * 4);
2331
0
    printable_name = pcalloc(cmd->tmp_pool, printable_namelen + 1);
2332
2333
    /* Check for any non-printable characters, and replace them with the octal
2334
     * escape sequence equivalent.
2335
     */
2336
0
    for (i = 0, j = 0; i < display_namelen && j < printable_namelen; i++) {
2337
0
      if (!PR_ISPRINT(display_name[i])) {
2338
0
        register int k;
2339
0
        int replace_len = 0;
2340
0
        char replace[32];
2341
2342
0
        memset(replace, '\0', sizeof(replace));
2343
0
        replace_len = pr_snprintf(replace, sizeof(replace)-1, "\\%03o",
2344
0
          display_name[i]);
2345
2346
0
        for (k = 0; k < replace_len; k++) {
2347
0
          printable_name[j++] = replace[k];
2348
0
        }
2349
2350
0
      } else {
2351
0
        printable_name[j++] = display_name[i];
2352
0
      }
2353
0
    }
2354
2355
0
    display_name = pstrdup(cmd->tmp_pool, printable_name);
2356
0
  }
2357
0
#endif /* PR_USE_NLS */
2358
2359
0
  if (opt_1) {
2360
0
    char *ptr;
2361
2362
    /* If the -1 option is configured, we want to make sure that we only
2363
     * display a file, not a path.  And it's possible that we given a path
2364
     * here.
2365
     */
2366
0
    ptr = strrchr(display_name, '/');
2367
0
    if (ptr != NULL) {
2368
0
      size_t display_namelen;
2369
2370
0
      display_namelen = strlen(display_name);
2371
0
      if (display_namelen > 1) {
2372
        /* Make sure that we handle a possible display_name of '/' properly. */
2373
0
        display_name = ptr + 1;
2374
0
      }
2375
0
    }
2376
0
  }
2377
2378
  /* Be sure to flush the output */
2379
0
  res = sendline(0, "%s\r\n", pr_fs_encode_path(cmd->tmp_pool, display_name));
2380
0
  if (res < 0) {
2381
0
    return res;
2382
0
  }
2383
2384
0
  return 1;
2385
0
}
2386
2387
/* Display listing of a directory, ACL checks performed on each entry,
2388
 * sent in NLST fashion.  Files which are inaccessible via ACL are skipped,
2389
 * error returned if data conn cannot be opened or is aborted.
2390
 */
2391
0
static int nlstdir(cmd_rec *cmd, const char *dir) {
2392
0
  char **list, *p, *f,
2393
0
       file[PR_TUNABLE_PATH_MAX + 1] = {'\0'};
2394
0
  char cwd_buf[PR_TUNABLE_PATH_MAX + 1] = {'\0'};
2395
0
  pool *workp;
2396
0
  unsigned char symhold;
2397
0
  int curdir = FALSE, i, j, count = 0, hidden = 0, use_sorting = FALSE;
2398
0
  mode_t mode;
2399
0
  config_rec *c = NULL;
2400
0
  unsigned char ignore_hidden = FALSE;
2401
2402
0
  if (list_ndepth.curr && list_ndepth.max &&
2403
0
      list_ndepth.curr >= list_ndepth.max) {
2404
2405
0
    if (!list_ndepth.logged) {
2406
      /* Don't forget to take away the one we add to maxdepth internally. */
2407
0
      pr_log_debug(DEBUG8, "ListOptions maxdepth (%u) reached",
2408
0
        list_ndepth.max - 1);
2409
0
      list_ndepth.logged = TRUE;
2410
0
    }
2411
2412
0
    return 0;
2413
0
  }
2414
2415
0
  if (list_ndirs.curr && list_ndirs.max &&
2416
0
      list_ndirs.curr >= list_ndirs.max) {
2417
2418
0
    if (!list_ndirs.logged) {
2419
0
      pr_log_debug(DEBUG8, "ListOptions maxdirs (%u) reached", list_ndirs.max);
2420
0
      list_ndirs.logged = TRUE;
2421
0
    }
2422
2423
0
    return 0;
2424
0
  }
2425
0
  list_ndirs.curr++;
2426
2427
0
  workp = make_sub_pool(cmd->tmp_pool);
2428
0
  pr_pool_tag(workp, "mod_ls: nlstdir(): workp (from cmd->tmp_pool)");
2429
2430
0
  if (!*dir || (*dir == '.' && !dir[1]) || strcmp(dir, "./") == 0) {
2431
0
    curdir = TRUE;
2432
0
    dir = "";
2433
2434
0
  } else {
2435
2436
    /* If dir is not '.', then we need to change directories.  Hence we
2437
     * push our current working directory onto the stack, do the chdir,
2438
     * and pop back, afterwards.
2439
     */
2440
0
    push_cwd(cwd_buf, &symhold);
2441
2442
0
    if (pr_fsio_chdir_canon(dir, !opt_L && list_show_symlinks) < 0) {
2443
0
      pop_cwd(cwd_buf, &symhold);
2444
2445
0
      destroy_pool(workp);
2446
0
      return 0;
2447
0
    }
2448
0
  }
2449
2450
0
  if (list_flags & LS_FL_SORTED_NLST) {
2451
0
    use_sorting = TRUE;
2452
0
  }
2453
2454
0
  PR_DEVEL_CLOCK(list = sreaddir(".", use_sorting));
2455
0
  if (list == NULL) {
2456
0
    pr_trace_msg("fsio", 9,
2457
0
      "sreaddir() error on '.': %s", strerror(errno));
2458
2459
0
    if (!curdir) {
2460
0
      pop_cwd(cwd_buf, &symhold);
2461
0
    }
2462
2463
0
    destroy_pool(workp);
2464
0
    return 0;
2465
0
  }
2466
2467
  /* Search for relevant <Limit>'s to this NLST command.  If found,
2468
   * check to see whether hidden files should be ignored.
2469
   */
2470
0
  c = find_ls_limit(cmd->argv[0]);
2471
0
  if (c != NULL) {
2472
0
    unsigned char *ignore = get_param_ptr(c->subset, "IgnoreHidden", FALSE);
2473
2474
0
    if (ignore &&
2475
0
        *ignore == TRUE) {
2476
0
      ignore_hidden = TRUE;
2477
0
    }
2478
0
  }
2479
2480
0
  j = 0;
2481
0
  while (list[j] && count >= 0) {
2482
0
    p = list[j++];
2483
2484
0
    pr_signals_handle();
2485
2486
0
    if (*p == '.') {
2487
0
      if (!opt_a && (!opt_A || is_dotdir(p))) {
2488
0
        continue;
2489
0
      }
2490
2491
      /* Make sure IgnoreHidden is properly honored. */
2492
0
      if (ignore_hidden) {
2493
0
        continue;
2494
0
      }
2495
0
    }
2496
2497
0
    if (list_flags & LS_FL_ADJUSTED_SYMLINKS) {
2498
0
      i = dir_readlink(cmd->tmp_pool, p, file, sizeof(file) - 1,
2499
0
        PR_DIR_READLINK_FL_HANDLE_REL_PATH);
2500
2501
0
    } else {
2502
0
      i = pr_fsio_readlink(p, file, sizeof(file) - 1);
2503
0
    }
2504
2505
0
    if (i > 0) {
2506
0
      if ((size_t) i >= sizeof(file)) {
2507
0
        continue;
2508
0
      }
2509
2510
0
      file[i] = '\0';
2511
0
      f = file;
2512
2513
0
    } else {
2514
0
      f = p;
2515
0
    }
2516
2517
0
    if (ls_perms(workp, cmd, dir_best_path(cmd->tmp_pool, f), &hidden)) {
2518
0
      if (hidden) {
2519
0
        continue;
2520
0
      }
2521
2522
0
      mode = file_mode2(cmd->tmp_pool, f);
2523
0
      if (mode == 0) {
2524
0
        continue;
2525
0
      }
2526
2527
0
      if (!curdir) {
2528
0
        char *str = NULL;
2529
2530
0
        if (opt_1) {
2531
          /* Send just the file name, not the path. */
2532
0
          str = pr_fs_encode_path(cmd->tmp_pool, p);
2533
2534
0
        } else {
2535
0
          str = pr_fs_encode_path(cmd->tmp_pool,
2536
0
            pdircat(cmd->tmp_pool, dir, p, NULL));
2537
0
        }
2538
2539
0
        if (sendline(0, "%s\r\n", str) < 0) {
2540
0
          count = -1;
2541
2542
0
        } else {
2543
0
          count++;
2544
2545
0
          if (list_nfiles.curr > 0 &&
2546
0
              list_nfiles.max > 0 &&
2547
0
              list_nfiles.curr >= list_nfiles.max) {
2548
2549
0
            if (!list_nfiles.logged) {
2550
0
              pr_log_debug(DEBUG8, "ListOptions maxfiles (%u) reached",
2551
0
                list_nfiles.max);
2552
0
              list_nfiles.logged = TRUE;
2553
0
            }
2554
2555
0
            break;
2556
0
          }
2557
0
          list_nfiles.curr++;
2558
0
        }
2559
2560
0
      } else {
2561
0
        if (sendline(0, "%s\r\n", pr_fs_encode_path(cmd->tmp_pool, p)) < 0) {
2562
0
          count = -1;
2563
2564
0
        } else {
2565
0
          count++;
2566
2567
0
          if (list_nfiles.curr > 0 &&
2568
0
              list_nfiles.max > 0 &&
2569
0
              list_nfiles.curr >= list_nfiles.max) {
2570
2571
0
            if (!list_nfiles.logged) {
2572
0
              pr_log_debug(DEBUG8, "ListOptions maxfiles (%u) reached",
2573
0
                list_nfiles.max);
2574
0
              list_nfiles.logged = TRUE;
2575
0
            }
2576
2577
0
            break;
2578
0
          }
2579
0
          list_nfiles.curr++;
2580
0
        }
2581
0
      }
2582
0
    }
2583
0
  }
2584
2585
0
  sendline(LS_SENDLINE_FL_FLUSH, " ");
2586
2587
0
  if (!curdir) {
2588
0
    pop_cwd(cwd_buf, &symhold);
2589
0
  }
2590
0
  destroy_pool(workp);
2591
2592
  /* Explicitly free the memory allocated for containing the list of
2593
   * filenames.
2594
   */
2595
0
  i = 0;
2596
0
  while (list[i] != NULL) {
2597
0
    pr_signals_handle();
2598
0
    free(list[i++]);
2599
0
  }
2600
0
  free(list);
2601
2602
0
  return count;
2603
0
}
2604
2605
/* The LIST command.  */
2606
0
MODRET genericlist(cmd_rec *cmd) {
2607
0
  int res = 0;
2608
0
  char *decoded_path = NULL;
2609
0
  unsigned char *tmp = NULL;
2610
0
  mode_t *fake_mode = NULL;
2611
0
  config_rec *c = NULL;
2612
2613
0
  tmp = get_param_ptr(TOPLEVEL_CONF, "ShowSymlinks", FALSE);
2614
0
  if (tmp != NULL) {
2615
0
    list_show_symlinks = *tmp;
2616
0
  }
2617
2618
0
  list_strict_opts = FALSE;
2619
0
  list_nfiles.max = list_ndirs.max = list_ndepth.max = 0;
2620
2621
0
  c = find_config(CURRENT_CONF, CONF_PARAM, "ListOptions", FALSE);
2622
0
  while (c != NULL) {
2623
0
    unsigned long flags;
2624
2625
0
    pr_signals_handle();
2626
2627
0
    flags = *((unsigned long *) c->argv[5]);
2628
2629
    /* Make sure that this ListOptions can be applied to the LIST command.
2630
     * If not, keep looking for other applicable ListOptions.
2631
     */
2632
0
    if (flags & LS_FL_NLST_ONLY) {
2633
0
      pr_log_debug(DEBUG10, "%s: skipping NLSTOnly ListOptions",
2634
0
        (char *) cmd->argv[0]);
2635
0
      c = find_config_next(c, c->next, CONF_PARAM, "ListOptions", FALSE);
2636
0
      continue;
2637
0
    }
2638
2639
0
    list_options = c->argv[0];
2640
0
    list_strict_opts = *((unsigned char *) c->argv[1]);
2641
0
    list_ndepth.max = *((unsigned int *) c->argv[2]);
2642
2643
    /* We add one to the configured maxdepth in order to allow it to
2644
     * function properly: if one configures a maxdepth of 2, one should
2645
     * allowed to list the current directory, and all subdirectories one
2646
     * layer deeper.  For the checks to work, the maxdepth of 2 needs to
2647
     * handled internally as a maxdepth of 3.
2648
     */
2649
0
    if (list_ndepth.max) {
2650
0
      list_ndepth.max += 1;
2651
0
    }
2652
2653
0
    list_nfiles.max = *((unsigned int *) c->argv[3]);
2654
0
    list_ndirs.max = *((unsigned int *) c->argv[4]);
2655
0
    list_flags = *((unsigned long *) c->argv[5]);
2656
2657
0
    break;
2658
0
  }
2659
2660
0
  fakeuser = get_param_ptr(CURRENT_CONF, "DirFakeUser", FALSE);
2661
2662
  /* Check for a configured "logged in user" DirFakeUser. */
2663
0
  if (fakeuser != NULL &&
2664
0
      strcmp(fakeuser, "~") == 0) {
2665
0
    fakeuser = session.user;
2666
0
  }
2667
2668
0
  fakegroup = get_param_ptr(CURRENT_CONF, "DirFakeGroup", FALSE);
2669
2670
  /* Check for a configured "logged in user" DirFakeGroup. */
2671
0
  if (fakegroup != NULL &&
2672
0
      strcmp(fakegroup, "~") == 0) {
2673
0
    fakegroup = session.group;
2674
0
  }
2675
2676
0
  fake_mode = get_param_ptr(CURRENT_CONF, "DirFakeMode", FALSE);
2677
0
  if (fake_mode) {
2678
0
    fakemode = *fake_mode;
2679
0
    have_fake_mode = TRUE;
2680
2681
0
  } else {
2682
0
    have_fake_mode = FALSE;
2683
0
  }
2684
2685
0
  tmp = get_param_ptr(TOPLEVEL_CONF, "TimesGMT", FALSE);
2686
0
  if (tmp != NULL) {
2687
0
    list_times_gmt = *tmp;
2688
0
  }
2689
2690
0
  decoded_path = pr_fs_decode_path2(cmd->tmp_pool, cmd->arg,
2691
0
    FSIO_DECODE_FL_TELL_ERRORS);
2692
0
  if (decoded_path == NULL) {
2693
0
    int xerrno = errno;
2694
2695
0
    pr_log_debug(DEBUG8, "'%s' failed to decode properly: %s", cmd->arg,
2696
0
      strerror(xerrno));
2697
0
    pr_response_add_err(R_550, _("%s: Illegal character sequence in filename"),
2698
0
      cmd->arg);
2699
2700
0
    pr_cmd_set_errno(cmd, xerrno);
2701
0
    errno = xerrno;
2702
0
    return PR_ERROR(cmd);
2703
0
  }
2704
2705
0
  res = dolist(cmd, decoded_path, R_211, TRUE);
2706
2707
0
  if (XFER_ABORTED) {
2708
0
    pr_data_abort(0, 0);
2709
0
    res = -1;
2710
2711
0
  } else if (session.sf_flags & SF_XFER) {
2712
0
    ls_done(cmd);
2713
0
  }
2714
2715
0
  opt_l = 0;
2716
2717
0
  return (res == -1 ? PR_ERROR(cmd) : PR_HANDLED(cmd));
2718
0
}
2719
2720
0
MODRET ls_log_nlst(cmd_rec *cmd) {
2721
0
  pr_data_cleanup();
2722
0
  return PR_DECLINED(cmd);
2723
0
}
2724
2725
0
MODRET ls_err_nlst(cmd_rec *cmd) {
2726
0
  pr_data_cleanup();
2727
0
  return PR_DECLINED(cmd);
2728
0
}
2729
2730
0
MODRET ls_stat(cmd_rec *cmd) {
2731
0
  struct stat st;
2732
0
  int res;
2733
0
  char *arg = cmd->arg, *decoded_path, *path, *resp_code = NULL;
2734
0
  unsigned char *ptr = NULL;
2735
0
  mode_t *fake_mode = NULL;
2736
0
  config_rec *c = NULL;
2737
2738
0
  if (cmd->argc == 1) {
2739
    /* In this case, the client is requesting the current session status. */
2740
2741
0
    if (!dir_check(cmd->tmp_pool, cmd, cmd->group, session.cwd, NULL)) {
2742
0
      int xerrno = EPERM;
2743
2744
0
      pr_response_add_err(R_500, "%s: %s", (char *) cmd->argv[0],
2745
0
        strerror(xerrno));
2746
2747
0
      pr_cmd_set_errno(cmd, xerrno);
2748
0
      errno = xerrno;
2749
0
      return PR_ERROR(cmd);
2750
0
    }
2751
2752
0
    pr_response_add(R_211, _("Status of '%s'"), main_server->ServerName);
2753
0
    pr_response_add(R_DUP, _("Connected from %s (%s)"), session.c->remote_name,
2754
0
      pr_netaddr_get_ipstr(session.c->remote_addr));
2755
0
    pr_response_add(R_DUP, _("Logged in as %s"), session.user);
2756
0
    pr_response_add(R_DUP, _("TYPE: %s, STRUcture: File, Mode: Stream"),
2757
0
      (session.sf_flags & SF_ASCII) ? "ASCII" : "BINARY");
2758
2759
0
    if (session.total_bytes) {
2760
0
      pr_response_add(R_DUP, _("Total bytes transferred for session: %" PR_LU),
2761
0
        (pr_off_t) session.total_bytes);
2762
0
    }
2763
2764
0
    if (session.sf_flags & SF_XFER) {
2765
      /* Report on the data transfer attributes. */
2766
2767
0
      pr_response_add(R_DUP, _("%s from %s port %u"),
2768
0
        (session.sf_flags & SF_PASSIVE) ?
2769
0
          _("Passive data transfer from") : _("Active data transfer to"),
2770
0
        pr_netaddr_get_ipstr(session.d->remote_addr), session.d->remote_port);
2771
2772
0
      if (session.xfer.file_size) {
2773
0
        pr_response_add(R_DUP, "%s %s (%" PR_LU "/%" PR_LU ")",
2774
0
          session.xfer.direction == PR_NETIO_IO_RD ? C_STOR : C_RETR,
2775
0
          session.xfer.path, (pr_off_t) session.xfer.file_size,
2776
0
          (pr_off_t) session.xfer.total_bytes);
2777
2778
0
      } else {
2779
0
        pr_response_add(R_DUP, "%s %s (%" PR_LU ")",
2780
0
          session.xfer.direction == PR_NETIO_IO_RD ? C_STOR : C_RETR,
2781
0
          session.xfer.path, (pr_off_t) session.xfer.total_bytes);
2782
0
      }
2783
2784
0
    } else {
2785
0
      pr_response_add(R_DUP, _("No data connection"));
2786
0
    }
2787
2788
0
    pr_response_add(R_DUP, _("End of status"));
2789
0
    return PR_HANDLED(cmd);
2790
0
  }
2791
2792
0
  list_nfiles.curr = list_ndirs.curr = list_ndepth.curr = 0;
2793
0
  list_nfiles.logged = list_ndirs.logged = list_ndepth.logged = FALSE;
2794
2795
0
  decoded_path = pr_fs_decode_path2(cmd->tmp_pool, arg,
2796
0
    FSIO_DECODE_FL_TELL_ERRORS);
2797
0
  if (decoded_path == NULL) {
2798
0
    int xerrno = errno;
2799
2800
0
    pr_log_debug(DEBUG8, "'%s' failed to decode properly: %s", arg,
2801
0
      strerror(xerrno));
2802
0
    pr_response_add_err(R_550, _("%s: Illegal character sequence in filename"),
2803
0
      arg);
2804
2805
0
    pr_cmd_set_errno(cmd, xerrno);
2806
0
    errno = xerrno;
2807
0
    return PR_ERROR(cmd);
2808
0
  }
2809
2810
0
  arg = decoded_path;
2811
2812
  /* Get to the actual argument. */
2813
0
  if (*arg == '-') {
2814
0
    while (arg && *arg && !PR_ISSPACE(*arg)) {
2815
0
      arg++;
2816
0
    }
2817
0
  }
2818
2819
0
  while (arg && *arg && PR_ISSPACE(*arg)) {
2820
0
    arg++;
2821
0
  }
2822
2823
0
  ptr = get_param_ptr(TOPLEVEL_CONF, "ShowSymlinks", FALSE);
2824
0
  if (ptr != NULL) {
2825
0
    list_show_symlinks = *ptr;
2826
0
  }
2827
2828
0
  list_strict_opts = FALSE;
2829
0
  list_ndepth.max = list_nfiles.max = list_ndirs.max = 0;
2830
2831
0
  c = find_config(CURRENT_CONF, CONF_PARAM, "ListOptions", FALSE);
2832
0
  while (c != NULL) {
2833
0
    unsigned long flags;
2834
2835
0
    pr_signals_handle();
2836
2837
0
    flags = *((unsigned long *) c->argv[5]);
2838
2839
    /* Make sure that this ListOptions can be applied to the STAT command.
2840
     * If not, keep looking for other applicable ListOptions.
2841
     */
2842
0
    if (flags & LS_FL_LIST_ONLY) {
2843
0
      pr_log_debug(DEBUG10, "%s: skipping LISTOnly ListOptions",
2844
0
        (char *) cmd->argv[0]);
2845
0
      c = find_config_next(c, c->next, CONF_PARAM, "ListOptions", FALSE);
2846
0
      continue;
2847
0
    }
2848
2849
0
    if (flags & LS_FL_NLST_ONLY) {
2850
0
      pr_log_debug(DEBUG10, "%s: skipping NLSTOnly ListOptions",
2851
0
        (char *) cmd->argv[0]);
2852
0
      c = find_config_next(c, c->next, CONF_PARAM, "ListOptions", FALSE);
2853
0
      continue;
2854
0
    }
2855
2856
0
    list_options = c->argv[0];
2857
0
    list_strict_opts = *((unsigned char *) c->argv[1]);
2858
2859
0
    list_ndepth.max = *((unsigned int *) c->argv[2]);
2860
2861
    /* We add one to the configured maxdepth in order to allow it to
2862
     * function properly: if one configures a maxdepth of 2, one should
2863
     * allowed to list the current directory, and all subdirectories one
2864
     * layer deeper.  For the checks to work, the maxdepth of 2 needs to
2865
     * handled internally as a maxdepth of 3.
2866
     */
2867
0
    if (list_ndepth.max) {
2868
0
      list_ndepth.max += 1;
2869
0
    }
2870
2871
0
    list_nfiles.max = *((unsigned int *) c->argv[3]);
2872
0
    list_ndirs.max = *((unsigned int *) c->argv[4]);
2873
0
    list_flags = *((unsigned long *) c->argv[5]);
2874
2875
0
    break;
2876
0
  }
2877
2878
0
  fakeuser = get_param_ptr(CURRENT_CONF, "DirFakeUser", FALSE);
2879
2880
  /* Check for a configured "logged in user" DirFakeUser. */
2881
0
  if (fakeuser != NULL &&
2882
0
      strcmp(fakeuser, "~") == 0) {
2883
0
    fakeuser = session.user;
2884
0
  }
2885
2886
0
  fakegroup = get_param_ptr(CURRENT_CONF, "DirFakeGroup", FALSE);
2887
2888
  /* Check for a configured "logged in user" DirFakeGroup. */
2889
0
  if (fakegroup != NULL &&
2890
0
      strcmp(fakegroup, "~") == 0) {
2891
0
    fakegroup = session.group;
2892
0
  }
2893
2894
0
  fake_mode = get_param_ptr(CURRENT_CONF, "DirFakeMode", FALSE);
2895
0
  if (fake_mode) {
2896
0
    fakemode = *fake_mode;
2897
0
    have_fake_mode = TRUE;
2898
2899
0
  } else {
2900
0
    have_fake_mode = FALSE;
2901
0
  }
2902
2903
0
  ptr = get_param_ptr(TOPLEVEL_CONF, "TimesGMT", FALSE);
2904
0
  if (ptr != NULL) {
2905
0
    list_times_gmt = *ptr;
2906
0
  }
2907
2908
0
  opt_C = opt_d = opt_F = opt_R = 0;
2909
0
  opt_a = opt_l = opt_STAT = 1;
2910
2911
0
  path = (arg && *arg) ? arg : ".";
2912
2913
0
  pr_fs_clear_cache2(path);
2914
0
  if (list_show_symlinks) {
2915
0
    res = pr_fsio_lstat(path, &st);
2916
2917
0
  } else {
2918
0
    res = pr_fsio_stat(path, &st);
2919
0
  }
2920
2921
0
  if (res < 0) {
2922
0
    int xerrno = errno;
2923
2924
0
    pr_log_debug(DEBUG8,
2925
0
          "error checking %s: %s", path, strerror(xerrno));
2926
0
    pr_response_add_err(R_450, "%s: %s", path, strerror(xerrno));
2927
2928
0
    pr_cmd_set_errno(cmd, xerrno);
2929
0
    errno = xerrno;
2930
0
    return PR_ERROR(cmd);
2931
0
  }
2932
2933
0
  if (S_ISDIR(st.st_mode)) {
2934
0
    resp_code = R_212;
2935
2936
0
  } else {
2937
0
    resp_code = R_213;
2938
0
  }
2939
2940
0
  pr_response_add(resp_code, _("Status of %s:"),
2941
0
    pr_fs_encode_path(cmd->tmp_pool, path));
2942
0
  res = dolist(cmd, path, resp_code, FALSE);
2943
0
  pr_response_add(resp_code, _("End of status"));
2944
0
  return (res == -1 ? PR_ERROR(cmd) : PR_HANDLED(cmd));
2945
0
}
2946
2947
0
MODRET ls_list(cmd_rec *cmd) {
2948
0
  list_nfiles.curr = list_ndirs.curr = list_ndepth.curr = 0;
2949
0
  list_nfiles.logged = list_ndirs.logged = list_ndepth.logged = FALSE;
2950
2951
0
  opt_l = 1;
2952
2953
0
  return genericlist(cmd);
2954
0
}
2955
2956
/* NLST is a very simplistic directory listing, unlike LIST (which emulates
2957
 * ls(1)), it only sends a list of all files/directories matching the glob(s).
2958
 */
2959
0
MODRET ls_nlst(cmd_rec *cmd) {
2960
0
  char *decoded_path, *target, buf[PR_TUNABLE_PATH_MAX + 1] = {'\0'};
2961
0
  size_t targetlen = 0;
2962
0
  config_rec *c = NULL;
2963
0
  int res = 0, hidden = 0;
2964
0
  int glob_flags = GLOB_NOSORT;
2965
0
  unsigned char *tmp = NULL;
2966
2967
0
  list_nfiles.curr = list_ndirs.curr = list_ndepth.curr = 0;
2968
0
  list_nfiles.logged = list_ndirs.logged = list_ndepth.logged = FALSE;
2969
2970
0
  tmp = get_param_ptr(TOPLEVEL_CONF, "ShowSymlinks", FALSE);
2971
0
  if (tmp != NULL) {
2972
0
    list_show_symlinks = *tmp;
2973
0
  }
2974
2975
0
  decoded_path = pr_fs_decode_path2(cmd->tmp_pool, cmd->arg,
2976
0
    FSIO_DECODE_FL_TELL_ERRORS);
2977
0
  if (decoded_path == NULL) {
2978
0
    int xerrno = errno;
2979
2980
0
    pr_log_debug(DEBUG8, "'%s' failed to decode properly: %s", cmd->arg,
2981
0
      strerror(xerrno));
2982
0
    pr_response_add_err(R_550, _("%s: Illegal character sequence in filename"),
2983
0
      cmd->arg);
2984
2985
0
    pr_cmd_set_errno(cmd, xerrno);
2986
0
    errno = xerrno;
2987
0
    return PR_ERROR(cmd);
2988
0
  }
2989
2990
0
  target = cmd->argc == 1 ? "." : decoded_path;
2991
2992
0
  c = find_config(CURRENT_CONF, CONF_PARAM, "ListOptions", FALSE);
2993
0
  while (c != NULL) {
2994
0
    unsigned long flags;
2995
2996
0
    pr_signals_handle();
2997
2998
0
    flags = *((unsigned long *) c->argv[5]);
2999
3000
    /* Make sure that this ListOptions can be applied to the NLST command.
3001
     * If not, keep looking for other applicable ListOptions.
3002
     */
3003
0
    if (flags & LS_FL_LIST_ONLY) {
3004
0
      pr_log_debug(DEBUG10, "%s: skipping LISTOnly ListOptions",
3005
0
        (char *) cmd->argv[0]);
3006
0
      c = find_config_next(c, c->next, CONF_PARAM, "ListOptions", FALSE);
3007
0
      continue;
3008
0
    }
3009
3010
0
    list_options = c->argv[0];
3011
0
    list_strict_opts = *((unsigned char *) c->argv[1]);
3012
3013
0
    list_ndepth.max = *((unsigned int *) c->argv[2]);
3014
3015
    /* We add one to the configured maxdepth in order to allow it to
3016
     * function properly: if one configures a maxdepth of 2, one should
3017
     * allowed to list the current directory, and all subdirectories one
3018
     * layer deeper.  For the checks to work, the maxdepth of 2 needs to
3019
     * handled internally as a maxdepth of 3.
3020
     */
3021
0
    if (list_ndepth.max) {
3022
0
      list_ndepth.max += 1;
3023
0
    }
3024
3025
0
    list_nfiles.max = *((unsigned int *) c->argv[3]);
3026
0
    list_ndirs.max = *((unsigned int *) c->argv[4]);
3027
0
    list_flags = *((unsigned long *) c->argv[5]);
3028
3029
0
    break;
3030
0
  }
3031
3032
  /* Clear the listing option flags. */
3033
0
  opt_1 = opt_A = opt_a = opt_B = opt_C = opt_d = opt_F = opt_n = opt_r =
3034
0
    opt_R = opt_S = opt_t = opt_STAT = opt_L = 0;
3035
3036
0
  if (have_options(cmd, target)) {
3037
0
    if (!list_strict_opts) {
3038
0
      parse_list_opts(&target, &glob_flags, FALSE);
3039
3040
0
    } else {
3041
0
      char *ptr;
3042
3043
      /* Even if the user-given options are ignored, they still need to
3044
       * "processed" (i.e. skip past options) in order to get to the paths.
3045
       *
3046
       * First, scan for options.  Any leading whitespace before options can
3047
       * be skipped, as long as there ARE options.
3048
       */
3049
0
      ptr = target;
3050
3051
0
      while (PR_ISSPACE(*ptr)) {
3052
0
        pr_signals_handle();
3053
0
        ptr++;
3054
0
      }
3055
3056
0
      if (*ptr == '-') {
3057
        /* Options are found; skip past the leading whitespace. */
3058
0
        target = ptr;
3059
0
      }
3060
3061
0
      while (target && *target == '-') {
3062
        /* Advance to the next whitespace */
3063
0
        while (*target != '\0' && !PR_ISSPACE(*target)) {
3064
0
          target++;
3065
0
        }
3066
3067
0
        ptr = target;
3068
3069
0
        while (*ptr &&
3070
0
               PR_ISSPACE(*ptr)) {
3071
0
          pr_signals_handle();
3072
0
          ptr++;
3073
0
        }
3074
3075
0
        if (*ptr == '-') {
3076
          /* Options are found; skip past the leading whitespace. */
3077
0
          target = ptr;
3078
3079
0
        } else if (*target && *(target + 1) == ' ') {
3080
          /* If the next character is a blank space, advance just one
3081
           * character.
3082
           */
3083
0
          target++;
3084
0
          break;
3085
3086
0
        } else {
3087
0
          target = ptr;
3088
0
          break;
3089
0
        }
3090
0
      }
3091
0
    }
3092
0
  }
3093
3094
0
  if (list_options) {
3095
0
    parse_list_opts(&list_options, &glob_flags, TRUE);
3096
0
  }
3097
3098
  /* If, after parsing out any options, the target string is empty, assume
3099
   * the current directory (Bug#4069).
3100
   */
3101
0
  if (*target == '\0') {
3102
0
    target = pstrdup(cmd->tmp_pool, ".");
3103
0
  }
3104
3105
  /* If the target starts with '~' ... */
3106
0
  if (*target == '~') {
3107
0
    char pb[PR_TUNABLE_PATH_MAX + 1] = {'\0'};
3108
0
    struct passwd *pw = NULL;
3109
0
    int i = 0;
3110
0
    const char *p = target;
3111
3112
0
    p++;
3113
3114
0
    while (*p && *p != '/' && i < PR_TUNABLE_PATH_MAX) {
3115
0
      pb[i++] = *p++;
3116
0
    }
3117
0
    pb[i] = '\0';
3118
3119
0
    pw = pr_auth_getpwnam(cmd->tmp_pool, i ? pb : session.user);
3120
0
    if (pw != NULL) {
3121
0
      pr_snprintf(pb, sizeof(pb), "%s%s", pw->pw_dir, p);
3122
0
      sstrncpy(buf, pb, sizeof(buf));
3123
0
      target = buf;
3124
0
    }
3125
0
  }
3126
3127
  /* If the target is a glob, get the listing of files/dirs to send. */
3128
0
  if (use_globbing == TRUE &&
3129
0
      pr_str_is_fnmatch(target)) {
3130
0
    glob_t g;
3131
0
    char **path, *p;
3132
0
    int globbed = FALSE;
3133
3134
    /* Make sure the glob_t is initialized */
3135
0
    memset(&g, '\0', sizeof(glob_t));
3136
3137
0
    res = pr_fs_glob(target, glob_flags, NULL, &g);
3138
0
    if (res == 0) {
3139
0
      pr_log_debug(DEBUG8, "NLST: glob(3) returned %lu %s",
3140
0
        (unsigned long) g.gl_pathc, g.gl_pathc != 1 ? "paths" : "path");
3141
0
      globbed = TRUE;
3142
3143
0
    } else {
3144
0
      if (res == GLOB_NOMATCH) {
3145
0
        struct stat st;
3146
3147
0
        pr_fs_clear_cache2(target);
3148
0
        if (pr_fsio_stat(target, &st) == 0) {
3149
0
          pr_log_debug(DEBUG10, "NLST: glob(3) returned GLOB_NOMATCH for '%s', "
3150
0
            "handling as literal path", target);
3151
3152
          /* Trick the following code into using the non-glob() processed path.
3153
           */
3154
0
          res = 0;
3155
0
          g.gl_pathv = (char **) pcalloc(cmd->tmp_pool, 2 * sizeof(char *));
3156
0
          g.gl_pathv[0] = (char *) pstrdup(cmd->tmp_pool, target);
3157
0
          g.gl_pathv[1] = NULL;
3158
3159
0
        } else {
3160
0
          if (list_flags & LS_FL_NO_ERROR_IF_ABSENT) {
3161
0
            if (pr_data_open(NULL, "file list", PR_NETIO_IO_WR, 0) < 0) {
3162
0
              int xerrno = errno;
3163
3164
0
              pr_cmd_set_errno(cmd, xerrno);
3165
0
              errno = xerrno;
3166
0
              return PR_ERROR(cmd);
3167
0
            }
3168
3169
0
            session.sf_flags |= SF_ASCII_OVERRIDE;
3170
0
            pr_response_add(R_226, _("Transfer complete"));
3171
0
            ls_done(cmd);
3172
3173
0
            return PR_HANDLED(cmd);
3174
0
          }
3175
3176
0
          pr_log_debug(DEBUG8,
3177
0
            "error checking %s: %s", target, strerror(errno));
3178
0
          pr_response_add_err(R_450, _("No files found"));
3179
3180
0
          pr_cmd_set_errno(cmd, ENOENT);
3181
0
          errno = ENOENT;
3182
0
          return PR_ERROR(cmd);
3183
0
        }
3184
3185
0
      } else {
3186
0
        if (list_flags & LS_FL_NO_ERROR_IF_ABSENT) {
3187
0
          if (pr_data_open(NULL, "file list", PR_NETIO_IO_WR, 0) < 0) {
3188
0
            int xerrno = errno;
3189
3190
0
            pr_cmd_set_errno(cmd, xerrno);
3191
0
            errno = xerrno;
3192
0
            return PR_ERROR(cmd);
3193
0
          }
3194
3195
0
          session.sf_flags |= SF_ASCII_OVERRIDE;
3196
0
          pr_response_add(R_226, _("Transfer complete"));
3197
0
          ls_done(cmd);
3198
3199
0
          return PR_HANDLED(cmd);
3200
0
        }
3201
3202
0
        pr_response_add_err(R_450, _("No files found"));
3203
3204
0
        pr_cmd_set_errno(cmd, ENOENT);
3205
0
        errno = ENOENT;
3206
0
        return PR_ERROR(cmd);
3207
0
      }
3208
0
    }
3209
3210
0
    if (pr_data_open(NULL, "file list", PR_NETIO_IO_WR, 0) < 0) {
3211
0
      int xerrno = errno;
3212
3213
0
      pr_cmd_set_errno(cmd, xerrno);
3214
0
      errno = xerrno;
3215
0
      return PR_ERROR(cmd);
3216
0
    }
3217
3218
0
    session.sf_flags |= SF_ASCII_OVERRIDE;
3219
3220
    /* Iterate through each matching entry */
3221
0
    path = g.gl_pathv;
3222
0
    while (path && *path && res >= 0) {
3223
0
      struct stat st;
3224
3225
0
      pr_signals_handle();
3226
3227
0
      p = *path;
3228
0
      path++;
3229
3230
0
      pr_fs_clear_cache2(p);
3231
0
      if (pr_fsio_stat(p, &st) == 0) {
3232
        /* If it's a directory... */
3233
0
        if (S_ISDIR(st.st_mode)) {
3234
0
          if (opt_R) {
3235
            /* ...and we are recursing, hand off to nlstdir()...*/
3236
0
            res = nlstdir(cmd, p);
3237
3238
0
          } else {
3239
            /*...otherwise, just list the name. */
3240
0
            res = nlstfile(cmd, p);
3241
0
          }
3242
3243
0
        } else if (S_ISREG(st.st_mode) &&
3244
0
            ls_perms(cmd->tmp_pool, cmd, p, &hidden)) {
3245
          /* Don't display hidden files */
3246
0
          if (hidden) {
3247
0
            continue;
3248
0
          }
3249
3250
0
          res = nlstfile(cmd, p);
3251
0
        }
3252
0
      }
3253
0
    }
3254
3255
0
    sendline(LS_SENDLINE_FL_FLUSH, " ");
3256
0
    if (globbed) {
3257
0
      pr_fs_globfree(&g);
3258
0
    }
3259
3260
0
  } else {
3261
    /* A single target. If it's a directory, list the contents; if it's a
3262
     * file, just list the file.
3263
     */
3264
0
    struct stat st;
3265
3266
    /* Remove any trailing separators. */
3267
0
    targetlen = strlen(target);
3268
0
    while (targetlen >= 1 &&
3269
0
           target[targetlen-1] == '/') {
3270
0
      pr_signals_handle();
3271
3272
0
      if (strcmp(target, "/") == 0) {
3273
0
        break;
3274
0
      }
3275
3276
0
      target[targetlen-1] = '\0';
3277
0
      targetlen = strlen(target);
3278
0
    }
3279
3280
0
    if (!is_dotdir(target)) {
3281
      /* Clean the path. */
3282
0
      if (*target != '/') {
3283
0
        pr_fs_clean_path2(target, buf, sizeof(buf), 0);
3284
3285
0
      } else {
3286
0
        pr_fs_clean_path(target, buf, sizeof(buf));
3287
0
      }
3288
3289
0
      target = buf;
3290
0
    }
3291
3292
0
    if (!ls_perms_full(cmd->tmp_pool, cmd, target, &hidden)) {
3293
0
      int xerrno = errno;
3294
3295
0
      if (xerrno == ENOENT &&
3296
0
          (list_flags & LS_FL_NO_ERROR_IF_ABSENT)) {
3297
0
        if (pr_data_open(NULL, "file list", PR_NETIO_IO_WR, 0) < 0) {
3298
0
          xerrno = errno;
3299
3300
0
          pr_cmd_set_errno(cmd, xerrno);
3301
0
          errno = xerrno;
3302
0
          return PR_ERROR(cmd);
3303
0
        }
3304
0
        session.sf_flags |= SF_ASCII_OVERRIDE;
3305
0
        pr_response_add(R_226, _("Transfer complete"));
3306
0
        ls_done(cmd);
3307
3308
0
        return PR_HANDLED(cmd);
3309
0
      }
3310
3311
0
      pr_response_add_err(R_450, "%s: %s", *cmd->arg ? cmd->arg :
3312
0
        pr_fs_encode_path(cmd->tmp_pool, session.vwd), strerror(xerrno));
3313
3314
0
      pr_cmd_set_errno(cmd, xerrno);
3315
0
      errno = xerrno;
3316
0
      return PR_ERROR(cmd);
3317
0
    }
3318
3319
    /* Don't display hidden files */
3320
0
    if (hidden) {
3321
0
      c = find_ls_limit(target);
3322
0
      if (c) {
3323
0
        unsigned char *ignore_hidden;
3324
0
        int xerrno;
3325
3326
0
        ignore_hidden = get_param_ptr(c->subset, "IgnoreHidden", FALSE);
3327
0
        if (ignore_hidden &&
3328
0
            *ignore_hidden == TRUE) {
3329
3330
0
          if (list_flags & LS_FL_NO_ERROR_IF_ABSENT) {
3331
0
            if (pr_data_open(NULL, "file list", PR_NETIO_IO_WR, 0) < 0) {
3332
0
              xerrno = errno;
3333
3334
0
              pr_cmd_set_errno(cmd, xerrno);
3335
0
              errno = xerrno;
3336
0
              return PR_ERROR(cmd);
3337
0
            }
3338
0
            session.sf_flags |= SF_ASCII_OVERRIDE;
3339
0
            pr_response_add(R_226, _("Transfer complete"));
3340
0
            ls_done(cmd);
3341
3342
0
            return PR_HANDLED(cmd);
3343
0
          }
3344
3345
0
          xerrno = ENOENT;
3346
3347
0
        } else {
3348
0
          xerrno = EACCES;
3349
0
        }
3350
3351
0
        pr_response_add_err(R_450, "%s: %s",
3352
0
          pr_fs_encode_path(cmd->tmp_pool, target), strerror(xerrno));
3353
3354
0
        pr_cmd_set_errno(cmd, xerrno);
3355
0
        errno = xerrno;
3356
0
        return PR_ERROR(cmd);
3357
0
      }
3358
0
    }
3359
3360
    /* Make sure the target is a file or directory, and that we have access
3361
     * to it.
3362
     */
3363
0
    pr_fs_clear_cache2(target);
3364
0
    if (pr_fsio_stat(target, &st) < 0) {
3365
0
      int xerrno = errno;
3366
3367
0
      if (xerrno == ENOENT &&
3368
0
          (list_flags & LS_FL_NO_ERROR_IF_ABSENT)) {
3369
0
        if (pr_data_open(NULL, "file list", PR_NETIO_IO_WR, 0) < 0) {
3370
0
          xerrno = errno;
3371
3372
0
          pr_cmd_set_errno(cmd, xerrno);
3373
0
          errno = xerrno;
3374
0
          return PR_ERROR(cmd);
3375
0
        }
3376
0
        session.sf_flags |= SF_ASCII_OVERRIDE;
3377
0
        pr_response_add(R_226, _("Transfer complete"));
3378
0
        ls_done(cmd);
3379
3380
0
        return PR_HANDLED(cmd);
3381
0
      }
3382
3383
0
      pr_log_debug(DEBUG8,
3384
0
          "error checking %s: %s", target, strerror(xerrno));
3385
0
      pr_response_add_err(R_450, "%s: %s", cmd->arg, strerror(xerrno));
3386
3387
0
      pr_cmd_set_errno(cmd, xerrno);
3388
0
      errno = xerrno;
3389
0
      return PR_ERROR(cmd);
3390
0
    }
3391
3392
0
    if (S_ISREG(st.st_mode)) {
3393
0
      if (pr_data_open(NULL, "file list", PR_NETIO_IO_WR, 0) < 0) {
3394
0
        int xerrno = errno;
3395
3396
0
        pr_cmd_set_errno(cmd, xerrno);
3397
0
        errno = xerrno;
3398
0
        return PR_ERROR(cmd);
3399
0
      }
3400
0
      session.sf_flags |= SF_ASCII_OVERRIDE;
3401
3402
0
      res = nlstfile(cmd, target);
3403
3404
0
    } else if (S_ISDIR(st.st_mode)) {
3405
0
      if (pr_data_open(NULL, "file list", PR_NETIO_IO_WR, 0) < 0) {
3406
0
        int xerrno = errno;
3407
3408
0
        pr_cmd_set_errno(cmd, xerrno);
3409
0
        errno = xerrno;
3410
0
        return PR_ERROR(cmd);
3411
0
      }
3412
0
      session.sf_flags |= SF_ASCII_OVERRIDE;
3413
3414
0
      res = nlstdir(cmd, target);
3415
3416
0
    } else {
3417
0
      pr_response_add_err(R_450, _("%s: Not a regular file"), cmd->arg);
3418
3419
0
      pr_cmd_set_errno(cmd, EPERM);
3420
0
      errno = EPERM;
3421
0
      return PR_ERROR(cmd);
3422
0
    }
3423
3424
0
    sendline(LS_SENDLINE_FL_FLUSH, " ");
3425
0
  }
3426
3427
0
  if (XFER_ABORTED) {
3428
0
    pr_data_abort(0, 0);
3429
0
    res = -1;
3430
3431
0
  } else {
3432
    /* Note that the data connection is NOT cleared here, as an error in
3433
     * NLST still leaves data ready for another command.
3434
     */
3435
0
    ls_done(cmd);
3436
0
  }
3437
3438
0
  return (res < 0 ? PR_ERROR(cmd) : PR_HANDLED(cmd));
3439
0
}
3440
3441
/* Check for the UseGlobbing setting, if any, after the PASS command has
3442
 * been successfully handled, as well as other post-login settings.
3443
 */
3444
0
MODRET ls_post_pass(cmd_rec *cmd) {
3445
0
  config_rec *c;
3446
0
  unsigned char *globbing = NULL;
3447
3448
0
  globbing = get_param_ptr(TOPLEVEL_CONF, "UseGlobbing", FALSE);
3449
0
  if (globbing != NULL &&
3450
0
      *globbing == FALSE) {
3451
0
    pr_log_debug(DEBUG3, "UseGlobbing: disabling globbing functionality");
3452
0
    use_globbing = FALSE;
3453
0
  }
3454
3455
0
  c = find_config(TOPLEVEL_CONF, CONF_PARAM, "ListStyle", FALSE);
3456
0
  if (c != NULL) {
3457
0
    list_style = *((int *) c->argv[0]);
3458
0
  }
3459
3460
0
  return PR_DECLINED(cmd);
3461
0
}
3462
3463
/* Configuration handlers
3464
 */
3465
3466
0
MODRET set_dirfakeusergroup(cmd_rec *cmd) {
3467
0
  int dir_fake_usergroup = -1;
3468
0
  char *as = "ftp";
3469
0
  config_rec *c = NULL;
3470
3471
0
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_ANON|CONF_GLOBAL|
3472
0
    CONF_DIR|CONF_DYNDIR);
3473
3474
0
  if (cmd->argc < 2 ||
3475
0
      cmd->argc > 3) {
3476
0
    CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "syntax: ", (char *) cmd->argv[0],
3477
0
      " on|off [<id to display>]", NULL));
3478
0
  }
3479
3480
0
  dir_fake_usergroup = get_boolean(cmd, 1);
3481
0
  if (dir_fake_usergroup == -1) {
3482
0
    CONF_ERROR(cmd, "expected Boolean argument");
3483
0
  }
3484
3485
0
  if (dir_fake_usergroup == TRUE) {
3486
    /* Use the configured ID to display rather than the default "ftp". */
3487
0
    if (cmd->argc > 2) {
3488
0
      as = cmd->argv[2];
3489
0
    }
3490
3491
0
    c = add_config_param_str(cmd->argv[0], 1, as);
3492
3493
0
  } else {
3494
    /* Still need to add a config_rec to turn off the display of fake IDs. */
3495
0
    c = add_config_param_str(cmd->argv[0], 0);
3496
0
  }
3497
3498
0
  c->flags |= CF_MERGEDOWN;
3499
0
  return PR_HANDLED(cmd);
3500
0
}
3501
3502
0
MODRET set_dirfakemode(cmd_rec *cmd) {
3503
0
  config_rec *c = NULL;
3504
0
  char *endp = NULL;
3505
0
  mode_t fake_mode;
3506
3507
0
  CHECK_ARGS(cmd, 1);
3508
0
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON|CONF_DIR|
3509
0
    CONF_DYNDIR);
3510
3511
0
  fake_mode = (mode_t) strtol(cmd->argv[1], &endp, 8);
3512
3513
0
  if (endp && *endp)
3514
0
    CONF_ERROR(cmd, "parameter must be an octal number");
3515
3516
0
  c = add_config_param(cmd->argv[0], 1, NULL);
3517
0
  c->argv[0] = pcalloc(c->pool, sizeof(mode_t));
3518
0
  *((mode_t *) c->argv[0]) = fake_mode;
3519
0
  c->flags |= CF_MERGEDOWN;
3520
3521
0
  return PR_HANDLED(cmd);
3522
0
}
3523
3524
0
MODRET set_listoptions(cmd_rec *cmd) {
3525
0
  config_rec *c = NULL;
3526
0
  unsigned long flags = 0;
3527
3528
0
  if (cmd->argc-1 < 1) {
3529
0
    CONF_ERROR(cmd, "wrong number of parameters");
3530
0
  }
3531
3532
0
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON|
3533
0
    CONF_DIR|CONF_DYNDIR);
3534
3535
0
  c = add_config_param(cmd->argv[0], 6, NULL, NULL, NULL, NULL, NULL, NULL);
3536
0
  c->flags |= CF_MERGEDOWN;
3537
3538
0
  c->argv[0] = pstrdup(c->pool, cmd->argv[1]);
3539
3540
  /* The default "strict" setting. */
3541
0
  c->argv[1] = pcalloc(c->pool, sizeof(unsigned char));
3542
0
  *((unsigned char *) c->argv[1]) = FALSE;
3543
3544
  /* The default "maxdepth" setting. */
3545
0
  c->argv[2] = pcalloc(c->pool, sizeof(unsigned int));
3546
0
  *((unsigned int *) c->argv[2]) = 0;
3547
3548
  /* The default "maxfiles" setting. */
3549
0
  c->argv[3] = pcalloc(c->pool, sizeof(unsigned int));
3550
0
  *((unsigned int *) c->argv[3]) = 0;
3551
3552
  /* The default "maxdirs" setting. */
3553
0
  c->argv[4] = pcalloc(c->pool, sizeof(unsigned int));
3554
0
  *((unsigned int *) c->argv[4]) = 0;
3555
3556
  /* The default flags */
3557
0
  c->argv[5] = pcalloc(c->pool, sizeof(unsigned long));
3558
3559
  /* Check for, and handle, optional arguments. */
3560
0
  if (cmd->argc-1 >= 2) {
3561
0
    register unsigned int i = 0;
3562
3563
0
    for (i = 2; i < cmd->argc; i++) {
3564
3565
0
      if (strcasecmp(cmd->argv[i], "strict") == 0) {
3566
0
        *((unsigned int *) c->argv[1]) = TRUE;
3567
3568
0
      } else if (strcasecmp(cmd->argv[i], "maxdepth") == 0) {
3569
0
        int maxdepth = atoi(cmd->argv[++i]);
3570
3571
0
        if (maxdepth < 1) {
3572
0
          CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
3573
0
            ": maxdepth must be greater than 0: '", cmd->argv[i],
3574
0
            "'", NULL));
3575
0
        }
3576
3577
0
        *((unsigned int *) c->argv[2]) = maxdepth;
3578
3579
0
      } else if (strcasecmp(cmd->argv[i], "maxfiles") == 0) {
3580
0
        int maxfiles = atoi(cmd->argv[++i]);
3581
3582
0
        if (maxfiles < 1) {
3583
0
          CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
3584
0
            ": maxfiles must be greater than 0: '", (char *) cmd->argv[i],
3585
0
            "'", NULL));
3586
0
        }
3587
3588
0
        *((unsigned int *) c->argv[3]) = maxfiles;
3589
3590
0
      } else if (strcasecmp(cmd->argv[i], "maxdirs") == 0) {
3591
0
        int maxdirs = atoi(cmd->argv[++i]);
3592
3593
0
        if (maxdirs < 1) {
3594
0
          CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
3595
0
            ": maxdirs must be greater than 0: '", (char *) cmd->argv[i],
3596
0
            "'", NULL));
3597
0
        }
3598
3599
0
        *((unsigned int *) c->argv[4]) = maxdirs;
3600
3601
0
      } else if (strcasecmp(cmd->argv[i], "LISTOnly") == 0) {
3602
0
        flags |= LS_FL_LIST_ONLY;
3603
3604
0
      } else if (strcasecmp(cmd->argv[i], "NLSTOnly") == 0) {
3605
0
        flags |= LS_FL_NLST_ONLY;
3606
3607
0
      } else if (strcasecmp(cmd->argv[i], "NoErrorIfAbsent") == 0) {
3608
0
        flags |= LS_FL_NO_ERROR_IF_ABSENT;
3609
3610
0
      } else if (strcasecmp(cmd->argv[i], "AdjustedSymlinks") == 0) {
3611
0
        flags |= LS_FL_ADJUSTED_SYMLINKS;
3612
3613
0
      } else if (strcasecmp(cmd->argv[i], "NoAdjustedSymlinks") == 0) {
3614
        /* Ignored, for backward compatibility. */
3615
3616
0
      } else if (strcasecmp(cmd->argv[i], "SortedNLST") == 0) {
3617
0
        flags |= LS_FL_SORTED_NLST;
3618
3619
0
      } else {
3620
0
        CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown keyword: '",
3621
0
          (char *) cmd->argv[i], "'", NULL));
3622
0
      }
3623
0
    }
3624
0
  }
3625
3626
0
  *((unsigned long *) c->argv[5]) = flags;
3627
0
  return PR_HANDLED(cmd);
3628
0
}
3629
3630
/* usage: ListStyle Unix|Windows */
3631
0
MODRET set_liststyle(cmd_rec *cmd) {
3632
0
  config_rec *c;
3633
0
  const char *style = NULL;
3634
0
  int style_id = -1;
3635
3636
0
  CHECK_ARGS(cmd, 1);
3637
0
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON);
3638
3639
0
  c = add_config_param(cmd->argv[0], 1, NULL);
3640
0
  style = cmd->argv[1];
3641
3642
0
  if (strcasecmp(style, "Unix") == 0) {
3643
0
    style_id = LS_LIST_STYLE_UNIX;
3644
3645
0
  } else if (strcasecmp(style, "Windows") == 0) {
3646
0
    style_id = LS_LIST_STYLE_WINDOWS;
3647
3648
0
  } else {
3649
0
    CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown ListStyle: '", style, "'",
3650
0
      NULL));
3651
0
  }
3652
3653
0
  c->argv[0] = palloc(c->pool, sizeof(int));
3654
0
  *((int *) c->argv[0]) = style_id;
3655
3656
0
  return PR_HANDLED(cmd);
3657
0
}
3658
3659
0
MODRET set_showsymlinks(cmd_rec *cmd) {
3660
0
  int show_symlinks = -1;
3661
0
  config_rec *c = NULL;
3662
3663
0
  CHECK_ARGS(cmd, 1);
3664
0
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON);
3665
3666
0
  show_symlinks = get_boolean(cmd, 1);
3667
0
  if (show_symlinks == -1) {
3668
0
    CONF_ERROR(cmd, "expected Boolean parameter");
3669
0
  }
3670
3671
0
  c = add_config_param(cmd->argv[0], 1, NULL);
3672
0
  c->argv[0] = pcalloc(c->pool, sizeof(unsigned char));
3673
0
  *((unsigned char *) c->argv[0]) = show_symlinks;
3674
0
  c->flags |= CF_MERGEDOWN;
3675
3676
0
  return PR_HANDLED(cmd);
3677
0
}
3678
3679
0
MODRET set_useglobbing(cmd_rec *cmd) {
3680
0
  int globbing = -1;
3681
0
  config_rec *c = NULL;
3682
3683
0
  CHECK_ARGS(cmd, 1);
3684
0
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON);
3685
3686
0
  globbing = get_boolean(cmd, 1);
3687
0
  if (globbing == -1) {
3688
0
    CONF_ERROR(cmd, "expected Boolean parameter");
3689
0
  }
3690
3691
0
  c = add_config_param(cmd->argv[0], 1, NULL);
3692
0
  c->argv[0] = pcalloc(c->pool, sizeof(unsigned char));
3693
0
  *((unsigned char *) c->argv[0]) = globbing;
3694
0
  c->flags |= CF_MERGEDOWN;
3695
3696
0
  return PR_HANDLED(cmd);
3697
0
}
3698
3699
/* Initialization routines
3700
 */
3701
3702
0
static int ls_init(void) {
3703
3704
  /* Add the commands handled by this module to the HELP list. */
3705
0
  pr_help_add(C_LIST, _("[<sp> pathname]"), TRUE);
3706
0
  pr_help_add(C_NLST, _("[<sp> (pathname)]"), TRUE);
3707
0
  pr_help_add(C_STAT, _("[<sp> pathname]"), TRUE);
3708
3709
0
  return 0;
3710
0
}
3711
3712
/* Module API tables
3713
 */
3714
3715
static conftable ls_conftab[] = {
3716
  { "DirFakeUser",  set_dirfakeusergroup,     NULL },
3717
  { "DirFakeGroup", set_dirfakeusergroup,     NULL },
3718
  { "DirFakeMode",  set_dirfakemode,      NULL },
3719
  { "ListOptions",  set_listoptions,      NULL },
3720
  { "ListStyle",  set_liststyle,        NULL },
3721
  { "ShowSymlinks", set_showsymlinks,     NULL },
3722
  { "UseGlobbing",  set_useglobbing,      NULL },
3723
  { NULL,   NULL,         NULL }
3724
};
3725
3726
static cmdtable ls_cmdtab[] = {
3727
  { CMD,    C_NLST, G_DIRS, ls_nlst,  TRUE, FALSE, CL_DIRS },
3728
  { CMD,  C_LIST, G_DIRS, ls_list,  TRUE, FALSE, CL_DIRS },
3729
  { CMD,  C_STAT, G_DIRS, ls_stat,  TRUE, FALSE, CL_INFO },
3730
  { POST_CMD, C_PASS, G_NONE, ls_post_pass, FALSE, FALSE },
3731
  { LOG_CMD,  C_LIST, G_NONE, ls_log_nlst,  FALSE, FALSE },
3732
  { LOG_CMD,  C_NLST, G_NONE, ls_log_nlst,  FALSE, FALSE },
3733
  { LOG_CMD_ERR,C_LIST, G_NONE, ls_err_nlst,   FALSE, FALSE },
3734
  { LOG_CMD_ERR,C_NLST, G_NONE, ls_err_nlst,   FALSE, FALSE },
3735
  { 0, NULL }
3736
};
3737
3738
module ls_module = {
3739
  NULL, NULL,
3740
3741
  /* Module API version */
3742
  0x20,
3743
3744
  /* Module name */
3745
  "ls",
3746
3747
  /* Module configuration handler table */
3748
  ls_conftab,
3749
3750
  /* Module command handler table */
3751
  ls_cmdtab,
3752
3753
  /* Module authentication handler table */
3754
  NULL,
3755
3756
  /* Module initialization */
3757
  ls_init,
3758
3759
  /* Session initialization */
3760
  NULL
3761
};