1 /*
2  * Part of Very Secure FTPd
3  * Licence: GPL v2
4  * Author: Chris Evans
5  * ls.c
6  *
7  * Would you believe, code to handle directory listing.
8  */
9 
10 #include "ls.h"
11 #include "access.h"
12 #include "defs.h"
13 #include "str.h"
14 #include "strlist.h"
15 #include "sysstr.h"
16 #include "sysutil.h"
17 #include "tunables.h"
18 #include "charconv.h"
19 #include "http_str.h"
20 #include "http_msg.h"
21 
22 static void build_dir_line(struct vsf_session* p_sess,
23                            struct mystr* p_str,
24                            const struct mystr* p_filename_str,
25                            const struct vsf_sysutil_statbuf* p_stat,
26                            long curr_time);
27 
28 static void build_http_dir_line(struct vsf_session* p_sess,
29                            struct mystr* p_str,
30                            const struct mystr* p_filename_str,
31                            const struct vsf_sysutil_statbuf* p_stat,
32                            long curr_time);
33 
34 void
vsf_ls_populate_dir_list(struct vsf_session * p_sess,struct mystr_list * p_list,struct mystr_list * p_subdir_list,struct vsf_sysutil_dir * p_dir,const struct mystr * p_base_dir_str,const struct mystr * p_option_str,const struct mystr * p_filter_str,int is_verbose,int is_http)35 vsf_ls_populate_dir_list(struct vsf_session* p_sess,
36                          struct mystr_list* p_list,
37                          struct mystr_list* p_subdir_list,
38                          struct vsf_sysutil_dir* p_dir,
39                          const struct mystr* p_base_dir_str,
40                          const struct mystr* p_option_str,
41                          const struct mystr* p_filter_str,
42                          int is_verbose,
43                          int is_http)
44 {
45   struct mystr dirline_str = INIT_MYSTR;
46   struct mystr normalised_base_dir_str = INIT_MYSTR;
47   struct str_locate_result loc_result;
48   int a_option;
49   int r_option;
50   int t_option;
51   int F_option;
52   int do_stat = 0;
53   long curr_time = 0;
54   int show_parent = (is_http == 1 && !str_equal_text(p_base_dir_str, "/")) ? 1 : 0;
55 
56   loc_result = str_locate_char(p_option_str, 'a');
57   a_option = loc_result.found;
58   loc_result = str_locate_char(p_option_str, 'r');
59   r_option = loc_result.found;
60   loc_result = str_locate_char(p_option_str, 't');
61   t_option = loc_result.found;
62   loc_result = str_locate_char(p_option_str, 'F');
63   F_option = loc_result.found;
64   loc_result = str_locate_char(p_option_str, 'l');
65   if (loc_result.found)
66   {
67     is_verbose = 1;
68   }
69   /* Invert "reverse" arg for "-t", the time sorting */
70   if (t_option)
71   {
72     r_option = !r_option;
73   }
74   if (is_verbose || t_option || F_option || p_subdir_list != 0)
75   {
76     do_stat = 1;
77   }
78   /* If the filter starts with a . then implicitly enable -a */
79   if (!str_isempty(p_filter_str) && str_get_char_at(p_filter_str, 0) == '.')
80   {
81     a_option = 1;
82   }
83   /* "Normalise" the incoming base directory string by making sure it
84    * ends in a '/' if it is nonempty
85    */
86   if (!str_equal_text(p_base_dir_str, "."))
87   {
88     str_copy(&normalised_base_dir_str, p_base_dir_str);
89   }
90   if (!str_isempty(&normalised_base_dir_str))
91   {
92     unsigned int len = str_getlen(&normalised_base_dir_str);
93     if (str_get_char_at(&normalised_base_dir_str, len - 1) != '/')
94     {
95       str_append_char(&normalised_base_dir_str, '/');
96     }
97   }
98   /* If we're going to need to do time comparisions, cache the local time */
99   if (is_verbose)
100   {
101     curr_time = vsf_sysutil_get_time_sec();
102   }
103   while (1)
104   {
105     static struct mystr s_next_filename_str;
106     static struct mystr s_next_path_and_filename_str;
107     static struct vsf_sysutil_statbuf* s_p_statbuf;
108     str_next_dirent(&s_next_filename_str, p_dir);
109     if (str_isempty(&s_next_filename_str))
110     {
111       break;
112     }
113     {
114       unsigned int len = str_getlen(&s_next_filename_str);
115       if (len > 0 && str_get_char_at(&s_next_filename_str, 0) == '.' &&
116         ((show_parent == 0) || (show_parent == 1 && !str_equal_text(&s_next_filename_str, ".."))))
117       {
118         if (!a_option && !tunable_force_dot_files)
119         {
120           continue;
121         }
122         if (!a_option &&
123             ((len == 2 && str_get_char_at(&s_next_filename_str, 1) == '.') ||
124              len == 1))
125         {
126           continue;
127         }
128       }
129     }
130     /* Don't show hidden directory entries */
131     if (!vsf_access_check_file_visible(&s_next_filename_str))
132     {
133       continue;
134     }
135     /* If we have an ls option which is a filter, apply it */
136     if (!str_isempty(p_filter_str))
137     {
138       unsigned int iters = 0;
139       if (!vsf_filename_passes_filter(&s_next_filename_str, p_filter_str,
140                                       &iters))
141       {
142         continue;
143       }
144     }
145     /* Calculate the full path (relative to CWD) for lstat() and
146      * output purposes
147      */
148     str_copy(&s_next_path_and_filename_str, &normalised_base_dir_str);
149     str_append_str(&s_next_path_and_filename_str, &s_next_filename_str);
150     if (do_stat)
151     {
152       /* lstat() the file. Of course there's a race condition - the
153        * directory entry may have gone away whilst we read it, so
154        * ignore failure to stat
155        */
156       int retval = str_lstat(&s_next_path_and_filename_str, &s_p_statbuf);
157       if (vsf_sysutil_retval_is_error(retval))
158       {
159         continue;
160       }
161     }
162     if (is_verbose)
163     {
164       static struct mystr s_final_file_str;
165       /* If it's a damn symlink, we need to append the target */
166       str_copy(&s_final_file_str, &s_next_filename_str);
167       if (!is_http && vsf_sysutil_statbuf_is_symlink(s_p_statbuf))
168       {
169         static struct mystr s_temp_str;
170         int retval = str_readlink(&s_temp_str, &s_next_path_and_filename_str);
171         if (retval == 0 && !str_isempty(&s_temp_str))
172         {
173           str_append_text(&s_final_file_str, " -> ");
174           str_append_str(&s_final_file_str, &s_temp_str);
175         }
176       }
177       if (F_option && vsf_sysutil_statbuf_is_dir(s_p_statbuf))
178       {
179         str_append_char(&s_final_file_str, '/');
180       }
181       if (is_http)
182       {
183         build_http_dir_line(p_sess, &dirline_str, &s_final_file_str, s_p_statbuf, curr_time);
184       }
185       else
186       {
187         build_dir_line(p_sess, &dirline_str, &s_final_file_str, s_p_statbuf, curr_time);
188       }
189     }
190     else
191     {
192       /* Just emit the filenames - note, we prepend the directory for NLST
193        * but not for LIST
194        */
195       str_copy(&dirline_str, &s_next_path_and_filename_str);
196       if (F_option)
197       {
198         if (vsf_sysutil_statbuf_is_dir(s_p_statbuf))
199         {
200           str_append_char(&dirline_str, '/');
201         }
202         else if (vsf_sysutil_statbuf_is_symlink(s_p_statbuf))
203         {
204           str_append_char(&dirline_str, '@');
205         }
206       }
207       vsf_charconv_convert(p_sess, &dirline_str, VSFTP_CONVDIRECT_FORWARD);
208       str_append_text(&dirline_str, "\r\n");
209     }
210     /* Add filename into our sorted list - sorting by filename or time. Also,
211      * if we are required to, maintain a distinct list of direct
212      * subdirectories.
213      */
214     {
215       static struct mystr s_temp_str;
216       const struct mystr* p_sort_str = 0;
217       const struct mystr* p_sort_subdir_str = 0;
218       if (!t_option)
219       {
220         p_sort_str = &s_next_filename_str;
221       }
222       else
223       {
224         str_alloc_text(&s_temp_str,
225                        vsf_sysutil_statbuf_get_sortkey_mtime(s_p_statbuf));
226         p_sort_str = &s_temp_str;
227         p_sort_subdir_str = &s_temp_str;
228       }
229       str_list_add(p_list, &dirline_str, p_sort_str);
230       if (p_subdir_list != 0 && vsf_sysutil_statbuf_is_dir(s_p_statbuf))
231       {
232         str_list_add(p_subdir_list, &s_next_filename_str, p_sort_subdir_str);
233       }
234     }
235   } /* END: while(1) */
236   str_list_sort(p_list, r_option);
237   if (p_subdir_list != 0)
238   {
239     str_list_sort(p_subdir_list, r_option);
240   }
241   str_free(&dirline_str);
242   str_free(&normalised_base_dir_str);
243 }
244 
245 int
vsf_filename_passes_filter(const struct mystr * p_filename_str,const struct mystr * p_filter_str,unsigned int * iters)246 vsf_filename_passes_filter(const struct mystr* p_filename_str,
247                            const struct mystr* p_filter_str,
248                            unsigned int* iters)
249 {
250   /* A simple routine to match a filename against a pattern.
251    * This routine is used instead of e.g. fnmatch(3), because we should be
252    * reluctant to trust the latter. fnmatch(3) involves _lots_ of string
253    * parsing and handling. There is broad potential for any given fnmatch(3)
254    * implementation to be buggy.
255    *
256    * Currently supported pattern(s):
257    * - any number of wildcards, "*" or "?"
258    * - {,} syntax (not nested)
259    *
260    * Note that pattern matching is only supported within the last path
261    * component. For example, searching for /a/b/? will work, but searching
262    * for /a/?/c will not.
263    */
264   struct mystr filter_remain_str = INIT_MYSTR;
265   struct mystr name_remain_str = INIT_MYSTR;
266   struct mystr temp_str = INIT_MYSTR;
267   struct mystr brace_list_str = INIT_MYSTR;
268   struct mystr new_filter_str = INIT_MYSTR;
269   int ret = 0;
270   char last_token = 0;
271   int must_match_at_current_pos = 1;
272   str_copy(&filter_remain_str, p_filter_str);
273 
274   if (!str_isempty (&filter_remain_str) && !str_isempty(p_filename_str)) {
275     if (str_get_char_at(p_filter_str, 0) == '/') {
276       if (str_get_char_at(p_filename_str, 0) != '/') {
277         str_getcwd (&name_remain_str);
278 
279         if (str_getlen(&name_remain_str) > 1) /* cwd != root dir */
280           str_append_char (&name_remain_str, '/');
281 
282         str_append_str (&name_remain_str, p_filename_str);
283       }
284       else
285         str_copy(&name_remain_str, p_filename_str);
286     } else {
287       if (str_get_char_at(p_filter_str, 0) != '{')
288         str_basename (&name_remain_str, p_filename_str);
289       else
290         str_copy (&name_remain_str, p_filename_str);
291     }
292   } else
293     str_copy(&name_remain_str, p_filename_str);
294 
295   while (!str_isempty(&filter_remain_str) && *iters < VSFTP_MATCHITERS_MAX)
296   {
297     static struct mystr s_match_needed_str;
298     /* Locate next special token */
299     struct str_locate_result locate_result =
300       str_locate_chars(&filter_remain_str, "*?{");
301     (*iters)++;
302     /* Isolate text leading up to token (if any) - needs to be matched */
303     if (locate_result.found)
304     {
305       unsigned int indexx = locate_result.index;
306       str_left(&filter_remain_str, &s_match_needed_str, indexx);
307       str_mid_to_end(&filter_remain_str, &temp_str, indexx + 1);
308       str_copy(&filter_remain_str, &temp_str);
309       last_token = locate_result.char_found;
310     }
311     else
312     {
313       /* No more tokens. Must match remaining filter string exactly. */
314       str_copy(&s_match_needed_str, &filter_remain_str);
315       str_empty(&filter_remain_str);
316       last_token = 0;
317     }
318     if (!str_isempty(&s_match_needed_str))
319     {
320       /* Need to match something.. could be a match which has to start at
321        * current position, or we could allow it to start anywhere
322        */
323       unsigned int indexx;
324       locate_result = str_locate_str(&name_remain_str, &s_match_needed_str);
325       if (!locate_result.found)
326       {
327         /* Fail */
328         goto out;
329       }
330       indexx = locate_result.index;
331       if (must_match_at_current_pos && indexx > 0)
332       {
333         goto out;
334       }
335       if (!must_match_at_current_pos)
336       {
337         struct mystr scan_fwd = INIT_MYSTR;
338 
339         str_mid_to_end(&name_remain_str, &scan_fwd,
340                         indexx + str_getlen(&s_match_needed_str));
341         /* We're allowed to be greedy, test if it match further along
342          * keep advancing indexx while we can still match.
343          */
344         while( (locate_result = str_locate_str(&scan_fwd, &s_match_needed_str)),
345             locate_result.found )
346         {
347           indexx += locate_result.index + str_getlen(&s_match_needed_str);
348           str_mid_to_end(&scan_fwd, &temp_str,
349                          locate_result.index + str_getlen(&s_match_needed_str));
350           str_copy(&scan_fwd, &temp_str);
351         }
352         str_free(&scan_fwd);
353       }
354       /* Chop matched string out of remainder */
355       str_mid_to_end(&name_remain_str, &temp_str,
356                      indexx + str_getlen(&s_match_needed_str));
357       str_copy(&name_remain_str, &temp_str);
358     }
359     if (last_token == '?')
360     {
361       if (str_isempty(&name_remain_str))
362       {
363         goto out;
364       }
365       str_right(&name_remain_str, &temp_str, str_getlen(&name_remain_str) - 1);
366       str_copy(&name_remain_str, &temp_str);
367       must_match_at_current_pos = 1;
368     }
369     else if (last_token == '{')
370     {
371       struct str_locate_result end_brace =
372         str_locate_char(&filter_remain_str, '}');
373       must_match_at_current_pos = 1;
374       if (end_brace.found)
375       {
376         str_split_char(&filter_remain_str, &temp_str, '}');
377         str_copy(&brace_list_str, &filter_remain_str);
378         str_copy(&filter_remain_str, &temp_str);
379         str_split_char(&brace_list_str, &temp_str, ',');
380         while (!str_isempty(&brace_list_str))
381         {
382           str_copy(&new_filter_str, &brace_list_str);
383           str_append_str(&new_filter_str, &filter_remain_str);
384           if (vsf_filename_passes_filter(&name_remain_str, &new_filter_str,
385                                          iters))
386           {
387             ret = 1;
388             goto out;
389           }
390           str_copy(&brace_list_str, &temp_str);
391           str_split_char(&brace_list_str, &temp_str, ',');
392         }
393         goto out;
394       }
395       else if (str_isempty(&name_remain_str) ||
396                str_get_char_at(&name_remain_str, 0) != '{')
397       {
398         goto out;
399       }
400       else
401       {
402         str_right(&name_remain_str, &temp_str,
403                   str_getlen(&name_remain_str) - 1);
404         str_copy(&name_remain_str, &temp_str);
405       }
406     }
407     else
408     {
409       must_match_at_current_pos = 0;
410     }
411   }
412   /* Any incoming string left means no match unless we ended on the correct
413    * type of wildcard.
414    */
415   if (str_getlen(&name_remain_str) > 0 && last_token != '*')
416   {
417     goto out;
418   }
419   /* OK, a match */
420   ret = 1;
421   if (*iters == VSFTP_MATCHITERS_MAX) {
422     ret = 0;
423   }
424 out:
425   str_free(&filter_remain_str);
426   str_free(&name_remain_str);
427   str_free(&temp_str);
428   str_free(&brace_list_str);
429   str_free(&new_filter_str);
430   return ret;
431 }
432 
433 static void
build_dir_line(struct vsf_session * p_sess,struct mystr * p_str,const struct mystr * p_filename_str,const struct vsf_sysutil_statbuf * p_stat,long curr_time)434 build_dir_line(struct vsf_session* p_sess, struct mystr* p_str, const struct mystr* p_filename_str,
435                const struct vsf_sysutil_statbuf* p_stat, long curr_time)
436 {
437   static struct mystr s_tmp_str;
438   filesize_t size = vsf_sysutil_statbuf_get_size(p_stat);
439   /* Permissions */
440   str_alloc_text(p_str, vsf_sysutil_statbuf_get_perms(p_stat));
441   str_append_char(p_str, ' ');
442   /* Hard link count */
443   str_alloc_ulong(&s_tmp_str, vsf_sysutil_statbuf_get_links(p_stat));
444   str_lpad(&s_tmp_str, 4);
445   str_append_str(p_str, &s_tmp_str);
446   str_append_char(p_str, ' ');
447   /* User */
448   str_getuser(&s_tmp_str, p_stat);
449   str_rpad(&s_tmp_str, 8);
450   str_append_str(p_str, &s_tmp_str);
451   str_append_char(p_str, ' ');
452   /* Group */
453   str_getgroup(&s_tmp_str, p_stat);
454   str_rpad(&s_tmp_str, 8);
455   str_append_str(p_str, &s_tmp_str);
456   str_append_char(p_str, ' ');
457   /* Size in bytes */
458   str_alloc_filesize_t(&s_tmp_str, size);
459   str_lpad(&s_tmp_str, 8);
460   str_append_str(p_str, &s_tmp_str);
461   str_append_char(p_str, ' ');
462   /* Date stamp */
463   str_append_text(p_str, vsf_sysutil_statbuf_get_date(p_stat,
464                                                       tunable_use_localtime,
465                                                       curr_time));
466   str_append_char(p_str, ' ');
467   /* Filename */
468   str_append_str(p_str, p_filename_str);
469   vsf_charconv_convert(p_sess, p_str, VSFTP_CONVDIRECT_FORWARD);
470   str_append_text(p_str, "\r\n");
471 }
472 
473 static void
build_http_dir_line(struct vsf_session * p_sess,struct mystr * p_str,const struct mystr * p_filename_str,const struct vsf_sysutil_statbuf * p_stat,long curr_time)474 build_http_dir_line(struct vsf_session* p_sess, struct mystr* p_str, const struct mystr* p_filename_str,
475                     const struct vsf_sysutil_statbuf* p_stat, long curr_time)
476 {
477   str_process_template(p_sess, p_str, &msg_browse_line, p_filename_str, p_stat, curr_time, 0);
478 }
479 
480