• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * util.c --- miscellaneous utilities
3  *
4  * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o.
5  *
6  * %Begin-Header%
7  * This file may be redistributed under the terms of the GNU Public
8  * License.
9  * %End-Header%
10  */
11 
12 #include "config.h"
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <unistd.h>
16 #include <string.h>
17 #include <ctype.h>
18 #ifdef __linux__
19 #include <sys/utsname.h>
20 #endif
21 
22 #ifdef HAVE_CONIO_H
23 #undef HAVE_TERMIOS_H
24 #include <conio.h>
25 #define read_a_char()	getch()
26 #else
27 #ifdef HAVE_TERMIOS_H
28 #include <termios.h>
29 #endif
30 #endif
31 
32 #ifdef HAVE_MALLOC_H
33 #include <malloc.h>
34 #endif
35 
36 #ifdef HAVE_ERRNO_H
37 #include <errno.h>
38 #endif
39 
40 #ifdef HAVE_SYS_SYSCTL_H
41 #include <sys/sysctl.h>
42 #endif
43 
44 #include "e2fsck.h"
45 
46 extern e2fsck_t e2fsck_global_ctx;   /* Try your very best not to use this! */
47 
48 #include <stdarg.h>
49 #include <time.h>
50 #include <sys/time.h>
51 #include <sys/resource.h>
52 
fatal_error(e2fsck_t ctx,const char * msg)53 void fatal_error(e2fsck_t ctx, const char *msg)
54 {
55 	ext2_filsys fs = ctx->fs;
56 	int exit_value = FSCK_ERROR;
57 
58 	if (msg)
59 		fprintf (stderr, "e2fsck: %s\n", msg);
60 	if (!fs)
61 		goto out;
62 	if (fs->io && fs->super) {
63 		ext2fs_mmp_stop(ctx->fs);
64 		if (ctx->fs->io->magic == EXT2_ET_MAGIC_IO_CHANNEL)
65 			io_channel_flush(ctx->fs->io);
66 		else
67 			log_err(ctx, "e2fsck: io manager magic bad!\n");
68 	}
69 	if (ext2fs_test_changed(fs)) {
70 		exit_value |= FSCK_NONDESTRUCT;
71 		log_out(ctx, _("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"),
72 			ctx->device_name);
73 		if (ctx->mount_flags & EXT2_MF_ISROOT)
74 			exit_value |= FSCK_REBOOT;
75 	}
76 	if (!ext2fs_test_valid(fs)) {
77 		log_out(ctx, _("\n%s: ********** WARNING: Filesystem still has "
78 			       "errors **********\n\n"), ctx->device_name);
79 		exit_value |= FSCK_UNCORRECTED;
80 		exit_value &= ~FSCK_NONDESTRUCT;
81 	}
82 out:
83 	ctx->flags |= E2F_FLAG_ABORT;
84 	if (ctx->flags & E2F_FLAG_SETJMP_OK)
85 		longjmp(ctx->abort_loc, 1);
86 	if (ctx->logf)
87 		fprintf(ctx->logf, "Exit status: %d\n", exit_value);
88 	exit(exit_value);
89 }
90 
log_out(e2fsck_t ctx,const char * fmt,...)91 void log_out(e2fsck_t ctx, const char *fmt, ...)
92 {
93 	va_list pvar;
94 
95 	va_start(pvar, fmt);
96 	vprintf(fmt, pvar);
97 	va_end(pvar);
98 	if (ctx->logf) {
99 		va_start(pvar, fmt);
100 		vfprintf(ctx->logf, fmt, pvar);
101 		va_end(pvar);
102 	}
103 }
104 
log_err(e2fsck_t ctx,const char * fmt,...)105 void log_err(e2fsck_t ctx, const char *fmt, ...)
106 {
107 	va_list pvar;
108 
109 	va_start(pvar, fmt);
110 	vfprintf(stderr, fmt, pvar);
111 	va_end(pvar);
112 	if (ctx->logf) {
113 		va_start(pvar, fmt);
114 		vfprintf(ctx->logf, fmt, pvar);
115 		va_end(pvar);
116 	}
117 }
118 
e2fsck_allocate_memory(e2fsck_t ctx,unsigned long size,const char * description)119 void *e2fsck_allocate_memory(e2fsck_t ctx, unsigned long size,
120 			     const char *description)
121 {
122 	void *ret;
123 	char buf[256];
124 
125 #ifdef DEBUG_ALLOCATE_MEMORY
126 	printf("Allocating %u bytes for %s...\n", size, description);
127 #endif
128 	if (ext2fs_get_memzero(size, &ret)) {
129 		sprintf(buf, "Can't allocate %u bytes for %s\n",
130 			size, description);
131 		fatal_error(ctx, buf);
132 	}
133 
134 	return ret;
135 }
136 
string_copy(e2fsck_t ctx EXT2FS_ATTR ((unused)),const char * str,int len)137 char *string_copy(e2fsck_t ctx EXT2FS_ATTR((unused)),
138 		  const char *str, int len)
139 {
140 	char	*ret;
141 
142 	if (!str)
143 		return NULL;
144 	if (!len)
145 		len = strlen(str);
146 	ret = malloc(len+1);
147 	if (ret) {
148 		strncpy(ret, str, len);
149 		ret[len] = 0;
150 	}
151 	return ret;
152 }
153 
154 #ifndef HAVE_STRNLEN
155 /*
156  * Incredibly, libc5 doesn't appear to have strnlen.  So we have to
157  * provide our own.
158  */
e2fsck_strnlen(const char * s,int count)159 int e2fsck_strnlen(const char * s, int count)
160 {
161 	const char *cp = s;
162 
163 	while (count-- && *cp)
164 		cp++;
165 	return cp - s;
166 }
167 #endif
168 
169 #ifndef HAVE_CONIO_H
read_a_char(void)170 static int read_a_char(void)
171 {
172 	char	c;
173 	int	r;
174 	int	fail = 0;
175 
176 	while(1) {
177 		if (e2fsck_global_ctx &&
178 		    (e2fsck_global_ctx->flags & E2F_FLAG_CANCEL)) {
179 			return 3;
180 		}
181 		r = read(0, &c, 1);
182 		if (r == 1)
183 			return c;
184 		if (fail++ > 100)
185 			break;
186 	}
187 	return EOF;
188 }
189 #endif
190 
ask_yn(e2fsck_t ctx,const char * string,int def)191 int ask_yn(e2fsck_t ctx, const char * string, int def)
192 {
193 	int		c;
194 	const char	*defstr;
195 	const char	*short_yes = _("yY");
196 	const char	*short_no = _("nN");
197 	const char	*short_yesall = _("aA");
198 	const char	*english_yes = "yY";
199 	const char	*english_no = "nN";
200 	const char	*english_yesall = "aA";
201 	const char	*yesall_prompt = _(" ('a' enables 'yes' to all) ");
202 	const char	*extra_prompt = "";
203 	static int	yes_answers;
204 
205 #ifdef HAVE_TERMIOS_H
206 	struct termios	termios, tmp;
207 
208 	if (tcgetattr (0, &termios) < 0)
209 		memset(&termios, 0, sizeof(termios));
210 	tmp = termios;
211 	tmp.c_lflag &= ~(ICANON | ECHO);
212 	tmp.c_cc[VMIN] = 1;
213 	tmp.c_cc[VTIME] = 0;
214 	tcsetattr (0, TCSANOW, &tmp);
215 #endif
216 
217 	if (def == 1)
218 		defstr = _(_("<y>"));
219 	else if (def == 0)
220 		defstr = _(_("<n>"));
221 	else
222 		defstr = _(" (y/n)");
223 	/*
224 	 * If the user presses 'y' more than 8 (but less than 12) times in
225 	 * succession without pressing anything else, display a hint about
226 	 * yes-to-all mode.
227 	 */
228 	if (yes_answers > 12)
229 		yes_answers = -1;
230 	else if (yes_answers > 8)
231 		extra_prompt = yesall_prompt;
232 	log_out(ctx, "%s%s%s? ", string, extra_prompt, defstr);
233 	while (1) {
234 		fflush (stdout);
235 		if ((c = read_a_char()) == EOF)
236 			break;
237 		if (c == 3) {
238 #ifdef HAVE_TERMIOS_H
239 			tcsetattr (0, TCSANOW, &termios);
240 #endif
241 			if (ctx->flags & E2F_FLAG_SETJMP_OK) {
242 				log_out(ctx, "\n");
243 				longjmp(e2fsck_global_ctx->abort_loc, 1);
244 			}
245 			log_out(ctx, "%s", _("cancelled!\n"));
246 			yes_answers = 0;
247 			return 0;
248 		}
249 		if (strchr(short_yes, (char) c)) {
250 		do_yes:
251 			def = 1;
252 			if (yes_answers >= 0)
253 				yes_answers++;
254 			break;
255 		} else if (strchr(short_no, (char) c)) {
256 		do_no:
257 			def = 0;
258 			yes_answers = -1;
259 			break;
260 		} else if (strchr(short_yesall, (char)c)) {
261 		do_all:
262 			def = 2;
263 			yes_answers = -1;
264 			ctx->options |= E2F_OPT_YES;
265 			break;
266 		} else if (strchr(english_yes, (char) c)) {
267 			goto do_yes;
268 		} else if (strchr(english_no, (char) c)) {
269 			goto do_no;
270 		} else if (strchr(english_yesall, (char) c)) {
271 			goto do_all;
272 		} else if ((c == 27 || c == ' ' || c == '\n') && (def != -1)) {
273 			yes_answers = -1;
274 			break;
275 		}
276 	}
277 	if (def == 2)
278 		log_out(ctx, "%s", _("yes to all\n"));
279 	else if (def)
280 		log_out(ctx, "%s", _("yes\n"));
281 	else
282 		log_out(ctx, "%s", _("no\n"));
283 #ifdef HAVE_TERMIOS_H
284 	tcsetattr (0, TCSANOW, &termios);
285 #endif
286 	return def;
287 }
288 
ask(e2fsck_t ctx,const char * string,int def)289 int ask (e2fsck_t ctx, const char * string, int def)
290 {
291 	if (ctx->options & E2F_OPT_NO) {
292 		log_out(ctx, _("%s? no\n\n"), string);
293 		return 0;
294 	}
295 	if (ctx->options & E2F_OPT_YES) {
296 		log_out(ctx, _("%s? yes\n\n"), string);
297 		return 1;
298 	}
299 	if (ctx->options & E2F_OPT_PREEN) {
300 		log_out(ctx, "%s? %s\n\n", string, def ? _("yes") : _("no"));
301 		return def;
302 	}
303 	return ask_yn(ctx, string, def);
304 }
305 
e2fsck_read_bitmaps(e2fsck_t ctx)306 void e2fsck_read_bitmaps(e2fsck_t ctx)
307 {
308 	ext2_filsys fs = ctx->fs;
309 	errcode_t	retval;
310 	const char	*old_op;
311 	unsigned int	save_type;
312 	int		flags;
313 
314 	if (ctx->invalid_bitmaps) {
315 		com_err(ctx->program_name, 0,
316 		    _("e2fsck_read_bitmaps: illegal bitmap block(s) for %s"),
317 			ctx->device_name);
318 		fatal_error(ctx, 0);
319 	}
320 
321 	old_op = ehandler_operation(_("reading inode and block bitmaps"));
322 	e2fsck_set_bitmap_type(fs, EXT2FS_BMAP64_RBTREE, "fs_bitmaps",
323 			       &save_type);
324 	flags = ctx->fs->flags;
325 	ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
326 	retval = ext2fs_read_bitmaps(fs);
327 	ctx->fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) |
328 			 (ctx->fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
329 	fs->default_bitmap_type = save_type;
330 	ehandler_operation(old_op);
331 	if (retval) {
332 		com_err(ctx->program_name, retval,
333 			_("while retrying to read bitmaps for %s"),
334 			ctx->device_name);
335 		fatal_error(ctx, 0);
336 	}
337 }
338 
e2fsck_write_bitmaps(e2fsck_t ctx)339 void e2fsck_write_bitmaps(e2fsck_t ctx)
340 {
341 	ext2_filsys fs = ctx->fs;
342 	errcode_t	retval;
343 	const char	*old_op;
344 
345 	old_op = ehandler_operation(_("writing block and inode bitmaps"));
346 	retval = ext2fs_write_bitmaps(fs);
347 	ehandler_operation(old_op);
348 	if (retval) {
349 		com_err(ctx->program_name, retval,
350 			_("while rewriting block and inode bitmaps for %s"),
351 			ctx->device_name);
352 		fatal_error(ctx, 0);
353 	}
354 }
355 
preenhalt(e2fsck_t ctx)356 void preenhalt(e2fsck_t ctx)
357 {
358 	ext2_filsys fs = ctx->fs;
359 
360 	if (!(ctx->options & E2F_OPT_PREEN))
361 		return;
362 	log_err(ctx, _("\n\n%s: UNEXPECTED INCONSISTENCY; "
363 		"RUN fsck MANUALLY.\n\t(i.e., without -a or -p options)\n"),
364 	       ctx->device_name);
365 	ctx->flags |= E2F_FLAG_EXITING;
366 	if (fs != NULL) {
367 		fs->super->s_state |= EXT2_ERROR_FS;
368 		ext2fs_mark_super_dirty(fs);
369 		ext2fs_close_free(&fs);
370 	}
371 	exit(FSCK_UNCORRECTED);
372 }
373 
374 #ifdef RESOURCE_TRACK
init_resource_track(struct resource_track * track,io_channel channel)375 void init_resource_track(struct resource_track *track, io_channel channel)
376 {
377 #ifdef HAVE_GETRUSAGE
378 	struct rusage r;
379 #endif
380 	io_stats io_start = 0;
381 
382 	track->brk_start = sbrk(0);
383 	gettimeofday(&track->time_start, 0);
384 #ifdef HAVE_GETRUSAGE
385 #ifdef sun
386 	memset(&r, 0, sizeof(struct rusage));
387 #endif
388 	getrusage(RUSAGE_SELF, &r);
389 	track->user_start = r.ru_utime;
390 	track->system_start = r.ru_stime;
391 #else
392 	track->user_start.tv_sec = track->user_start.tv_usec = 0;
393 	track->system_start.tv_sec = track->system_start.tv_usec = 0;
394 #endif
395 	track->bytes_read = 0;
396 	track->bytes_written = 0;
397 	if (channel && channel->manager && channel->manager->get_stats)
398 		channel->manager->get_stats(channel, &io_start);
399 	if (io_start) {
400 		track->bytes_read = io_start->bytes_read;
401 		track->bytes_written = io_start->bytes_written;
402 	}
403 }
404 
405 #ifdef __GNUC__
406 #define _INLINE_ __inline__
407 #else
408 #define _INLINE_
409 #endif
410 
timeval_subtract(struct timeval * tv1,struct timeval * tv2)411 static _INLINE_ float timeval_subtract(struct timeval *tv1,
412 				       struct timeval *tv2)
413 {
414 	return ((tv1->tv_sec - tv2->tv_sec) +
415 		((float) (tv1->tv_usec - tv2->tv_usec)) / 1000000);
416 }
417 
print_resource_track(e2fsck_t ctx,const char * desc,struct resource_track * track,io_channel channel)418 void print_resource_track(e2fsck_t ctx, const char *desc,
419 			  struct resource_track *track, io_channel channel)
420 {
421 #ifdef HAVE_GETRUSAGE
422 	struct rusage r;
423 #endif
424 	struct timeval time_end;
425 
426 	if ((desc && !(ctx->options & E2F_OPT_TIME2)) ||
427 	    (!desc && !(ctx->options & E2F_OPT_TIME)))
428 		return;
429 
430 	e2fsck_clear_progbar(ctx);
431 	gettimeofday(&time_end, 0);
432 
433 	if (desc)
434 		log_out(ctx, "%s: ", desc);
435 
436 #define kbytes(x)	(((unsigned long long)(x) + 1023) / 1024)
437 #ifdef HAVE_MALLINFO
438 	/* don't use mallinfo() if over 2GB used, since it returns "int" */
439 	if ((char *)sbrk(0) - (char *)track->brk_start < 2ULL << 30) {
440 		struct mallinfo	malloc_info = mallinfo();
441 
442 		log_out(ctx, _("Memory used: %lluk/%lluk (%lluk/%lluk), "),
443 			kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd),
444 			kbytes(malloc_info.uordblks),
445 			kbytes(malloc_info.fordblks));
446 	} else
447 #endif
448 	log_out(ctx, _("Memory used: %lluk, "),
449 		kbytes(((char *)sbrk(0)) - ((char *)track->brk_start)));
450 
451 #ifdef HAVE_GETRUSAGE
452 	getrusage(RUSAGE_SELF, &r);
453 
454 	log_out(ctx, _("time: %5.2f/%5.2f/%5.2f\n"),
455 		timeval_subtract(&time_end, &track->time_start),
456 		timeval_subtract(&r.ru_utime, &track->user_start),
457 		timeval_subtract(&r.ru_stime, &track->system_start));
458 #else
459 	log_out(ctx, _("elapsed time: %6.3f\n"),
460 		timeval_subtract(&time_end, &track->time_start));
461 #endif
462 #define mbytes(x)	(((x) + 1048575) / 1048576)
463 	if (channel && channel->manager && channel->manager->get_stats) {
464 		io_stats delta = 0;
465 		unsigned long long bytes_read = 0;
466 		unsigned long long bytes_written = 0;
467 
468 		if (desc)
469 			log_out(ctx, "%s: ", desc);
470 
471 		channel->manager->get_stats(channel, &delta);
472 		if (delta) {
473 			bytes_read = delta->bytes_read - track->bytes_read;
474 			bytes_written = delta->bytes_written -
475 				track->bytes_written;
476 		}
477 		log_out(ctx, "I/O read: %lluMB, write: %lluMB, "
478 			"rate: %.2fMB/s\n",
479 			mbytes(bytes_read), mbytes(bytes_written),
480 			(double)mbytes(bytes_read + bytes_written) /
481 			timeval_subtract(&time_end, &track->time_start));
482 	}
483 }
484 #endif /* RESOURCE_TRACK */
485 
e2fsck_read_inode(e2fsck_t ctx,unsigned long ino,struct ext2_inode * inode,const char * proc)486 void e2fsck_read_inode(e2fsck_t ctx, unsigned long ino,
487 			      struct ext2_inode * inode, const char *proc)
488 {
489 	errcode_t retval;
490 
491 	retval = ext2fs_read_inode(ctx->fs, ino, inode);
492 	if (retval) {
493 		com_err("ext2fs_read_inode", retval,
494 			_("while reading inode %lu in %s"), ino, proc);
495 		fatal_error(ctx, 0);
496 	}
497 }
498 
e2fsck_read_inode_full(e2fsck_t ctx,unsigned long ino,struct ext2_inode * inode,int bufsize,const char * proc)499 void e2fsck_read_inode_full(e2fsck_t ctx, unsigned long ino,
500 			    struct ext2_inode *inode, int bufsize,
501 			    const char *proc)
502 {
503 	errcode_t retval;
504 
505 	retval = ext2fs_read_inode_full(ctx->fs, ino, inode, bufsize);
506 	if (retval) {
507 		com_err("ext2fs_read_inode_full", retval,
508 			_("while reading inode %lu in %s"), ino, proc);
509 		fatal_error(ctx, 0);
510 	}
511 }
512 
e2fsck_write_inode_full(e2fsck_t ctx,unsigned long ino,struct ext2_inode * inode,int bufsize,const char * proc)513 void e2fsck_write_inode_full(e2fsck_t ctx, unsigned long ino,
514 			     struct ext2_inode * inode, int bufsize,
515 			     const char *proc)
516 {
517 	errcode_t retval;
518 
519 	retval = ext2fs_write_inode_full(ctx->fs, ino, inode, bufsize);
520 	if (retval) {
521 		com_err("ext2fs_write_inode", retval,
522 			_("while writing inode %lu in %s"), ino, proc);
523 		fatal_error(ctx, 0);
524 	}
525 }
526 
e2fsck_write_inode(e2fsck_t ctx,unsigned long ino,struct ext2_inode * inode,const char * proc)527 void e2fsck_write_inode(e2fsck_t ctx, unsigned long ino,
528 			struct ext2_inode * inode, const char *proc)
529 {
530 	errcode_t retval;
531 
532 	retval = ext2fs_write_inode(ctx->fs, ino, inode);
533 	if (retval) {
534 		com_err("ext2fs_write_inode", retval,
535 			_("while writing inode %lu in %s"), ino, proc);
536 		fatal_error(ctx, 0);
537 	}
538 }
539 
540 #ifdef MTRACE
mtrace_print(char * mesg)541 void mtrace_print(char *mesg)
542 {
543 	FILE	*malloc_get_mallstream();
544 	FILE	*f = malloc_get_mallstream();
545 
546 	if (f)
547 		fprintf(f, "============= %s\n", mesg);
548 }
549 #endif
550 
get_backup_sb(e2fsck_t ctx,ext2_filsys fs,const char * name,io_manager manager)551 blk64_t get_backup_sb(e2fsck_t ctx, ext2_filsys fs, const char *name,
552 		      io_manager manager)
553 {
554 	struct ext2_super_block *sb;
555 	io_channel		io = NULL;
556 	void			*buf = NULL;
557 	int			blocksize;
558 	blk64_t			superblock, ret_sb = 8193;
559 
560 	if (fs && fs->super) {
561 		ret_sb = (fs->super->s_blocks_per_group +
562 			  fs->super->s_first_data_block);
563 		if (ctx) {
564 			ctx->superblock = ret_sb;
565 			ctx->blocksize = fs->blocksize;
566 		}
567 		return ret_sb;
568 	}
569 
570 	if (ctx) {
571 		if (ctx->blocksize) {
572 			ret_sb = ctx->blocksize * 8;
573 			if (ctx->blocksize == 1024)
574 				ret_sb++;
575 			ctx->superblock = ret_sb;
576 			return ret_sb;
577 		}
578 		ctx->superblock = ret_sb;
579 		ctx->blocksize = 1024;
580 	}
581 
582 	if (!name || !manager)
583 		goto cleanup;
584 
585 	if (manager->open(name, 0, &io) != 0)
586 		goto cleanup;
587 
588 	if (ext2fs_get_mem(SUPERBLOCK_SIZE, &buf))
589 		goto cleanup;
590 	sb = (struct ext2_super_block *) buf;
591 
592 	for (blocksize = EXT2_MIN_BLOCK_SIZE;
593 	     blocksize <= EXT2_MAX_BLOCK_SIZE ; blocksize *= 2) {
594 		superblock = blocksize*8;
595 		if (blocksize == 1024)
596 			superblock++;
597 		io_channel_set_blksize(io, blocksize);
598 		if (io_channel_read_blk64(io, superblock,
599 					-SUPERBLOCK_SIZE, buf))
600 			continue;
601 #ifdef WORDS_BIGENDIAN
602 		if (sb->s_magic == ext2fs_swab16(EXT2_SUPER_MAGIC))
603 			ext2fs_swap_super(sb);
604 #endif
605 		if ((sb->s_magic == EXT2_SUPER_MAGIC) &&
606 		    (EXT2_BLOCK_SIZE(sb) == blocksize)) {
607 			ret_sb = superblock;
608 			if (ctx) {
609 				ctx->superblock = superblock;
610 				ctx->blocksize = blocksize;
611 			}
612 			break;
613 		}
614 	}
615 
616 cleanup:
617 	if (io)
618 		io_channel_close(io);
619 	if (buf)
620 		ext2fs_free_mem(&buf);
621 	return (ret_sb);
622 }
623 
624 /*
625  * Given a mode, return the ext2 file type
626  */
ext2_file_type(unsigned int mode)627 int ext2_file_type(unsigned int mode)
628 {
629 	if (LINUX_S_ISREG(mode))
630 		return EXT2_FT_REG_FILE;
631 
632 	if (LINUX_S_ISDIR(mode))
633 		return EXT2_FT_DIR;
634 
635 	if (LINUX_S_ISCHR(mode))
636 		return EXT2_FT_CHRDEV;
637 
638 	if (LINUX_S_ISBLK(mode))
639 		return EXT2_FT_BLKDEV;
640 
641 	if (LINUX_S_ISLNK(mode))
642 		return EXT2_FT_SYMLINK;
643 
644 	if (LINUX_S_ISFIFO(mode))
645 		return EXT2_FT_FIFO;
646 
647 	if (LINUX_S_ISSOCK(mode))
648 		return EXT2_FT_SOCK;
649 
650 	return 0;
651 }
652 
653 /*
654  * Check to see if a filesystem is in /proc/filesystems.
655  * Returns 1 if found, 0 if not
656  */
fs_proc_check(const char * fs_name)657 int fs_proc_check(const char *fs_name)
658 {
659 	FILE	*f;
660 	char	buf[80], *cp, *t;
661 
662 	f = fopen("/proc/filesystems", "r");
663 	if (!f)
664 		return (0);
665 	while (!feof(f)) {
666 		if (!fgets(buf, sizeof(buf), f))
667 			break;
668 		cp = buf;
669 		if (!isspace(*cp)) {
670 			while (*cp && !isspace(*cp))
671 				cp++;
672 		}
673 		while (*cp && isspace(*cp))
674 			cp++;
675 		if ((t = strchr(cp, '\n')) != NULL)
676 			*t = 0;
677 		if ((t = strchr(cp, '\t')) != NULL)
678 			*t = 0;
679 		if ((t = strchr(cp, ' ')) != NULL)
680 			*t = 0;
681 		if (!strcmp(fs_name, cp)) {
682 			fclose(f);
683 			return (1);
684 		}
685 	}
686 	fclose(f);
687 	return (0);
688 }
689 
690 /*
691  * Check to see if a filesystem is available as a module
692  * Returns 1 if found, 0 if not
693  */
check_for_modules(const char * fs_name)694 int check_for_modules(const char *fs_name)
695 {
696 #ifdef __linux__
697 	struct utsname	uts;
698 	FILE		*f;
699 	char		buf[1024], *cp, *t;
700 	int		i;
701 
702 	if (uname(&uts))
703 		return (0);
704 	snprintf(buf, sizeof(buf), "/lib/modules/%s/modules.dep", uts.release);
705 
706 	f = fopen(buf, "r");
707 	if (!f)
708 		return (0);
709 	while (!feof(f)) {
710 		if (!fgets(buf, sizeof(buf), f))
711 			break;
712 		if ((cp = strchr(buf, ':')) != NULL)
713 			*cp = 0;
714 		else
715 			continue;
716 		if ((cp = strrchr(buf, '/')) != NULL)
717 			cp++;
718 		else
719 			cp = buf;
720 		i = strlen(cp);
721 		if (i > 3) {
722 			t = cp + i - 3;
723 			if (!strcmp(t, ".ko"))
724 				*t = 0;
725 		}
726 		if (!strcmp(cp, fs_name)) {
727 			fclose(f);
728 			return (1);
729 		}
730 	}
731 	fclose(f);
732 #endif /* __linux__ */
733 	return (0);
734 }
735 
736 /*
737  * Helper function that does the right thing if write returns a
738  * partial write, or an EAGAIN/EINTR error.
739  */
write_all(int fd,char * buf,size_t count)740 int write_all(int fd, char *buf, size_t count)
741 {
742 	ssize_t ret;
743 	int c = 0;
744 
745 	while (count > 0) {
746 		ret = write(fd, buf, count);
747 		if (ret < 0) {
748 			if ((errno == EAGAIN) || (errno == EINTR))
749 				continue;
750 			return -1;
751 		}
752 		count -= ret;
753 		buf += ret;
754 		c += ret;
755 	}
756 	return c;
757 }
758 
dump_mmp_msg(struct mmp_struct * mmp,const char * fmt,...)759 void dump_mmp_msg(struct mmp_struct *mmp, const char *fmt, ...)
760 {
761 	va_list pvar;
762 
763 	if (fmt) {
764 		printf("MMP check failed: ");
765 		va_start(pvar, fmt);
766 		vprintf(fmt, pvar);
767 		va_end(pvar);
768 	}
769 	if (mmp) {
770 		time_t t = mmp->mmp_time;
771 
772 		printf("MMP_block:\n");
773 		printf("    mmp_magic: 0x%x\n", mmp->mmp_magic);
774 		printf("    mmp_check_interval: %d\n",
775 		       mmp->mmp_check_interval);
776 		printf("    mmp_sequence: %08x\n", mmp->mmp_seq);
777 		printf("    mmp_update_date: %s", ctime(&t));
778 		printf("    mmp_update_time: %lld\n", mmp->mmp_time);
779 		printf("    mmp_node_name: %.*s\n",
780 		       EXT2_LEN_STR(mmp->mmp_nodename));
781 		printf("    mmp_device_name: %.*s\n",
782 		       EXT2_LEN_STR(mmp->mmp_bdevname));
783 	}
784 }
785 
e2fsck_mmp_update(ext2_filsys fs)786 errcode_t e2fsck_mmp_update(ext2_filsys fs)
787 {
788 	errcode_t retval;
789 
790 	retval = ext2fs_mmp_update(fs);
791 	if (retval == EXT2_ET_MMP_CHANGE_ABORT)
792 		dump_mmp_msg(fs->mmp_cmp,
793 			     _("UNEXPECTED INCONSISTENCY: the filesystem is "
794 			       "being modified while fsck is running.\n"));
795 
796 	return retval;
797 }
798 
e2fsck_set_bitmap_type(ext2_filsys fs,unsigned int default_type,const char * profile_name,unsigned int * old_type)799 void e2fsck_set_bitmap_type(ext2_filsys fs, unsigned int default_type,
800 			    const char *profile_name, unsigned int *old_type)
801 {
802 	unsigned type;
803 	e2fsck_t ctx = (e2fsck_t) fs->priv_data;
804 
805 	if (old_type)
806 		*old_type = fs->default_bitmap_type;
807 	profile_get_uint(ctx->profile, "bitmaps", profile_name, 0,
808 			 default_type, &type);
809 	profile_get_uint(ctx->profile, "bitmaps", "all", 0, type, &type);
810 	fs->default_bitmap_type = type ? type : default_type;
811 }
812 
e2fsck_allocate_inode_bitmap(ext2_filsys fs,const char * descr,int deftype,const char * name,ext2fs_inode_bitmap * ret)813 errcode_t e2fsck_allocate_inode_bitmap(ext2_filsys fs, const char *descr,
814 				       int deftype,
815 				       const char *name,
816 				       ext2fs_inode_bitmap *ret)
817 {
818 	errcode_t	retval;
819 	unsigned int	save_type;
820 
821 	e2fsck_set_bitmap_type(fs, deftype, name, &save_type);
822 	retval = ext2fs_allocate_inode_bitmap(fs, descr, ret);
823 	fs->default_bitmap_type = save_type;
824 	return retval;
825 }
826 
e2fsck_allocate_block_bitmap(ext2_filsys fs,const char * descr,int deftype,const char * name,ext2fs_block_bitmap * ret)827 errcode_t e2fsck_allocate_block_bitmap(ext2_filsys fs, const char *descr,
828 				       int deftype,
829 				       const char *name,
830 				       ext2fs_block_bitmap *ret)
831 {
832 	errcode_t	retval;
833 	unsigned int	save_type;
834 
835 	e2fsck_set_bitmap_type(fs, deftype, name, &save_type);
836 	retval = ext2fs_allocate_block_bitmap(fs, descr, ret);
837 	fs->default_bitmap_type = save_type;
838 	return retval;
839 }
840 
e2fsck_allocate_subcluster_bitmap(ext2_filsys fs,const char * descr,int deftype,const char * name,ext2fs_block_bitmap * ret)841 errcode_t e2fsck_allocate_subcluster_bitmap(ext2_filsys fs, const char *descr,
842 					    int deftype,
843 					    const char *name,
844 					    ext2fs_block_bitmap *ret)
845 {
846 	errcode_t	retval;
847 	unsigned int	save_type;
848 
849 	e2fsck_set_bitmap_type(fs, deftype, name, &save_type);
850 	retval = ext2fs_allocate_subcluster_bitmap(fs, descr, ret);
851 	fs->default_bitmap_type = save_type;
852 	return retval;
853 }
854 
855 /* Return memory size in bytes */
get_memory_size(void)856 unsigned long long get_memory_size(void)
857 {
858 #if defined(_SC_PHYS_PAGES)
859 # if defined(_SC_PAGESIZE)
860 	return (unsigned long long)sysconf(_SC_PHYS_PAGES) *
861 	       (unsigned long long)sysconf(_SC_PAGESIZE);
862 # elif defined(_SC_PAGE_SIZE)
863 	return (unsigned long long)sysconf(_SC_PHYS_PAGES) *
864 	       (unsigned long long)sysconf(_SC_PAGE_SIZE);
865 # endif
866 #elif defined(CTL_HW)
867 # if (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))
868 #  define CTL_HW_INT64
869 # elif (defined(HW_PHYSMEM) || defined(HW_REALMEM))
870 #  define CTL_HW_UINT
871 # endif
872 	int mib[2];
873 
874 	mib[0] = CTL_HW;
875 # if defined(HW_MEMSIZE)
876 	mib[1] = HW_MEMSIZE;
877 # elif defined(HW_PHYSMEM64)
878 	mib[1] = HW_PHYSMEM64;
879 # elif defined(HW_REALMEM)
880 	mib[1] = HW_REALMEM;
881 # elif defined(HW_PYSMEM)
882 	mib[1] = HW_PHYSMEM;
883 # endif
884 # if defined(CTL_HW_INT64)
885 	unsigned long long size = 0;
886 # elif defined(CTL_HW_UINT)
887 	unsigned int size = 0;
888 # endif
889 # if defined(CTL_HW_INT64) || defined(CTL_HW_UINT)
890 	size_t len = sizeof(size);
891 
892 	if (sysctl(mib, 2, &size, &len, NULL, 0) == 0)
893 		return (unsigned long long)size;
894 # endif
895 	return 0;
896 #else
897 # warning "Don't know how to detect memory on your platform?"
898 	return 0;
899 #endif
900 }
901