• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  */
reset_getopt(void)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 
find_pager(char * buf)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 
open_pager(void)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 
close_pager(FILE * stream)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  */
string_to_inode(char * str)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  */
check_fs_open(char * name)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  */
check_fs_not_open(char * name)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  */
check_fs_read_write(char * name)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  */
check_fs_bitmaps(char * name)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 
inode_time_to_string(__u32 xtime,__u32 xtime_extra)194 char *inode_time_to_string(__u32 xtime, __u32 xtime_extra)
195 {
196 	__s64 t = (__s32) xtime;
197 
198 	t += (__s64) (xtime_extra & EXT4_EPOCH_MASK) << 32;
199 	return time_to_string(t);
200 }
201 
202 /*
203  * This function takes a __s64 time value and converts it to a string,
204  * using ctime
205  */
time_to_string(__s64 cl)206 char *time_to_string(__s64 cl)
207 {
208 	static int	do_gmt = -1;
209 	time_t		t = (time_t) cl;
210 	const char	*tz;
211 
212 	if (do_gmt == -1) {
213 		/* The diet libc doesn't respect the TZ environment variable */
214 		tz = ss_safe_getenv("TZ");
215 		if (!tz)
216 			tz = "";
217 		do_gmt = !strcmp(tz, "GMT") || !strcmp(tz, "GMT0");
218 	}
219 
220 	return asctime((do_gmt) ? gmtime(&t) : localtime(&t));
221 }
222 
223 /*
224  * Parse a string as a time.  Return ((time_t)-1) if the string
225  * doesn't appear to be a sane time.
226  */
string_to_time(const char * arg)227 extern __s64 string_to_time(const char *arg)
228 {
229 	struct	tm	ts;
230 	__s64		ret;
231 	char *tmp;
232 
233 	if (strcmp(arg, "now") == 0) {
234 		return time(0);
235 	}
236 	if (arg[0] == '@') {
237 		/* interpret it as an integer */
238 		arg++;
239 	fallback:
240 		ret = strtoll(arg, &tmp, 0);
241 		if (*tmp)
242 			return -1;
243 		return ret;
244 	}
245 	memset(&ts, 0, sizeof(ts));
246 #ifdef HAVE_STRPTIME
247 	tmp = strptime(arg, "%Y%m%d%H%M%S", &ts);
248 	if (tmp == NULL)
249 		tmp = strptime(arg, "%Y%m%d%H%M", &ts);
250 	if (tmp == NULL)
251 		tmp = strptime(arg, "%Y%m%d", &ts);
252 	if (tmp == NULL)
253 		goto fallback;
254 #else
255 	sscanf(arg, "%4d%2d%2d%2d%2d%2d", &ts.tm_year, &ts.tm_mon,
256 	       &ts.tm_mday, &ts.tm_hour, &ts.tm_min, &ts.tm_sec);
257 	ts.tm_year -= 1900;
258 	ts.tm_mon -= 1;
259 	if (ts.tm_year < 0 || ts.tm_mon < 0 || ts.tm_mon > 11 ||
260 	    ts.tm_mday <= 0 || ts.tm_mday > 31 || ts.tm_hour > 23 ||
261 	    ts.tm_min > 59 || ts.tm_sec > 61)
262 		goto fallback;
263 #endif
264 	ts.tm_isdst = -1;
265 	/* strptime() may only update the specified fields, which does not
266 	 * necessarily include ts.tm_yday (%j).  Calculate this if unset:
267 	 *
268 	 * Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
269 	 * 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
270 	 *
271 	 * Start with 31 days per month.  Even months have only 30 days, but
272 	 * reverse in August, subtract one day for those months. February has
273 	 * only 28 days, not 30, subtract two days. Add day of month, minus
274 	 * one, since day is not finished yet.  Leap years handled afterward. */
275 	if (ts.tm_yday == 0)
276 		ts.tm_yday = (ts.tm_mon * 31) -
277 			((ts.tm_mon - (ts.tm_mon > 7)) / 2) -
278 			2 * (ts.tm_mon > 1) + ts.tm_mday - 1;
279 	ret = ts.tm_sec + ts.tm_min*60 + ts.tm_hour*3600 + ts.tm_yday*86400 +
280 		((__s64) ts.tm_year-70)*31536000 +
281 		(((__s64) ts.tm_year-69)/4)*86400 -
282 		(((__s64) ts.tm_year-1)/100)*86400 +
283 		(((__s64) ts.tm_year+299)/400)*86400;
284 	return ret;
285 }
286 
287 /*
288  * This function will convert a string to an unsigned long, printing
289  * an error message if it fails, and returning success or failure in err.
290  */
parse_ulong(const char * str,const char * cmd,const char * descr,int * err)291 unsigned long parse_ulong(const char *str, const char *cmd,
292 			  const char *descr, int *err)
293 {
294 	char		*tmp;
295 	unsigned long	ret;
296 
297 	ret = strtoul(str, &tmp, 0);
298 	if (*tmp == 0) {
299 		if (err)
300 			*err = 0;
301 		return ret;
302 	}
303 	com_err(cmd, 0, "Bad %s - %s", descr, str);
304 	if (err)
305 		*err = 1;
306 	else
307 		exit(1);
308 	return 0;
309 }
310 
311 /*
312  * This function will convert a string to an unsigned long long, printing
313  * an error message if it fails, and returning success or failure in err.
314  */
parse_ulonglong(const char * str,const char * cmd,const char * descr,int * err)315 unsigned long long parse_ulonglong(const char *str, const char *cmd,
316 				   const char *descr, int *err)
317 {
318 	char			*tmp;
319 	unsigned long long	ret;
320 
321 	ret = strtoull(str, &tmp, 0);
322 	if (*tmp == 0) {
323 		if (err)
324 			*err = 0;
325 		return ret;
326 	}
327 	com_err(cmd, 0, "Bad %s - %s", descr, str);
328 	if (err)
329 		*err = 1;
330 	else
331 		exit(1);
332 	return 0;
333 }
334 
335 /*
336  * This function will convert a string to a block number.  It returns
337  * 0 on success, 1 on failure.  On failure, it outputs either an optionally
338  * specified error message or a default.
339  */
strtoblk(const char * cmd,const char * str,const char * errmsg,blk64_t * ret)340 int strtoblk(const char *cmd, const char *str, const char *errmsg,
341 	     blk64_t *ret)
342 {
343 	blk64_t	blk;
344 	int	err;
345 
346 	if (errmsg == NULL)
347 		blk = parse_ulonglong(str, cmd, "block number", &err);
348 	else
349 		blk = parse_ulonglong(str, cmd, errmsg, &err);
350 	*ret = blk;
351 	return err;
352 }
353 
354 /*
355  * This is a common helper function used by the command processing
356  * routines
357  */
common_args_process(int argc,char * argv[],int min_argc,int max_argc,const char * cmd,const char * usage,int flags)358 int common_args_process(int argc, char *argv[], int min_argc, int max_argc,
359 			const char *cmd, const char *usage, int flags)
360 {
361 	if (argc < min_argc || argc > max_argc) {
362 		com_err(argv[0], 0, "Usage: %s %s", cmd, usage);
363 		return 1;
364 	}
365 	if (flags & CHECK_FS_NOTOPEN) {
366 		if (check_fs_not_open(argv[0]))
367 			return 1;
368 	} else {
369 		if (check_fs_open(argv[0]))
370 			return 1;
371 	}
372 	if ((flags & CHECK_FS_RW) && check_fs_read_write(argv[0]))
373 		return 1;
374 	if ((flags & CHECK_FS_BITMAPS) && check_fs_bitmaps(argv[0]))
375 		return 1;
376 	return 0;
377 }
378 
379 /*
380  * This is a helper function used by do_stat, do_freei, do_seti, and
381  * do_testi, etc.  Basically, any command which takes a single
382  * argument which is a file/inode number specifier.
383  */
common_inode_args_process(int argc,char * argv[],ext2_ino_t * inode,int flags)384 int common_inode_args_process(int argc, char *argv[],
385 			      ext2_ino_t *inode, int flags)
386 {
387 	if (common_args_process(argc, argv, 2, 2, argv[0], "<file>", flags))
388 		return 1;
389 
390 	*inode = string_to_inode(argv[1]);
391 	if (!*inode)
392 		return 1;
393 	return 0;
394 }
395 
396 /*
397  * This is a helper function used by do_freeb, do_setb, and do_testb
398  */
common_block_args_process(int argc,char * argv[],blk64_t * block,blk64_t * count)399 int common_block_args_process(int argc, char *argv[],
400 			      blk64_t *block, blk64_t *count)
401 {
402 	int	err;
403 
404 	if (common_args_process(argc, argv, 2, 3, argv[0],
405 				"<block> [count]", CHECK_FS_BITMAPS))
406 		return 1;
407 
408 	if (strtoblk(argv[0], argv[1], NULL, block))
409 		return 1;
410 	if (*block == 0) {
411 		com_err(argv[0], 0, "Invalid block number 0");
412 		return 1;
413 	}
414 
415 	if (argc > 2) {
416 		err = strtoblk(argv[0], argv[2], "count", count);
417 		if (err)
418 			return 1;
419 	}
420 	return 0;
421 }
422 
debugfs_read_inode2(ext2_ino_t ino,struct ext2_inode * inode,const char * cmd,int bufsize,int flags)423 int debugfs_read_inode2(ext2_ino_t ino, struct ext2_inode * inode,
424 			const char *cmd, int bufsize, int flags)
425 {
426 	int retval;
427 
428 	retval = ext2fs_read_inode2(current_fs, ino, inode, bufsize, flags);
429 	if (retval) {
430 		com_err(cmd, retval, "while reading inode %u", ino);
431 		return 1;
432 	}
433 	return 0;
434 }
435 
debugfs_read_inode(ext2_ino_t ino,struct ext2_inode * inode,const char * cmd)436 int debugfs_read_inode(ext2_ino_t ino, struct ext2_inode * inode,
437 			const char *cmd)
438 {
439 	int retval;
440 
441 	retval = ext2fs_read_inode(current_fs, ino, inode);
442 	if (retval) {
443 		com_err(cmd, retval, "while reading inode %u", ino);
444 		return 1;
445 	}
446 	return 0;
447 }
448 
debugfs_write_inode2(ext2_ino_t ino,struct ext2_inode * inode,const char * cmd,int bufsize,int flags)449 int debugfs_write_inode2(ext2_ino_t ino,
450 			 struct ext2_inode *inode,
451 			 const char *cmd,
452 			 int bufsize, int flags)
453 {
454 	int retval;
455 
456 	retval = ext2fs_write_inode2(current_fs, ino, inode, bufsize, flags);
457 	if (retval) {
458 		com_err(cmd, retval, "while writing inode %u", ino);
459 		return 1;
460 	}
461 	return 0;
462 }
463 
debugfs_write_inode(ext2_ino_t ino,struct ext2_inode * inode,const char * cmd)464 int debugfs_write_inode(ext2_ino_t ino, struct ext2_inode * inode,
465 			const char *cmd)
466 {
467 	int retval;
468 
469 	retval = ext2fs_write_inode(current_fs, ino, inode);
470 	if (retval) {
471 		com_err(cmd, retval, "while writing inode %u", ino);
472 		return 1;
473 	}
474 	return 0;
475 }
476 
debugfs_write_new_inode(ext2_ino_t ino,struct ext2_inode * inode,const char * cmd)477 int debugfs_write_new_inode(ext2_ino_t ino, struct ext2_inode * inode,
478 			    const char *cmd)
479 {
480 	int retval;
481 
482 	retval = ext2fs_write_new_inode(current_fs, ino, inode);
483 	if (retval) {
484 		com_err(cmd, retval, "while creating inode %u", ino);
485 		return 1;
486 	}
487 	return 0;
488 }
489 
490 /*
491  * Given a mode, return the ext2 file type
492  */
ext2_file_type(unsigned int mode)493 int ext2_file_type(unsigned int mode)
494 {
495 	if (LINUX_S_ISREG(mode))
496 		return EXT2_FT_REG_FILE;
497 
498 	if (LINUX_S_ISDIR(mode))
499 		return EXT2_FT_DIR;
500 
501 	if (LINUX_S_ISCHR(mode))
502 		return EXT2_FT_CHRDEV;
503 
504 	if (LINUX_S_ISBLK(mode))
505 		return EXT2_FT_BLKDEV;
506 
507 	if (LINUX_S_ISLNK(mode))
508 		return EXT2_FT_SYMLINK;
509 
510 	if (LINUX_S_ISFIFO(mode))
511 		return EXT2_FT_FIFO;
512 
513 	if (LINUX_S_ISSOCK(mode))
514 		return EXT2_FT_SOCK;
515 
516 	return 0;
517 }
518 
read_list(char * str,blk64_t ** list,size_t * len)519 errcode_t read_list(char *str, blk64_t **list, size_t *len)
520 {
521 	blk64_t *lst = *list;
522 	size_t ln = *len;
523 	char *tok, *p = str;
524 	errcode_t retval = 0;
525 
526 	while ((tok = strtok(p, ","))) {
527 		blk64_t *l;
528 		blk64_t x, y;
529 		char *e;
530 
531 		errno = 0;
532 		y = x = strtoull(tok, &e, 0);
533 		if (errno) {
534 			retval = errno;
535 			break;
536 		}
537 		if (*e == '-') {
538 			y = strtoull(e + 1, NULL, 0);
539 			if (errno) {
540 				retval = errno;
541 				break;
542 			}
543 		} else if (*e != 0) {
544 			retval = EINVAL;
545 			break;
546 		}
547 		if (y < x) {
548 			retval = EINVAL;
549 			break;
550 		}
551 		l = realloc(lst, sizeof(blk64_t) * (ln + y - x + 1));
552 		if (l == NULL) {
553 			retval = ENOMEM;
554 			break;
555 		}
556 		lst = l;
557 		for (; x <= y; x++)
558 			lst[ln++] = x;
559 		p = NULL;
560 	}
561 
562 	*list = lst;
563 	*len = ln;
564 	return retval;
565 }
566 
do_byte_hexdump(FILE * fp,unsigned char * buf,size_t bufsize)567 void do_byte_hexdump(FILE *fp, unsigned char *buf, size_t bufsize)
568 {
569 	size_t		i, j, max;
570 	int		suppress = -1;
571 
572 	for (i = 0; i < bufsize; i += 16) {
573 		max = (bufsize - i > 16) ? 16 : bufsize - i;
574 		if (suppress < 0) {
575 			if (i && memcmp(buf + i, buf + i - max, max) == 0) {
576 				suppress = i;
577 				fprintf(fp, "*\n");
578 				continue;
579 			}
580 		} else {
581 			if (memcmp(buf + i, buf + suppress, max) == 0)
582 				continue;
583 			suppress = -1;
584 		}
585 		fprintf(fp, "%04o  ", (unsigned int)i);
586 		for (j = 0; j < 16; j++) {
587 			if (j < max)
588 				fprintf(fp, "%02x", buf[i+j]);
589 			else
590 				fprintf(fp, "  ");
591 			if ((j % 2) == 1)
592 				fprintf(fp, " ");
593 		}
594 		fprintf(fp, " ");
595 		for (j = 0; j < max; j++)
596 			fprintf(fp, "%c", isprint(buf[i+j]) ? buf[i+j] : '.');
597 		fprintf(fp, "\n");
598 	}
599 	fprintf(fp, "\n");
600 }
601