Coverage Report

Created: 2026-05-23 07:02

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