Generated code for 'glob-expand'.
[libguestfs.git] / daemon / ls.c
1 /* libguestfs - the guestfsd daemon
2  * Copyright (C) 2009 Red Hat Inc. 
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <dirent.h>
27 #include <sys/stat.h>
28
29 #include "daemon.h"
30 #include "actions.h"
31
32 char **
33 do_ls (char *path)
34 {
35   char **r = NULL;
36   int size = 0, alloc = 0;
37   DIR *dir;
38   struct dirent *d;
39
40   NEED_ROOT (NULL);
41   ABS_PATH (path, NULL);
42
43   CHROOT_IN;
44   dir = opendir (path);
45   CHROOT_OUT;
46
47   if (!dir) {
48     reply_with_perror ("opendir: %s", path);
49     return NULL;
50   }
51
52   while ((d = readdir (dir)) != NULL) {
53     if (strcmp (d->d_name, ".") == 0 || strcmp (d->d_name, "..") == 0)
54       continue;
55
56     if (add_string (&r, &size, &alloc, d->d_name) == -1) {
57       closedir (dir);
58       return NULL;
59     }
60   }
61
62   if (add_string (&r, &size, &alloc, NULL) == -1) {
63     closedir (dir);
64     return NULL;
65   }
66
67   if (closedir (dir) == -1) {
68     reply_with_perror ("closedir: %s", path);
69     free_strings (r);
70     return NULL;
71   }
72
73   sort_strings (r, size-1);
74   return r;
75 }
76
77 char *
78 do_ll (char *path)
79 {
80   int r, len;
81   char *out, *err;
82   char *spath;
83
84   //NEED_ROOT
85   ABS_PATH (path, NULL);
86
87   /* This exposes the /sysroot, because we can't chroot and run the ls
88    * command (since 'ls' won't necessarily exist in the chroot).  This
89    * command is not meant for serious use anyway, just for quick
90    * interactive sessions.  For the same reason, you can also "escape"
91    * the sysroot (eg. 'll /..').
92    */
93   len = strlen (path) + 9;
94   spath = malloc (len);
95   if (!spath) {
96     reply_with_perror ("malloc");
97     return NULL;
98   }
99   snprintf (spath, len, "/sysroot%s", path);
100
101   r = command (&out, &err, "ls", "-la", spath, NULL);
102   free (spath);
103   if (r == -1) {
104     reply_with_error ("%s", err);
105     free (out);
106     free (err);
107     return NULL;
108   }
109
110   free (err);
111   return out;                   /* caller frees */
112 }