8e0975e1f6b08770f37f3bb6b67489f68dc00789
[platform/upstream/btrfs-progs.git] / btrfs.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public
4  * License v2 as published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9  * General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public
12  * License along with this program; if not, write to the
13  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
14  * Boston, MA 021110-1307, USA.
15  */
16
17 #define _GNU_SOURCE
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21
22 #include "kerncompat.h"
23 #include "btrfs_cmds.h"
24 #include "version.h"
25
26 typedef int (*CommandFunction)(int argc, char **argv);
27
28 struct Command {
29         CommandFunction func;   /* function which implements the command */
30         int     nargs;          /* if == 999, any number of arguments
31                                    if >= 0, number of arguments,
32                                    if < 0, _minimum_ number of arguments */
33         char    *verb;          /* verb */
34         char    *help;          /* help lines; form the 2nd onward they are
35                                    indented */
36
37         /* the following fields are run-time filled by the program */
38         char    **cmds;         /* array of subcommands */
39         int     ncmds;          /* number of subcommand */
40 };
41
42 static struct Command commands[] = {
43
44         /*
45                 avoid short commands different for the case only
46         */
47         { do_clone, 2,
48           "subvolume snapshot", "<source> [<dest>/]<name>\n"
49                 "Create a writable snapshot of the subvolume <source> with\n"
50                 "the name <name> in the <dest> directory."
51         },
52         { do_delete_subvolume, 1,
53           "subvolume delete", "<subvolume>\n"
54                 "Delete the subvolume <subvolume>."
55         },
56         { do_create_subvol, 1,
57           "subvolume create", "[<dest>/]<name>\n"
58                 "Create a subvolume in <dest> (or the current directory if\n"
59                 "not passed)."
60         },
61         { do_subvol_list, 1, "subvolume list", "<path>\n"
62                 "List the snapshot/subvolume of a filesystem."
63         },
64         { do_set_default_subvol, 2,
65           "subvolume set-default", "<id> <path>\n"
66                 "Set the subvolume of the filesystem <path> which will be mounted\n"
67                 "as default."
68         },
69         { do_find_newer, 2, "subvolume find-new", "<path> <last_gen>\n"
70                 "List the recently modified files in a filesystem."
71         },
72         { do_defrag, -1,
73           "filesystem defragment", "[-vf] [-c[zlib,lzo]] [-s start] [-l len] [-t size] <file>|<dir> [<file>|<dir>...]\n"
74                 "Defragment a file or a directory."
75         },
76         { do_fssync, 1,
77           "filesystem sync", "<path>\n"
78                 "Force a sync on the filesystem <path>."
79         },
80         { do_resize, 2,
81           "filesystem resize", "[+/-]<newsize>[gkm]|max <filesystem>\n"
82                 "Resize the file system. If 'max' is passed, the filesystem\n"
83                 "will occupe all available space on the device."
84         },
85         { do_show_filesystem, 999,
86           "filesystem show", "[<device>|<uuid>|<label>]\n"
87                 "Show the info of a btrfs filesystem. If no argument\n"
88                 "is passed, info of all the btrfs filesystem are shown."
89         },
90         { do_df_filesystem, 1,
91           "filesystem df", "<path>\n"
92                 "Show space usage information for a mount point."
93         },
94         { do_balance, 1,
95           "filesystem balance", "<path>\n"
96                 "Balance the chunks across the device."
97         },
98         { do_scan, 999, 
99           "device scan", "[<device>...]\n"
100                 "Scan all device for or the passed device for a btrfs\n"
101                 "filesystem."
102         },
103         { do_add_volume, -2,
104           "device add", "<device> [<device>...] <path>\n"
105                 "Add a device to a filesystem."
106         },
107         { do_remove_volume, -2,
108           "device delete", "<device> [<device>...] <path>\n"
109                 "Remove a device from a filesystem."
110         },
111         { 0, 0 , 0 }
112 };
113
114 static char *get_prgname(char *programname)
115 {
116         char    *np;
117         np = strrchr(programname,'/');
118         if(!np)
119                 np = programname;
120         else
121                 np++;
122
123         return np;
124 }
125
126 static void print_help(char *programname, struct Command *cmd)
127 {
128         char    *pc;
129
130         printf("\t%s %s ", programname, cmd->verb );
131
132         for(pc = cmd->help; *pc; pc++){
133                 putchar(*pc);
134                 if(*pc == '\n')
135                         printf("\t\t");
136         }
137         putchar('\n');
138 }
139
140 static void help(char *np)
141 {
142         struct Command *cp;
143
144         printf("Usage:\n");
145         for( cp = commands; cp->verb; cp++ )
146                 print_help(np, cp);
147
148         printf("\n\t%s help|--help|-h\n\t\tShow the help.\n",np);
149         printf("\n\t%s <cmd> --help\n\t\tShow detailed help for a command or\n\t\t"
150                "subset of commands.\n",np);
151         printf("\n%s\n", BTRFS_BUILD_VERSION);
152 }
153
154 static int split_command(char *cmd, char ***commands)
155 {
156         int     c, l;
157         char    *p, *s;
158
159         for( *commands = 0, l = c = 0, p = s = cmd ; ; p++, l++ ){
160                 if ( *p && *p != ' ' )
161                         continue;
162
163                 /* c + 2 so that we have room for the null */
164                 (*commands) = realloc( (*commands), sizeof(char *)*(c + 2));
165                 (*commands)[c] = strndup(s, l);
166                 c++;
167                 l = 0;
168                 s = p+1;
169                 if( !*p ) break;
170         }
171
172         (*commands)[c] = 0;
173         return c;
174 }
175
176 /*
177         This function checks if the passed command is ambiguous
178 */
179 static int check_ambiguity(struct Command *cmd, char **argv){
180         int             i;
181         struct Command  *cp;
182         /* check for ambiguity */
183         for( i = 0 ; i < cmd->ncmds ; i++ ){
184                 int match;
185                 for( match = 0, cp = commands; cp->verb; cp++ ){
186                         int     j, skip;
187                         char    *s1, *s2;
188
189                         if( cp->ncmds < i )
190                                 continue;
191
192                         for( skip = 0, j = 0 ; j < i ; j++ )
193                                 if( strcmp(cmd->cmds[j], cp->cmds[j])){
194                                         skip=1;
195                                         break;
196                                 }
197                         if(skip)
198                                 continue;
199
200                         if( !strcmp(cmd->cmds[i], cp->cmds[i]))
201                                 continue;
202                         for(s2 = cp->cmds[i], s1 = argv[i+1];
203                                 *s1 == *s2 && *s1; s1++, s2++ ) ;
204                         if( !*s1 )
205                                 match++;
206                 }
207                 if(match){
208                         int j;
209                         fprintf(stderr, "ERROR: in command '");
210                         for( j = 0 ; j <= i ; j++ )
211                                 fprintf(stderr, "%s%s",j?" ":"", argv[j+1]);
212                         fprintf(stderr, "', '%s' is ambiguous\n",argv[j]);
213                         return -2;
214                 }
215         }
216         return 0;
217 }
218
219 /*
220  * This function, compacts the program name and the command in the first
221  * element of the '*av' array
222  */
223 static int prepare_args(int *ac, char ***av, char *prgname, struct Command *cmd ){
224
225         char    **ret;
226         int     i;
227         char    *newname;
228
229         ret = (char **)malloc(sizeof(char*)*(*ac+1));
230         newname = (char*)malloc(strlen(prgname)+strlen(cmd->verb)+2);
231         if( !ret || !newname ){
232                 free(ret);
233                 free(newname);
234                 return -1;
235         }
236
237         ret[0] = newname;
238         for(i=0; i < *ac ; i++ )
239                 ret[i+1] = (*av)[i];
240
241         strcpy(newname, prgname);
242         strcat(newname, " ");
243         strcat(newname, cmd->verb);
244
245         (*ac)++;
246         *av = ret;
247
248         return 0;
249
250 }
251
252
253
254 /*
255
256         This function perform the following jobs:
257         - show the help if '--help' or 'help' or '-h' are passed
258         - verify that a command is not ambiguous, otherwise show which
259           part of the command is ambiguous
260         - if after a (even partial) command there is '--help' show the help
261           for all the matching commands
262         - if the command doesn't' match show an error
263         - finally, if a command match, they return which command is matched and
264           the arguments
265
266         The function return 0 in case of help is requested; <0 in case
267         of uncorrect command; >0 in case of matching commands
268         argc, argv are the arg-counter and arg-vector (input)
269         *nargs_ is the number of the arguments after the command (output)
270         **cmd_  is the invoked command (output)
271         ***args_ are the arguments after the command
272
273 */
274 static int parse_args(int argc, char **argv,
275                       CommandFunction *func_,
276                       int *nargs_, char **cmd_, char ***args_ )
277 {
278         struct Command  *cp;
279         struct Command  *matchcmd=0;
280         char            *prgname = get_prgname(argv[0]);
281         int             i=0, helprequested=0;
282
283         if( argc < 2 || !strcmp(argv[1], "help") ||
284                 !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")){
285                 help(prgname);
286                 return 0;
287         }
288
289         for( cp = commands; cp->verb; cp++ )
290                 if( !cp->ncmds)
291                         cp->ncmds = split_command(cp->verb, &(cp->cmds));
292
293         for( cp = commands; cp->verb; cp++ ){
294                 int     match;
295
296                 if( argc-1 < cp->ncmds )
297                         continue;
298                 for( match = 1, i = 0 ; i < cp->ncmds ; i++ ){
299                         char    *s1, *s2;
300                         s1 = cp->cmds[i];
301                         s2 = argv[i+1];
302
303                         for(s2 = cp->cmds[i], s1 = argv[i+1];
304                                 *s1 == *s2 && *s1;
305                                 s1++, s2++ ) ;
306                         if( *s1 ){
307                                 match=0;
308                                 break;
309                         }
310                 }
311
312                 /* If you understand why this code works ...
313                         you are a genious !! */
314                 if(argc>i+1 && !strcmp(argv[i+1],"--help")){
315                         if(!helprequested)
316                                 printf("Usage:\n");
317                         print_help(prgname, cp);
318                         helprequested=1;
319                         continue;
320                 }
321
322                 if(!match)
323                         continue;
324
325                 matchcmd = cp;
326                 *nargs_  = argc-matchcmd->ncmds-1;
327                 *cmd_ = matchcmd->verb;
328                 *args_ = argv+matchcmd->ncmds+1;
329                 *func_ = cp->func;
330
331                 break;
332         }
333
334         if(helprequested){
335                 printf("\n%s\n", BTRFS_BUILD_VERSION);
336                 return 0;
337         }
338
339         if(!matchcmd){
340                 fprintf( stderr, "ERROR: unknown command '%s'\n",argv[1]);
341                 help(prgname);
342                 return -1;
343         }
344
345         if(check_ambiguity(matchcmd, argv))
346                 return -2;
347
348         /* check the number of argument */
349         if (matchcmd->nargs < 0 && matchcmd->nargs < -*nargs_ ){
350                 fprintf(stderr, "ERROR: '%s' requires minimum %d arg(s)\n",
351                         matchcmd->verb, -matchcmd->nargs);
352                         return -2;
353         }
354         if(matchcmd->nargs >= 0 && matchcmd->nargs != *nargs_ && matchcmd->nargs != 999){
355                 fprintf(stderr, "ERROR: '%s' requires %d arg(s)\n",
356                         matchcmd->verb, matchcmd->nargs);
357                         return -2;
358         }
359         
360         if (prepare_args( nargs_, args_, prgname, matchcmd )){
361                 fprintf(stderr, "ERROR: not enough memory\\n");
362                 return -20;
363         }
364
365
366         return 1;
367 }
368 int main(int ac, char **av )
369 {
370
371         char            *cmd=0, **args=0;
372         int             nargs=0, r;
373         CommandFunction func=0;
374
375         r = parse_args(ac, av, &func, &nargs, &cmd, &args);
376         if( r <= 0 ){
377                 /* error or no command to parse*/
378                 exit(-r);
379         }
380
381         exit(func(nargs, args));
382
383 }
384