#ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include "hdaps.h" /* The most space we expect to need when reading in a file using these hdaps functions. To exceed 32 bytes worth of content in unload_heads you'd have to throw your laptop hard as a motherfucker. */ #define MAX_FILE_CONTENTS_SIZE 32 /* Where the block device names are located. */ #define SYSFS_BLOCK_DEVICE_DIR "/sys/block/" static int hdaps_device_exists(const char* device) { /* Determine whether or not a device (file) exists and has an unload_heads entry in sysfs. */ char path[FILENAME_MAX]; snprintf(path, FILENAME_MAX, UNLOAD_HEADS_FMT, device); return (access(path, F_OK) == 0); } int get_hdaps_device_list(char list[MAX_HDAPS_DEVICES][FILENAME_MAX]) { int list_idx = 0; DIR *dp; struct dirent *ep; dp = opendir(SYSFS_BLOCK_DEVICE_DIR); if (dp != NULL) { while ((ep = readdir(dp)) && list_idx < MAX_HDAPS_DEVICES) { /* This next test covers "." and ".." too. */ if (hdaps_device_exists(ep->d_name)) { strncpy(list[list_idx], ep->d_name, FILENAME_MAX); list_idx++; } } (void)closedir(dp); /* Explicitly ignore this. */ } return list_idx; } int slurp_file(const char* filename, char* buf, int max_bytes) { /* This function just reads the contents of filename * into buf. It is slightly stolen from the hdapsd project. */ /* Return an error value by default. */ int ret = HDAPS_ERROR; int fd = open(filename, O_RDONLY); if (filename == NULL || buf == NULL) { return ret; } if (fd < 0) { fprintf(stderr, "open(%s): %s\n", filename, strerror(errno)); return fd; } ret = read(fd, buf, max_bytes-1); if (ret < 0) { fprintf(stderr, "read(%s): %s\n", filename, strerror(errno)); } else { buf[ret] = 0; /* Null-terminate buf. */ } if (close(fd)) { fprintf(stderr, "close(%s): %s\n", filename, strerror(errno)); } return ret; } int parse_int_from_file(const char* filename) { /* Read an integer from a file. We expect the file to contain an integer (although in string form). */ char buf[MAX_FILE_CONTENTS_SIZE]; int ret = slurp_file(filename, buf, sizeof(buf)); if (ret < 0) { /* Why did we read fewer than 0 bytes? */ return ret; } else { /* If we read more than 0 bytes, hopefully we can count on atoi to succeed. */ return atoi(buf); } }