Coverage Report

Created: 2026-09-03 06:37

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