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
22extern int optind;
23extern char *optarg;
24#endif
25#ifdef HAVE_OPTRESET
26extern 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 */
51void 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
63static const char *pager_search_list[] = { "pager", "more", "less", 0 };
64static const char *pager_dir_list[] = { "/usr/bin", "/bin", 0 };
65
66static 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
80FILE *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
100void 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 */
109ext2_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=='>')
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	return ino;
132}
133
134/*
135 * This routine returns 1 if the filesystem is not open, and prints an
136 * error message to that effect.
137 */
138int check_fs_open(char *name)
139{
140	if (!current_fs) {
141		com_err(name, 0, "Filesystem not open");
142		return 1;
143	}
144	return 0;
145}
146
147/*
148 * This routine returns 1 if a filesystem is open, and prints an
149 * error message to that effect.
150 */
151int check_fs_not_open(char *name)
152{
153	if (current_fs) {
154		com_err(name, 0,
155			"Filesystem %s is still open.  Close it first.\n",
156			current_fs->device_name);
157		return 1;
158	}
159	return 0;
160}
161
162/*
163 * This routine returns 1 if a filesystem is not opened read/write,
164 * and prints an error message to that effect.
165 */
166int check_fs_read_write(char *name)
167{
168	if (!(current_fs->flags & EXT2_FLAG_RW)) {
169		com_err(name, 0, "Filesystem opened read/only");
170		return 1;
171	}
172	return 0;
173}
174
175/*
176 * This routine returns 1 if a filesystem is doesn't have its inode
177 * and block bitmaps loaded, and prints an error message to that
178 * effect.
179 */
180int check_fs_bitmaps(char *name)
181{
182	if (!current_fs->block_map || !current_fs->inode_map) {
183		com_err(name, 0, "Filesystem bitmaps not loaded");
184		return 1;
185	}
186	return 0;
187}
188
189char *inode_time_to_string(__u32 xtime, __u32 xtime_extra)
190{
191	__s64 t = (__s32) xtime;
192
193	t += (__s64) (xtime_extra & EXT4_EPOCH_MASK) << 32;
194	return time_to_string(t);
195}
196
197/*
198 * This function takes a __s64 time value and converts it to a string,
199 * using ctime
200 */
201char *time_to_string(__s64 cl)
202{
203	static int	do_gmt = -1;
204	time_t		t = (time_t) cl;
205	const char	*tz;
206
207	if (do_gmt == -1) {
208		/* The diet libc doesn't respect the TZ environemnt variable */
209		tz = ss_safe_getenv("TZ");
210		if (!tz)
211			tz = "";
212		do_gmt = !strcmp(tz, "GMT") || !strcmp(tz, "GMT0");
213	}
214
215	return asctime((do_gmt) ? gmtime(&t) : localtime(&t));
216}
217
218/*
219 * Parse a string as a time.  Return ((time_t)-1) if the string
220 * doesn't appear to be a sane time.
221 */
222extern __s64 string_to_time(const char *arg)
223{
224	struct	tm	ts;
225	__s64		ret;
226	char *tmp;
227
228	if (strcmp(arg, "now") == 0) {
229		return time(0);
230	}
231	if (arg[0] == '@') {
232		/* interpret it as an integer */
233		arg++;
234	fallback:
235		ret = strtoll(arg, &tmp, 0);
236		if (*tmp)
237			return -1;
238		return ret;
239	}
240	memset(&ts, 0, sizeof(ts));
241#ifdef HAVE_STRPTIME
242	tmp = strptime(arg, "%Y%m%d%H%M%S", &ts);
243	if (tmp == NULL)
244		tmp = strptime(arg, "%Y%m%d%H%M", &ts);
245	if (tmp == NULL)
246		tmp = strptime(arg, "%Y%m%d", &ts);
247	if (tmp == NULL)
248		goto fallback;
249#else
250	sscanf(arg, "%4d%2d%2d%2d%2d%2d", &ts.tm_year, &ts.tm_mon,
251	       &ts.tm_mday, &ts.tm_hour, &ts.tm_min, &ts.tm_sec);
252	ts.tm_year -= 1900;
253	ts.tm_mon -= 1;
254	if (ts.tm_year < 0 || ts.tm_mon < 0 || ts.tm_mon > 11 ||
255	    ts.tm_mday <= 0 || ts.tm_mday > 31 || ts.tm_hour > 23 ||
256	    ts.tm_min > 59 || ts.tm_sec > 61)
257		goto fallback;
258#endif
259	ts.tm_isdst = -1;
260	/* strptime() may only update the specified fields, which does not
261	 * necessarily include ts.tm_yday (%j).  Calculate this if unset:
262	 *
263	 * Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
264	 * 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
265	 *
266	 * Start with 31 days per month.  Even months have only 30 days, but
267	 * reverse in August, subtract one day for those months. February has
268	 * only 28 days, not 30, subtract two days. Add day of month, minus
269	 * one, since day is not finished yet.  Leap years handled afterward. */
270	if (ts.tm_yday == 0)
271		ts.tm_yday = (ts.tm_mon * 31) -
272			((ts.tm_mon - (ts.tm_mon > 7)) / 2) -
273			2 * (ts.tm_mon > 1) + ts.tm_mday - 1;
274	ret = ts.tm_sec + ts.tm_min*60 + ts.tm_hour*3600 + ts.tm_yday*86400 +
275		((__s64) ts.tm_year-70)*31536000 +
276		(((__s64) ts.tm_year-69)/4)*86400 -
277		(((__s64) ts.tm_year-1)/100)*86400 +
278		(((__s64) ts.tm_year+299)/400)*86400;
279	return ret;
280}
281
282/*
283 * This function will convert a string to an unsigned long, printing
284 * an error message if it fails, and returning success or failure in err.
285 */
286unsigned long parse_ulong(const char *str, const char *cmd,
287			  const char *descr, int *err)
288{
289	char		*tmp;
290	unsigned long	ret;
291
292	ret = strtoul(str, &tmp, 0);
293	if (*tmp == 0) {
294		if (err)
295			*err = 0;
296		return ret;
297	}
298	com_err(cmd, 0, "Bad %s - %s", descr, str);
299	if (err)
300		*err = 1;
301	else
302		exit(1);
303	return 0;
304}
305
306/*
307 * This function will convert a string to an unsigned long long, printing
308 * an error message if it fails, and returning success or failure in err.
309 */
310unsigned long long parse_ulonglong(const char *str, const char *cmd,
311				   const char *descr, int *err)
312{
313	char			*tmp;
314	unsigned long long	ret;
315
316	ret = strtoull(str, &tmp, 0);
317	if (*tmp == 0) {
318		if (err)
319			*err = 0;
320		return ret;
321	}
322	com_err(cmd, 0, "Bad %s - %s", descr, str);
323	if (err)
324		*err = 1;
325	else
326		exit(1);
327	return 0;
328}
329
330/*
331 * This function will convert a string to a block number.  It returns
332 * 0 on success, 1 on failure.  On failure, it outputs either an optionally
333 * specified error message or a default.
334 */
335int strtoblk(const char *cmd, const char *str, const char *errmsg,
336	     blk64_t *ret)
337{
338	blk64_t	blk;
339	int	err;
340
341	if (errmsg == NULL)
342		blk = parse_ulonglong(str, cmd, "block number", &err);
343	else
344		blk = parse_ulonglong(str, cmd, errmsg, &err);
345	*ret = blk;
346	return err;
347}
348
349/*
350 * This is a common helper function used by the command processing
351 * routines
352 */
353int common_args_process(int argc, char *argv[], int min_argc, int max_argc,
354			const char *cmd, const char *usage, int flags)
355{
356	if (argc < min_argc || argc > max_argc) {
357		com_err(argv[0], 0, "Usage: %s %s", cmd, usage);
358		return 1;
359	}
360	if (flags & CHECK_FS_NOTOPEN) {
361		if (check_fs_not_open(argv[0]))
362			return 1;
363	} else {
364		if (check_fs_open(argv[0]))
365			return 1;
366	}
367	if ((flags & CHECK_FS_RW) && check_fs_read_write(argv[0]))
368		return 1;
369	if ((flags & CHECK_FS_BITMAPS) && check_fs_bitmaps(argv[0]))
370		return 1;
371	return 0;
372}
373
374/*
375 * This is a helper function used by do_stat, do_freei, do_seti, and
376 * do_testi, etc.  Basically, any command which takes a single
377 * argument which is a file/inode number specifier.
378 */
379int common_inode_args_process(int argc, char *argv[],
380			      ext2_ino_t *inode, int flags)
381{
382	if (common_args_process(argc, argv, 2, 2, argv[0], "<file>", flags))
383		return 1;
384
385	*inode = string_to_inode(argv[1]);
386	if (!*inode)
387		return 1;
388	return 0;
389}
390
391/*
392 * This is a helper function used by do_freeb, do_setb, and do_testb
393 */
394int common_block_args_process(int argc, char *argv[],
395			      blk64_t *block, blk64_t *count)
396{
397	int	err;
398
399	if (common_args_process(argc, argv, 2, 3, argv[0],
400				"<block> [count]", CHECK_FS_BITMAPS))
401		return 1;
402
403	if (strtoblk(argv[0], argv[1], NULL, block))
404		return 1;
405	if (*block == 0) {
406		com_err(argv[0], 0, "Invalid block number 0");
407		return 1;
408	}
409
410	if (argc > 2) {
411		err = strtoblk(argv[0], argv[2], "count", count);
412		if (err)
413			return 1;
414	}
415	return 0;
416}
417
418int debugfs_read_inode_full(ext2_ino_t ino, struct ext2_inode * inode,
419			const char *cmd, int bufsize)
420{
421	int retval;
422
423	retval = ext2fs_read_inode_full(current_fs, ino, inode, bufsize);
424	if (retval) {
425		com_err(cmd, retval, "while reading inode %u", ino);
426		return 1;
427	}
428	return 0;
429}
430
431int debugfs_read_inode(ext2_ino_t ino, struct ext2_inode * inode,
432			const char *cmd)
433{
434	int retval;
435
436	retval = ext2fs_read_inode(current_fs, ino, inode);
437	if (retval) {
438		com_err(cmd, retval, "while reading inode %u", ino);
439		return 1;
440	}
441	return 0;
442}
443
444int debugfs_write_inode_full(ext2_ino_t ino,
445			     struct ext2_inode *inode,
446			     const char *cmd,
447			     int bufsize)
448{
449	int retval;
450
451	retval = ext2fs_write_inode_full(current_fs, ino,
452					 inode, bufsize);
453	if (retval) {
454		com_err(cmd, retval, "while writing inode %u", ino);
455		return 1;
456	}
457	return 0;
458}
459
460int debugfs_write_inode(ext2_ino_t ino, struct ext2_inode * inode,
461			const char *cmd)
462{
463	int retval;
464
465	retval = ext2fs_write_inode(current_fs, ino, inode);
466	if (retval) {
467		com_err(cmd, retval, "while writing inode %u", ino);
468		return 1;
469	}
470	return 0;
471}
472
473int debugfs_write_new_inode(ext2_ino_t ino, struct ext2_inode * inode,
474			    const char *cmd)
475{
476	int retval;
477
478	retval = ext2fs_write_new_inode(current_fs, ino, inode);
479	if (retval) {
480		com_err(cmd, retval, "while creating inode %u", ino);
481		return 1;
482	}
483	return 0;
484}
485
486/*
487 * Given a mode, return the ext2 file type
488 */
489int ext2_file_type(unsigned int mode)
490{
491	if (LINUX_S_ISREG(mode))
492		return EXT2_FT_REG_FILE;
493
494	if (LINUX_S_ISDIR(mode))
495		return EXT2_FT_DIR;
496
497	if (LINUX_S_ISCHR(mode))
498		return EXT2_FT_CHRDEV;
499
500	if (LINUX_S_ISBLK(mode))
501		return EXT2_FT_BLKDEV;
502
503	if (LINUX_S_ISLNK(mode))
504		return EXT2_FT_SYMLINK;
505
506	if (LINUX_S_ISFIFO(mode))
507		return EXT2_FT_FIFO;
508
509	if (LINUX_S_ISSOCK(mode))
510		return EXT2_FT_SOCK;
511
512	return 0;
513}
514
515errcode_t read_list(char *str, blk64_t **list, size_t *len)
516{
517	blk64_t *lst = *list;
518	size_t ln = *len;
519	char *tok, *p = str;
520	errcode_t retval;
521
522	while ((tok = strtok(p, ","))) {
523		blk64_t *l;
524		blk64_t x, y;
525		char *e;
526
527		errno = 0;
528		y = x = strtoull(tok, &e, 0);
529		if (errno)
530			return errno;
531		if (*e == '-') {
532			y = strtoull(e + 1, NULL, 0);
533			if (errno)
534				return errno;
535		} else if (*e != 0) {
536			retval = EINVAL;
537			goto err;
538		}
539		if (y < x) {
540			retval = EINVAL;
541			goto err;
542		}
543		l = realloc(lst, sizeof(blk64_t) * (ln + y - x + 1));
544		if (l == NULL) {
545			retval = ENOMEM;
546			goto err;
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 0;
557err:
558	free(lst);
559	return retval;
560}
561