e2label.c revision 18a1444b4f1e6a0948fd38fa0de382d86cfe04de
1/*
2 * e2label.c		- Print or change the volume label on an ext2 fs
3 *
4 * Written by Andries Brouwer (aeb@cwi.nl), 970714
5 *
6 * Copyright 1997, 1998 by Theodore Ts'o.
7 *
8 * %Begin-Header%
9 * This file may be redistributed under the terms of the GNU Public
10 * License.
11 * %End-Header%
12 */
13
14#include <stdio.h>
15#include <string.h>
16#include <fcntl.h>
17#include <ctype.h>
18#include <termios.h>
19#include <time.h>
20#ifdef HAVE_GETOPT_H
21#include <getopt.h>
22#else
23extern char *optarg;
24extern int optind;
25#endif
26#ifdef HAVE_UNISTD_H
27#include <unistd.h>
28#endif
29#ifdef HAVE_STDLIB_H
30#include <stdlib.h>
31#endif
32#ifdef HAVE_ERRNO_H
33#include <errno.h>
34#endif
35#include "nls-enable.h"
36
37#define EXT2_SUPER_MAGIC 0xEF53
38
39#define VOLNAMSZ 16
40
41struct ext2_super_block {
42	char  s_dummy0[56];
43	unsigned char  s_magic[2];
44	char  s_dummy1[62];
45	char  s_volume_name[VOLNAMSZ];
46	char  s_last_mounted[64];
47	char  s_dummy2[824];
48} sb;
49
50static int open_e2fs (char *dev, int mode)
51{
52	int fd;
53
54	fd = open(dev, mode);
55	if (fd < 0) {
56	     perror(dev);
57	     fprintf (stderr, _("e2label: cannot open %s\n"), dev);
58	     exit(1);
59	}
60	if (lseek(fd, 1024, SEEK_SET) != 1024) {
61	     perror(dev);
62	     fprintf (stderr, _("e2label: cannot seek to superblock\n"));
63	     exit(1);
64	}
65	if (read(fd, (char *) &sb, sizeof(sb)) != sizeof(sb)) {
66	     perror(dev);
67	     fprintf (stderr, _("e2label: error reading superblock\n"));
68	     exit(1);
69	}
70	if (sb.s_magic[0] + 256*sb.s_magic[1] != EXT2_SUPER_MAGIC) {
71	     fprintf (stderr, _("e2label: not an ext2 filesystem\n"));
72	     exit(1);
73	}
74
75	return fd;
76}
77
78static void print_label (char *dev)
79{
80	char label[VOLNAMSZ+1];
81
82	open_e2fs (dev, O_RDONLY);
83	strncpy(label, sb.s_volume_name, VOLNAMSZ);
84	label[VOLNAMSZ] = 0;
85	printf("%s\n", label);
86}
87
88static void change_label (char *dev, char *label)
89{
90	int fd;
91
92	fd = open_e2fs(dev, O_RDWR);
93	memset(sb.s_volume_name, 0, VOLNAMSZ);
94	strncpy(sb.s_volume_name, label, VOLNAMSZ);
95	if (strlen(label) > VOLNAMSZ)
96		fprintf(stderr, _("Warning: label too long, truncating.\n"));
97	if (lseek(fd, 1024, SEEK_SET) != 1024) {
98	     perror(dev);
99	     fprintf (stderr, _("e2label: cannot seek to superblock again\n"));
100	     exit(1);
101	}
102	if (write(fd, (char *) &sb, sizeof(sb)) != sizeof(sb)) {
103	     perror(dev);
104	     fprintf (stderr, _("e2label: error writing superblock\n"));
105	     exit(1);
106	}
107}
108
109int main (int argc, char ** argv)
110{
111	if (argc == 2)
112	     print_label(argv[1]);
113	else if (argc == 3)
114	     change_label(argv[1], argv[2]);
115	else {
116	     fprintf(stderr, _("Usage: e2label device [newlabel]\n"));
117	     exit(1);
118	}
119	return 0;
120}
121