Whamcloud - gitweb
Update version tag to 1.47.1-rc1 for test builds
[tools/e2fsprogs.git] / debugfs / util.c
1 /*
2  * util.c --- utilities for the debugfs program
3  *
4  * Copyright (C) 1993, 1994 Theodore Ts'o.  This file may be
5  * redistributed under the terms of the GNU Public License.
6  *
7  */
8
9 #define _XOPEN_SOURCE 600 /* needed for strptime */
10
11 #include "config.h"
12 #include <stdio.h>
13 #include <unistd.h>
14 #include <stdlib.h>
15 #include <ctype.h>
16 #include <string.h>
17 #include <time.h>
18 #include <signal.h>
19 #ifdef HAVE_GETOPT_H
20 #include <getopt.h>
21 #else
22 extern int optind;
23 extern char *optarg;
24 #endif
25 #ifdef HAVE_OPTRESET
26 extern int optreset;            /* defined by BSD, but not others */
27 #endif
28
29 #include "ss/ss.h"
30 #include "debugfs.h"
31
32 /*
33  * This function resets the libc getopt() function, which keeps
34  * internal state.  Bad design!  Stupid libc API designers!  No
35  * biscuit!
36  *
37  * BSD-derived getopt() functions require that optind be reset to 1 in
38  * order to reset getopt() state.  This used to be generally accepted
39  * way of resetting getopt().  However, glibc's getopt()
40  * has additional getopt() state beyond optind, and requires that
41  * optind be set zero to reset its state.  So the unfortunate state of
42  * affairs is that BSD-derived versions of getopt() misbehave if
43  * optind is set to 0 in order to reset getopt(), and glibc's getopt()
44  * will core dump if optind is set 1 in order to reset getopt().
45  *
46  * More modern versions of BSD require that optreset be set to 1 in
47  * order to reset getopt().   Sigh.  Standards, anyone?
48  *
49  * We hide the hair here.
50  */
51 void reset_getopt(void)
52 {
53 #if defined(__GLIBC__) || defined(__linux__)
54         optind = 0;
55 #else
56         optind = 1;
57 #endif
58 #ifdef HAVE_OPTRESET
59         optreset = 1;           /* Makes BSD getopt happy */
60 #endif
61 }
62
63 static const char *pager_search_list[] = { "pager", "more", "less", 0 };
64 static const char *pager_dir_list[] = { "/usr/bin", "/bin", 0 };
65
66 static const char *find_pager(char *buf)
67 {
68         const char **i, **j;
69
70         for (i = pager_search_list; *i; i++) {
71                 for (j = pager_dir_list; *j; j++) {
72                         sprintf(buf, "%s/%s", *j, *i);
73                         if (access(buf, X_OK) == 0)
74                                 return(buf);
75                 }
76         }
77         return 0;
78 }
79
80 FILE *open_pager(void)
81 {
82         FILE *outfile = 0;
83         const char *pager = ss_safe_getenv("DEBUGFS_PAGER");
84         char buf[80];
85
86         signal(SIGPIPE, SIG_IGN);
87         if (!isatty(1))
88                 return stdout;
89         if (!pager)
90                 pager = ss_safe_getenv("PAGER");
91         if (!pager)
92                 pager = find_pager(buf);
93         if (!pager ||
94             (strcmp(pager, "__none__") == 0) ||
95             ((outfile = popen(pager, "w")) == 0))
96                 return stdout;
97         return outfile;
98 }
99
100 void close_pager(FILE *stream)
101 {
102         if (stream && stream != stdout) pclose(stream);
103 }
104
105 /*
106  * This routine is used whenever a command needs to turn a string into
107  * an inode.
108  */
109 ext2_ino_t string_to_inode(char *str)
110 {
111         ext2_ino_t      ino;
112         int             len = strlen(str);
113         char            *end;
114         int             retval;
115
116         /*
117          * If the string is of the form <ino>, then treat it as an
118          * inode number.
119          */
120         if ((len > 2) && (str[0] == '<') && (str[len-1] == '>')) {
121                 ino = strtoul(str+1, &end, 0);
122                 if (*end=='>' && (ino <= current_fs->super->s_inodes_count))
123                         return ino;
124         }
125
126         retval = ext2fs_namei(current_fs, root, cwd, str, &ino);
127         if (retval) {
128                 com_err(str, retval, 0);
129                 return 0;
130         }
131         if (ino > current_fs->super->s_inodes_count) {
132                 com_err(str, 0, "resolves to an illegal inode number: %u\n",
133                         ino);
134                 return 0;
135         }
136         return ino;
137 }
138
139 /*
140  * This routine returns 1 if the filesystem is not open, and prints an
141  * error message to that effect.
142  */
143 int check_fs_open(char *name)
144 {
145         if (!current_fs) {
146                 com_err(name, 0, "Filesystem not open");
147                 return 1;
148         }
149         return 0;
150 }
151
152 /*
153  * This routine returns 1 if a filesystem is open, and prints an
154  * error message to that effect.
155  */
156 int check_fs_not_open(char *name)
157 {
158         if (current_fs) {
159                 com_err(name, 0,
160                         "Filesystem %s is still open.  Close it first.\n",
161                         current_fs->device_name);
162                 return 1;
163         }
164         return 0;
165 }
166
167 /*
168  * This routine returns 1 if a filesystem is not opened read/write,
169  * and prints an error message to that effect.
170  */
171 int check_fs_read_write(char *name)
172 {
173         if (!(current_fs->flags & EXT2_FLAG_RW)) {
174                 com_err(name, 0, "Filesystem opened read/only");
175                 return 1;
176         }
177         return 0;
178 }
179
180 /*
181  * This routine returns 1 if a filesystem is doesn't have its inode
182  * and block bitmaps loaded, and prints an error message to that
183  * effect.
184  */
185 int check_fs_bitmaps(char *name)
186 {
187         if (!current_fs->block_map || !current_fs->inode_map) {
188                 com_err(name, 0, "Filesystem bitmaps not loaded");
189                 return 1;
190         }
191         return 0;
192 }
193
194 /*
195  * This function takes a __s64 time value and converts it to a string,
196  * using ctime
197  */
198 char *time_to_string(__s64 cl)
199 {
200         static int      do_gmt = -1;
201         time_t          t = (time_t) cl;
202         const char      *tz;
203
204         if (do_gmt == -1) {
205                 /* The diet libc doesn't respect the TZ environment variable */
206                 tz = ss_safe_getenv("TZ");
207                 if (!tz)
208                         tz = "";
209                 do_gmt = !strcmp(tz, "GMT") || !strcmp(tz, "GMT0");
210         }
211
212         return asctime((do_gmt) ? gmtime(&t) : localtime(&t));
213 }
214
215 /*
216  * Parse a string as a time.  Return ((time_t)-1) if the string
217  * doesn't appear to be a sane time.
218  */
219 extern __s64 string_to_time(const char *arg)
220 {
221         struct  tm      ts;
222         __s64           ret;
223         char *tmp;
224
225         if (strcmp(arg, "now") == 0) {
226                 return time(0);
227         }
228         if (arg[0] == '@') {
229                 /* interpret it as an integer */
230                 arg++;
231         fallback:
232                 ret = strtoll(arg, &tmp, 0);
233                 if (*tmp)
234                         return -1;
235                 return ret;
236         }
237         memset(&ts, 0, sizeof(ts));
238 #ifdef HAVE_STRPTIME
239         tmp = strptime(arg, "%Y%m%d%H%M%S", &ts);
240         if (tmp == NULL)
241                 tmp = strptime(arg, "%Y%m%d%H%M", &ts);
242         if (tmp == NULL)
243                 tmp = strptime(arg, "%Y%m%d", &ts);
244         if (tmp == NULL)
245                 goto fallback;
246 #else
247         sscanf(arg, "%4d%2d%2d%2d%2d%2d", &ts.tm_year, &ts.tm_mon,
248                &ts.tm_mday, &ts.tm_hour, &ts.tm_min, &ts.tm_sec);
249         ts.tm_year -= 1900;
250         ts.tm_mon -= 1;
251         if (ts.tm_year < 0 || ts.tm_mon < 0 || ts.tm_mon > 11 ||
252             ts.tm_mday <= 0 || ts.tm_mday > 31 || ts.tm_hour > 23 ||
253             ts.tm_min > 59 || ts.tm_sec > 61)
254                 goto fallback;
255 #endif
256         ts.tm_isdst = -1;
257         /* strptime() may only update the specified fields, which does not
258          * necessarily include ts.tm_yday (%j).  Calculate this if unset:
259          *
260          * Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
261          * 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
262          *
263          * Start with 31 days per month.  Even months have only 30 days, but
264          * reverse in August, subtract one day for those months. February has
265          * only 28 days, not 30, subtract two days. Add day of month, minus
266          * one, since day is not finished yet.  Leap years handled afterward. */
267         if (ts.tm_yday == 0)
268                 ts.tm_yday = (ts.tm_mon * 31) -
269                         ((ts.tm_mon - (ts.tm_mon > 7)) / 2) -
270                         2 * (ts.tm_mon > 1) + ts.tm_mday - 1;
271         ret = ts.tm_sec + ts.tm_min*60 + ts.tm_hour*3600 + ts.tm_yday*86400 +
272                 ((__s64) ts.tm_year-70)*31536000 +
273                 (((__s64) ts.tm_year-69)/4)*86400 -
274                 (((__s64) ts.tm_year-1)/100)*86400 +
275                 (((__s64) ts.tm_year+299)/400)*86400;
276         return ret;
277 }
278
279 /*
280  * This function will convert a string to an unsigned long, printing
281  * an error message if it fails, and returning success or failure in err.
282  */
283 unsigned long parse_ulong(const char *str, const char *cmd,
284                           const char *descr, int *err)
285 {
286         char            *tmp;
287         unsigned long   ret;
288
289         ret = strtoul(str, &tmp, 0);
290         if (*tmp == 0) {
291                 if (err)
292                         *err = 0;
293                 return ret;
294         }
295         com_err(cmd, 0, "Bad %s - %s", descr, str);
296         if (err)
297                 *err = 1;
298         else
299                 exit(1);
300         return 0;
301 }
302
303 /*
304  * This function will convert a string to an unsigned long long, printing
305  * an error message if it fails, and returning success or failure in err.
306  */
307 unsigned long long parse_ulonglong(const char *str, const char *cmd,
308                                    const char *descr, int *err)
309 {
310         char                    *tmp;
311         unsigned long long      ret;
312
313         ret = strtoull(str, &tmp, 0);
314         if (*tmp == 0) {
315                 if (err)
316                         *err = 0;
317                 return ret;
318         }
319         com_err(cmd, 0, "Bad %s - %s", descr, str);
320         if (err)
321                 *err = 1;
322         else
323                 exit(1);
324         return 0;
325 }
326
327 /*
328  * This function will convert a string to a block number.  It returns
329  * 0 on success, 1 on failure.  On failure, it outputs either an optionally
330  * specified error message or a default.
331  */
332 int strtoblk(const char *cmd, const char *str, const char *errmsg,
333              blk64_t *ret)
334 {
335         blk64_t blk;
336         int     err;
337
338         if (errmsg == NULL)
339                 blk = parse_ulonglong(str, cmd, "block number", &err);
340         else
341                 blk = parse_ulonglong(str, cmd, errmsg, &err);
342         *ret = blk;
343         return err;
344 }
345
346 /*
347  * This is a common helper function used by the command processing
348  * routines
349  */
350 int common_args_process(int argc, char *argv[], int min_argc, int max_argc,
351                         const char *cmd, const char *usage, int flags)
352 {
353         if (argc < min_argc || argc > max_argc) {
354                 com_err(argv[0], 0, "Usage: %s %s", cmd, usage);
355                 return 1;
356         }
357         if (flags & CHECK_FS_NOTOPEN) {
358                 if (check_fs_not_open(argv[0]))
359                         return 1;
360         } else {
361                 if (check_fs_open(argv[0]))
362                         return 1;
363         }
364         if ((flags & CHECK_FS_RW) && check_fs_read_write(argv[0]))
365                 return 1;
366         if ((flags & CHECK_FS_BITMAPS) && check_fs_bitmaps(argv[0]))
367                 return 1;
368         return 0;
369 }
370
371 /*
372  * This is a helper function used by do_stat, do_freei, do_seti, and
373  * do_testi, etc.  Basically, any command which takes a single
374  * argument which is a file/inode number specifier.
375  */
376 int common_inode_args_process(int argc, char *argv[],
377                               ext2_ino_t *inode, int flags)
378 {
379         if (common_args_process(argc, argv, 2, 2, argv[0], "<file>", flags))
380                 return 1;
381
382         *inode = string_to_inode(argv[1]);
383         if (!*inode)
384                 return 1;
385         return 0;
386 }
387
388 /*
389  * This is a helper function used by do_freeb, do_setb, and do_testb
390  */
391 int common_block_args_process(int argc, char *argv[],
392                               blk64_t *block, blk64_t *count)
393 {
394         int     err;
395
396         if (common_args_process(argc, argv, 2, 3, argv[0],
397                                 "<block> [count]", CHECK_FS_BITMAPS))
398                 return 1;
399
400         if (strtoblk(argv[0], argv[1], NULL, block))
401                 return 1;
402         if (*block == 0) {
403                 com_err(argv[0], 0, "Invalid block number 0");
404                 return 1;
405         }
406
407         if (argc > 2) {
408                 err = strtoblk(argv[0], argv[2], "count", count);
409                 if (err)
410                         return 1;
411         }
412         return 0;
413 }
414
415 int debugfs_read_inode2(ext2_ino_t ino, struct ext2_inode * inode,
416                         const char *cmd, int bufsize, int flags)
417 {
418         int retval;
419
420         retval = ext2fs_read_inode2(current_fs, ino, inode, bufsize, flags);
421         if (retval) {
422                 com_err(cmd, retval, "while reading inode %u", ino);
423                 return 1;
424         }
425         return 0;
426 }
427
428 int debugfs_read_inode(ext2_ino_t ino, struct ext2_inode * inode,
429                         const char *cmd)
430 {
431         int retval;
432
433         retval = ext2fs_read_inode(current_fs, ino, inode);
434         if (retval) {
435                 com_err(cmd, retval, "while reading inode %u", ino);
436                 return 1;
437         }
438         return 0;
439 }
440
441 int debugfs_write_inode2(ext2_ino_t ino,
442                          struct ext2_inode *inode,
443                          const char *cmd,
444                          int bufsize, int flags)
445 {
446         int retval;
447
448         retval = ext2fs_write_inode2(current_fs, ino, inode, bufsize, flags);
449         if (retval) {
450                 com_err(cmd, retval, "while writing inode %u", ino);
451                 return 1;
452         }
453         return 0;
454 }
455
456 int debugfs_write_inode(ext2_ino_t ino, struct ext2_inode * inode,
457                         const char *cmd)
458 {
459         int retval;
460
461         retval = ext2fs_write_inode(current_fs, ino, inode);
462         if (retval) {
463                 com_err(cmd, retval, "while writing inode %u", ino);
464                 return 1;
465         }
466         return 0;
467 }
468
469 int debugfs_write_new_inode(ext2_ino_t ino, struct ext2_inode * inode,
470                             const char *cmd)
471 {
472         int retval;
473
474         retval = ext2fs_write_new_inode(current_fs, ino, inode);
475         if (retval) {
476                 com_err(cmd, retval, "while creating inode %u", ino);
477                 return 1;
478         }
479         return 0;
480 }
481
482 /*
483  * Given a mode, return the ext2 file type
484  */
485 int ext2_file_type(unsigned int mode)
486 {
487         if (LINUX_S_ISREG(mode))
488                 return EXT2_FT_REG_FILE;
489
490         if (LINUX_S_ISDIR(mode))
491                 return EXT2_FT_DIR;
492
493         if (LINUX_S_ISCHR(mode))
494                 return EXT2_FT_CHRDEV;
495
496         if (LINUX_S_ISBLK(mode))
497                 return EXT2_FT_BLKDEV;
498
499         if (LINUX_S_ISLNK(mode))
500                 return EXT2_FT_SYMLINK;
501
502         if (LINUX_S_ISFIFO(mode))
503                 return EXT2_FT_FIFO;
504
505         if (LINUX_S_ISSOCK(mode))
506                 return EXT2_FT_SOCK;
507
508         return 0;
509 }
510
511 errcode_t read_list(char *str, blk64_t **list, size_t *len)
512 {
513         blk64_t *lst = *list;
514         size_t ln = *len;
515         char *tok, *p = str;
516         errcode_t retval = 0;
517
518         while ((tok = strtok(p, ","))) {
519                 blk64_t *l;
520                 blk64_t x, y;
521                 char *e;
522
523                 errno = 0;
524                 y = x = strtoull(tok, &e, 0);
525                 if (errno) {
526                         retval = errno;
527                         break;
528                 }
529                 if (*e == '-') {
530                         y = strtoull(e + 1, NULL, 0);
531                         if (errno) {
532                                 retval = errno;
533                                 break;
534                         }
535                 } else if (*e != 0) {
536                         retval = EINVAL;
537                         break;
538                 }
539                 if (y < x) {
540                         retval = EINVAL;
541                         break;
542                 }
543                 l = realloc(lst, sizeof(blk64_t) * (ln + y - x + 1));
544                 if (l == NULL) {
545                         retval = ENOMEM;
546                         break;
547                 }
548                 lst = l;
549                 for (; x <= y; x++)
550                         lst[ln++] = x;
551                 p = NULL;
552         }
553
554         *list = lst;
555         *len = ln;
556         return retval;
557 }
558
559 void do_byte_hexdump(FILE *fp, unsigned char *buf, size_t bufsize)
560 {
561         size_t          i, j, max;
562         int             suppress = -1;
563
564         for (i = 0; i < bufsize; i += 16) {
565                 max = (bufsize - i > 16) ? 16 : bufsize - i;
566                 if (suppress < 0) {
567                         if (i && memcmp(buf + i, buf + i - max, max) == 0) {
568                                 suppress = i;
569                                 fprintf(fp, "*\n");
570                                 continue;
571                         }
572                 } else {
573                         if (memcmp(buf + i, buf + suppress, max) == 0)
574                                 continue;
575                         suppress = -1;
576                 }
577                 fprintf(fp, "%04o  ", (unsigned int)i);
578                 for (j = 0; j < 16; j++) {
579                         if (j < max)
580                                 fprintf(fp, "%02x", buf[i+j]);
581                         else
582                                 fprintf(fp, "  ");
583                         if ((j % 2) == 1)
584                                 fprintf(fp, " ");
585                 }
586                 fprintf(fp, " ");
587                 for (j = 0; j < max; j++)
588                         fprintf(fp, "%c", isprint(buf[i+j]) ? buf[i+j] : '.');
589                 fprintf(fp, "\n");
590         }
591         fprintf(fp, "\n");
592 }