daemon: count_strings function returns size_t
[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 (const char *path)
34 {
35   char **r = NULL;
36   int size = 0, alloc = 0;
37   DIR *dir;
38   struct dirent *d;
39
40   CHROOT_IN;
41   dir = opendir (path);
42   CHROOT_OUT;
43
44   if (!dir) {
45     reply_with_perror ("opendir: %s", path);
46     return NULL;
47   }
48
49   while ((d = readdir (dir)) != NULL) {
50     if (STREQ (d->d_name, ".") || STREQ (d->d_name, ".."))
51       continue;
52
53     if (add_string (&r, &size, &alloc, d->d_name) == -1) {
54       closedir (dir);
55       return NULL;
56     }
57   }
58
59   if (add_string (&r, &size, &alloc, NULL) == -1) {
60     closedir (dir);
61     return NULL;
62   }
63
64   if (closedir (dir) == -1) {
65     reply_with_perror ("closedir: %s", path);
66     free_strings (r);
67     return NULL;
68   }
69
70   sort_strings (r, size-1);
71   return r;
72 }
73
74 /* Because we can't chroot and run the ls command (since 'ls' won't
75  * necessarily exist in the chroot), this command can be used to escape
76  * from the sysroot (eg. 'll /..').  This command is not meant for
77  * serious use anyway, just for quick interactive sessions.
78  */
79
80 char *
81 do_ll (const char *path)
82 {
83   int r;
84   char *out, *err;
85   char *spath;
86
87   spath = sysroot_path (path);
88   if (!spath) {
89     reply_with_perror ("malloc");
90     return NULL;
91   }
92
93   r = command (&out, &err, "ls", "-la", spath, NULL);
94   free (spath);
95   if (r == -1) {
96     reply_with_error ("%s", err);
97     free (out);
98     free (err);
99     return NULL;
100   }
101
102   free (err);
103   return out;                   /* caller frees */
104 }