glusterfs
1
2#define _GNU_SOURCE3
4#include <stdio.h>5#include <stdlib.h>6#include <unistd.h>7#include <sys/types.h>8#include <sys/stat.h>9#include <fcntl.h>10#include <string.h>11#include <errno.h>12
13static char buffer[65536];14
15static int16parse_int(const char *text, size_t *value)17{
18char *ptr;19size_t val;20
21val = strtoul(text, &ptr, 0);22if (*ptr != 0) {23return 0;24}25
26*value = val;27
28return 1;29}
30
31static int32fill_area(int fd, off_t offset, size_t size)33{
34size_t len;35ssize_t res;36
37while (size > 0) {38len = sizeof(buffer);39if (len > size) {40len = size;41}42res = pwrite(fd, buffer, len, offset);43if (res < 0) {44fprintf(stderr, "pwrite(%d, %p, %lu, %lu) failed: %d\n", fd, buffer,45size, offset, errno);46return 0;47}48if (res != len) {49fprintf(stderr,50"pwrite(%d, %p, %lu, %lu) didn't wrote all "51"data: %lu/%lu\n",52fd, buffer, size, offset, res, len);53return 0;54}55offset += len;56size -= len;57}58
59return 1;60}
61
62static void63syntax(void)64{
65fprintf(stderr, "Syntax: seek create <path> <offset> <size> [...]\n");66fprintf(stderr, " seek scan <path> data|hole <offset>\n");67}
68
69static int70seek_create(const char *path, int argc, char *argv[])71{
72size_t off, size;73int fd;74int ret = 1;75
76fd = open(path, O_CREAT | O_TRUNC | O_RDWR, 0644);77if (fd < 0) {78fprintf(stderr, "Failed to create the file\n");79goto out;80}81
82while (argc > 0) {83if (!parse_int(argv[0], &off) || !parse_int(argv[1], &size)) {84syntax();85goto out_close;86}87if (!fill_area(fd, off, size)) {88goto out_close;89}90argv += 2;91argc -= 2;92}93
94ret = 0;95
96out_close:97close(fd);98out:99return ret;100}
101
102static int103seek_scan(const char *path, const char *type, const char *pos)104{
105size_t off, res;106int fd, whence;107int ret = 1;108
109if (strcmp(type, "data") == 0) {110whence = SEEK_DATA;111} else if (strcmp(type, "hole") == 0) {112whence = SEEK_HOLE;113} else {114syntax();115goto out;116}117
118if (!parse_int(pos, &off)) {119syntax();120goto out;121}122
123fd = open(path, O_RDWR);124if (fd < 0) {125fprintf(stderr, "Failed to open the file\n");126goto out;127}128
129res = lseek(fd, off, whence);130if (res == (off_t)-1) {131if (errno != ENXIO) {132fprintf(stderr, "seek(%d, %lu, %d) failed: %d\n", fd, off, whence,133errno);134goto out_close;135}136fprintf(stdout, "ENXIO\n");137} else {138fprintf(stdout, "%lu\n", res);139}140
141ret = 0;142
143out_close:144close(fd);145out:146return ret;147}
148
149int
150main(int argc, char *argv[])151{
152int ret = 1;153
154memset(buffer, 0x55, sizeof(buffer));155
156if (argc < 3) {157syntax();158goto out;159}160
161if (strcmp(argv[1], "create") == 0) {162if (((argc - 3) & 1) != 0) {163syntax();164goto out;165}166ret = seek_create(argv[2], argc - 3, argv + 3);167} else if (strcmp(argv[1], "scan") == 0) {168if (argc != 5) {169syntax();170goto out;171}172ret = seek_scan(argv[2], argv[3], argv[4]);173} else {174syntax();175goto out;176}177
178ret = 0;179
180out:181return ret;182}
183