morpheus-base

morpheus base system
git clone git://git.2f30.org/morpheus-base.git
Log | Files | Refs

swaplabel.c (1929B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <sys/types.h>
      3 
      4 #include <fcntl.h>
      5 #include <stdio.h>
      6 #include <stdlib.h>
      7 #include <string.h>
      8 #include <unistd.h>
      9 
     10 #include "util.h"
     11 
     12 #define SWAP_MAGIC1 "SWAPSPACE2"
     13 #define SWAP_MAGIC2 "SWAP-SPACE"
     14 #define SWAP_MAGIC_LENGTH (10)
     15 #define SWAP_MAGIC_OFFSET (sysconf(_SC_PAGESIZE) - SWAP_MAGIC_LENGTH)
     16 #define SWAP_LABEL_LENGTH (16)
     17 #define SWAP_LABEL_OFFSET (1024 + 4 + 4 + 4 + 16)
     18 
     19 static void
     20 usage(void)
     21 {
     22 	eprintf("usage: %s [-L label] device\n", argv0);
     23 }
     24 
     25 int
     26 main(int argc, char *argv[])
     27 {
     28 	int setlabel = 0;
     29 	int fd;
     30 	char magic[SWAP_MAGIC_LENGTH];
     31 	char *label;
     32 	char *device;
     33 	int i;
     34 
     35 	ARGBEGIN {
     36 	case 'L':
     37 		setlabel = 1;
     38 		label = EARGF(usage());
     39 		break;
     40 	default:
     41 		usage();
     42 	} ARGEND;
     43 
     44 	if (argc < 1)
     45 		usage();
     46 	device = argv[0];
     47 
     48 	fd = open(device, O_RDWR);
     49 	if (fd < 0)
     50 		eprintf("open %s:", device);
     51 
     52 	if (lseek(fd, SWAP_MAGIC_OFFSET, SEEK_SET) != SWAP_MAGIC_OFFSET)
     53 		eprintf("failed seeking to magic position:");
     54 	if (read(fd, magic, SWAP_MAGIC_LENGTH) != SWAP_MAGIC_LENGTH)
     55 		eprintf("reading magic failed:");
     56 	if (memcmp(magic, SWAP_MAGIC1, 10) && memcmp(magic, SWAP_MAGIC2, 10))
     57 		eprintf("%s: is not a swap partition\n", device);
     58 	if (lseek(fd, SWAP_LABEL_OFFSET, SEEK_SET) != SWAP_LABEL_OFFSET)
     59 		eprintf("failed seeking to label position:");
     60 
     61 	if (!setlabel) {
     62 		label = emalloc(SWAP_LABEL_LENGTH);
     63 		if (read(fd, label, SWAP_LABEL_LENGTH) != SWAP_LABEL_LENGTH)
     64 			eprintf("reading label failed:");
     65 		for (i = 0; i < SWAP_LABEL_LENGTH && label[i] != '\0'; i++)
     66 			if (i == (SWAP_LABEL_LENGTH - 1) && label[i] != '\0')
     67 				eprintf("invalid label\n");
     68 		printf("label: %s\n", label);
     69 		free(label);
     70 	} else {
     71 		if (strlen(label) + 1 > SWAP_LABEL_LENGTH)
     72 			eprintf("label too long\n");
     73 		if (write(fd, label, strlen(label) + 1) != (ssize_t)strlen(label) + 1)
     74 			eprintf("writing label failed:");
     75 	}
     76 
     77 	fsync(fd);
     78 	close(fd);
     79 	return 0;
     80 }