btrfs-progs: commands added
[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 #define BASIC_HELP 0
27 #define ADVANCED_HELP 1
28
29 typedef int (*CommandFunction)(int argc, char **argv);
30
31 struct Command {
32         CommandFunction func;   /* function which implements the command */
33         int     nargs;          /* if == 999, any number of arguments
34                                    if >= 0, number of arguments,
35                                    if < 0, _minimum_ number of arguments */
36         char    *verb;          /* verb */
37         char    *help;          /* help lines; from the 2nd line onward they 
38                                    are automatically indented */
39         char    *adv_help;      /* advanced help message; from the 2nd line 
40                                    onward they are automatically indented */
41
42         /* the following fields are run-time filled by the program */
43         char    **cmds;         /* array of subcommands */
44         int     ncmds;          /* number of subcommand */
45 };
46
47 static struct Command commands[] = {
48
49         /*
50                 avoid short commands different for the case only
51         */
52         { do_clone, -2,
53           "subvolume snapshot", "[-r] <source> [<dest>/]<name>\n"
54                 "Create a writable/readonly snapshot of the subvolume <source> with\n"
55                 "the name <name> in the <dest> directory.",
56           NULL
57         },
58         { do_delete_subvolume, 1,
59           "subvolume delete", "<subvolume>\n"
60                 "Delete the subvolume <subvolume>.",
61           NULL
62         },
63         { do_create_subvol, 1,
64           "subvolume create", "[<dest>/]<name>\n"
65                 "Create a subvolume in <dest> (or the current directory if\n"
66                 "not passed).",
67           NULL
68         },
69         { do_subvol_list, -1, "subvolume list", "[-p] <path>\n"
70                 "List the snapshot/subvolume of a filesystem.",
71                 "[-p] <path>\n"
72                 "List the snapshot/subvolume of a filesystem.\n"
73                 "-p        print parent ID"
74         },
75         { do_set_default_subvol, 2,
76           "subvolume set-default", "<id> <path>\n"
77                 "Set the subvolume of the filesystem <path> which will be mounted\n"
78                 "as default.",
79           NULL
80         },
81         { do_find_newer, 2, "subvolume find-new", "<path> <last_gen>\n"
82                 "List the recently modified files in a filesystem.",
83           NULL
84         },
85         { do_defrag, -1,
86           "filesystem defragment", "[-vf] [-c[zlib,lzo]] [-s start] [-l len] [-t size] <file>|<dir> [<file>|<dir>...]\n"
87                 "Defragment a file or a directory.",
88                 "[-vcf] [-s start] [-l len] [-t size] <file>|<dir> [<file>|<dir>...]\n"
89                 "Defragment file data or directory metadata.\n"
90                 "-v         be verbose\n"
91                 "-c         compress the file while defragmenting\n"
92                 "-f         flush data to disk immediately after defragmenting\n"
93                 "-s start   defragment only from byte onward\n"
94                 "-l len     defragment only up to len bytes\n"
95                 "-t size    minimal size of file to be considered for defragmenting\n"
96         },
97         { do_fssync, 1,
98           "filesystem sync", "<path>\n"
99                 "Force a sync on the filesystem <path>.",
100           NULL
101         },
102         { do_resize, 2,
103           "filesystem resize", "[+/-]<newsize>[gkm]|max <filesystem>\n"
104                 "Resize the file system. If 'max' is passed, the filesystem\n"
105                 "will occupe all available space on the device.",
106           NULL
107         },
108         { do_show_filesystem, 999,
109           "filesystem show", "[<device>|<uuid>|<label>]\n"
110                 "Show the info of a btrfs filesystem. If no argument\n"
111                 "is passed, info of all the btrfs filesystem are shown.",
112           NULL
113         },
114         { do_df_filesystem, 1,
115           "filesystem df", "<path>\n"
116                 "Show space usage information for a mount point.",
117           NULL
118         },
119         { do_balance, 1,
120           "filesystem balance", "<path>\n"
121                 "Balance the chunks across the device.",
122           NULL
123         },
124         { do_change_label, -1,
125           "filesystem label", "<device> [<newlabel>]\n"
126           "With one argument, get the label of filesystem on <device>.\n"
127           "If <newlabel> is passed, set the filesystem label to <newlabel>.\n"
128           "The filesystem must be unmounted.\n"
129         },
130         { do_scrub_start, -1,
131           "scrub start", "[-Bdqr] <path>|<device>\n"
132                 "Start a new scrub.",
133                 "\n-B  do not background\n"
134                 "-d  stats per device (-B only)\n"
135                 "-q  quiet\n"
136                 "-r  read only mode\n"
137         },
138         { do_scrub_cancel, 1,
139           "scrub cancel", "<path>|<device>\n"
140                 "Cancel a running scrub.",
141           NULL
142         },
143         { do_scrub_resume, -1,
144           "scrub resume", "[-Bdqr] <path>|<device>\n"
145                 "Resume previously canceled or interrupted scrub.",
146           NULL
147         },
148         { do_scrub_status, -1,
149           "scrub status", "[-d] <path>|<device>\n"
150                 "Show status of running or finished scrub.",
151           NULL
152         },
153         { do_scan, 999, 
154           "device scan", "[<device>...]\n"
155                 "Scan all device for or the passed device for a btrfs\n"
156                 "filesystem.",
157           NULL
158         },
159         { do_add_volume, -2,
160           "device add", "<device> [<device>...] <path>\n"
161                 "Add a device to a filesystem.",
162           NULL
163         },
164         { do_remove_volume, -2,
165           "device delete", "<device> [<device>...] <path>\n"
166                 "Remove a device from a filesystem.",
167           NULL
168         },
169         { 0, 0, 0, 0 }
170 };
171
172 static char *get_prgname(char *programname)
173 {
174         char    *np;
175         np = strrchr(programname,'/');
176         if(!np)
177                 np = programname;
178         else
179                 np++;
180
181         return np;
182 }
183
184 static void print_help(char *programname, struct Command *cmd, int helptype)
185 {
186         char    *pc;
187
188         printf("\t%s %s ", programname, cmd->verb );
189
190         if (helptype == ADVANCED_HELP && cmd->adv_help)
191                 for(pc = cmd->adv_help; *pc; pc++){
192                         putchar(*pc);
193                         if(*pc == '\n')
194                                 printf("\t\t");
195                 }
196         else
197                 for(pc = cmd->help; *pc; pc++){
198                         putchar(*pc);
199                         if(*pc == '\n')
200                                 printf("\t\t");
201                 }
202
203         putchar('\n');
204 }
205
206 static void help(char *np)
207 {
208         struct Command *cp;
209
210         printf("Usage:\n");
211         for( cp = commands; cp->verb; cp++ )
212                 print_help(np, cp, BASIC_HELP);
213
214         printf("\n\t%s help|--help|-h\n\t\tShow the help.\n",np);
215         printf("\n\t%s <cmd> --help\n\t\tShow detailed help for a command or\n\t\t"
216                "subset of commands.\n",np);
217         printf("\n%s\n", BTRFS_BUILD_VERSION);
218 }
219
220 static int split_command(char *cmd, char ***commands)
221 {
222         int     c, l;
223         char    *p, *s;
224
225         for( *commands = 0, l = c = 0, p = s = cmd ; ; p++, l++ ){
226                 if ( *p && *p != ' ' )
227                         continue;
228
229                 /* c + 2 so that we have room for the null */
230                 (*commands) = realloc( (*commands), sizeof(char *)*(c + 2));
231                 (*commands)[c] = strndup(s, l);
232                 c++;
233                 l = 0;
234                 s = p+1;
235                 if( !*p ) break;
236         }
237
238         (*commands)[c] = 0;
239         return c;
240 }
241
242 /*
243         This function checks if the passed command is ambiguous
244 */
245 static int check_ambiguity(struct Command *cmd, char **argv){
246         int             i;
247         struct Command  *cp;
248         /* check for ambiguity */
249         for( i = 0 ; i < cmd->ncmds ; i++ ){
250                 int match;
251                 for( match = 0, cp = commands; cp->verb; cp++ ){
252                         int     j, skip;
253                         char    *s1, *s2;
254
255                         if( cp->ncmds < i )
256                                 continue;
257
258                         for( skip = 0, j = 0 ; j < i ; j++ )
259                                 if( strcmp(cmd->cmds[j], cp->cmds[j])){
260                                         skip=1;
261                                         break;
262                                 }
263                         if(skip)
264                                 continue;
265
266                         if( !strcmp(cmd->cmds[i], cp->cmds[i]))
267                                 continue;
268                         for(s2 = cp->cmds[i], s1 = argv[i+1];
269                                 *s1 == *s2 && *s1; s1++, s2++ ) ;
270                         if( !*s1 )
271                                 match++;
272                 }
273                 if(match){
274                         int j;
275                         fprintf(stderr, "ERROR: in command '");
276                         for( j = 0 ; j <= i ; j++ )
277                                 fprintf(stderr, "%s%s",j?" ":"", argv[j+1]);
278                         fprintf(stderr, "', '%s' is ambiguous\n",argv[j]);
279                         return -2;
280                 }
281         }
282         return 0;
283 }
284
285 /*
286  * This function, compacts the program name and the command in the first
287  * element of the '*av' array
288  */
289 static int prepare_args(int *ac, char ***av, char *prgname, struct Command *cmd ){
290
291         char    **ret;
292         int     i;
293         char    *newname;
294
295         ret = (char **)malloc(sizeof(char*)*(*ac+1));
296         newname = (char*)malloc(strlen(prgname)+strlen(cmd->verb)+2);
297         if( !ret || !newname ){
298                 free(ret);
299                 free(newname);
300                 return -1;
301         }
302
303         ret[0] = newname;
304         for(i=0; i < *ac ; i++ )
305                 ret[i+1] = (*av)[i];
306
307         strcpy(newname, prgname);
308         strcat(newname, " ");
309         strcat(newname, cmd->verb);
310
311         (*ac)++;
312         *av = ret;
313
314         return 0;
315
316 }
317
318
319
320 /*
321         This function performs the following jobs:
322         - show the help if '--help' or 'help' or '-h' are passed
323         - verify that a command is not ambiguous, otherwise show which
324           part of the command is ambiguous
325         - if after a (even partial) command there is '--help' show detailed help
326           for all the matching commands
327         - if the command doesn't match show an error
328         - finally, if a command matches, they return which command matched and
329           the arguments
330
331         The function return 0 in case of help is requested; <0 in case
332         of uncorrect command; >0 in case of matching commands
333         argc, argv are the arg-counter and arg-vector (input)
334         *nargs_ is the number of the arguments after the command (output)
335         **cmd_  is the invoked command (output)
336         ***args_ are the arguments after the command
337
338 */
339 static int parse_args(int argc, char **argv,
340                       CommandFunction *func_,
341                       int *nargs_, char **cmd_, char ***args_ )
342 {
343         struct Command  *cp;
344         struct Command  *matchcmd=0;
345         char            *prgname = get_prgname(argv[0]);
346         int             i=0, helprequested=0;
347
348         if( argc < 2 || !strcmp(argv[1], "help") ||
349                 !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")){
350                 help(prgname);
351                 return 0;
352         }
353
354         for( cp = commands; cp->verb; cp++ )
355                 if( !cp->ncmds)
356                         cp->ncmds = split_command(cp->verb, &(cp->cmds));
357
358         for( cp = commands; cp->verb; cp++ ){
359                 int     match;
360
361                 if( argc-1 < cp->ncmds )
362                         continue;
363                 for( match = 1, i = 0 ; i < cp->ncmds ; i++ ){
364                         char    *s1, *s2;
365                         s1 = cp->cmds[i];
366                         s2 = argv[i+1];
367
368                         for(s2 = cp->cmds[i], s1 = argv[i+1];
369                                 *s1 == *s2 && *s1;
370                                 s1++, s2++ ) ;
371                         if( *s1 ){
372                                 match=0;
373                                 break;
374                         }
375                 }
376
377                 /* If you understand why this code works ...
378                         you are a genious !! */
379                 if(argc>i+1 && !strcmp(argv[i+1],"--help")){
380                         if(!helprequested)
381                                 printf("Usage:\n");
382                         print_help(prgname, cp, ADVANCED_HELP);
383                         helprequested=1;
384                         continue;
385                 }
386
387                 if(!match)
388                         continue;
389
390                 matchcmd = cp;
391                 *nargs_  = argc-matchcmd->ncmds-1;
392                 *cmd_ = matchcmd->verb;
393                 *args_ = argv+matchcmd->ncmds+1;
394                 *func_ = cp->func;
395
396                 break;
397         }
398
399         if(helprequested){
400                 printf("\n%s\n", BTRFS_BUILD_VERSION);
401                 return 0;
402         }
403
404         if(!matchcmd){
405                 fprintf( stderr, "ERROR: unknown command '%s'\n",argv[1]);
406                 help(prgname);
407                 return -1;
408         }
409
410         if(check_ambiguity(matchcmd, argv))
411                 return -2;
412
413         /* check the number of argument */
414         if (matchcmd->nargs < 0 && matchcmd->nargs < -*nargs_ ){
415                 fprintf(stderr, "ERROR: '%s' requires minimum %d arg(s)\n",
416                         matchcmd->verb, -matchcmd->nargs);
417                         return -2;
418         }
419         if(matchcmd->nargs >= 0 && matchcmd->nargs != *nargs_ && matchcmd->nargs != 999){
420                 fprintf(stderr, "ERROR: '%s' requires %d arg(s)\n",
421                         matchcmd->verb, matchcmd->nargs);
422                         return -2;
423         }
424         
425         if (prepare_args( nargs_, args_, prgname, matchcmd )){
426                 fprintf(stderr, "ERROR: not enough memory\\n");
427                 return -20;
428         }
429
430
431         return 1;
432 }
433 int main(int ac, char **av )
434 {
435
436         char            *cmd=0, **args=0;
437         int             nargs=0, r;
438         CommandFunction func=0;
439
440         r = parse_args(ac, av, &func, &nargs, &cmd, &args);
441         if( r <= 0 ){
442                 /* error or no command to parse*/
443                 exit(-r);
444         }
445
446         exit(func(nargs, args));
447
448 }
449