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