Coverage Report

Created: 2023-11-19 07:10

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