]> gitweb.michael.orlitzky.com - xfce4-hdaps.git/blob - panel-plugin/hdaps.c
Initial commit.
[xfce4-hdaps.git] / panel-plugin / hdaps.c
1 #ifdef HAVE_CONFIG_H
2 #include <config.h>
3 #endif
4
5 #include <dirent.h>
6 #include <sys/types.h>
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include "hdaps.h"
12
13 /* The most space we expect to need when reading in
14 a file using these hdaps functions. To exceed 32
15 bytes worth of content in unload_heads you'd have
16 to throw your laptop hard as a motherfucker. */
17 #define MAX_FILE_CONTENTS_SIZE 32
18
19 /* Where the block device names are located. */
20 #define SYSFS_BLOCK_DEVICE_DIR "/sys/block/"
21
22
23 static int hdaps_device_exists(const char* device) {
24 /* Determine whether or not a device (file) exists and has an
25 unload_heads entry in sysfs. */
26 char path[FILENAME_MAX];
27 snprintf(path, FILENAME_MAX, UNLOAD_HEADS_FMT, device);
28 return (access(path, F_OK) == 0);
29 }
30
31
32 int get_hdaps_device_list(char list[MAX_HDAPS_DEVICES][FILENAME_MAX]) {
33 int list_idx = 0;
34 DIR *dp;
35 struct dirent *ep;
36
37 dp = opendir(SYSFS_BLOCK_DEVICE_DIR);
38
39 if (dp != NULL) {
40 while ((ep = readdir(dp)) && list_idx < MAX_HDAPS_DEVICES) {
41 /* This next test covers "." and ".." too. */
42 if (hdaps_device_exists(ep->d_name)) {
43 strncpy(list[list_idx], ep->d_name, FILENAME_MAX);
44 list_idx++;
45 }
46 }
47
48 (void)closedir(dp); /* Explicitly ignore this. */
49 }
50
51 return list_idx;
52 }
53
54
55 int slurp_file(const char* filename, char* buf, int max_bytes) {
56 /* This function just reads the contents of filename
57 * into buf. It is slightly stolen from the hdapsd project.
58 */
59
60 /* Return an error value by default. */
61 int ret = HDAPS_ERROR;
62 int fd = open(filename, O_RDONLY);
63
64 if (filename == NULL || buf == NULL) {
65 return ret;
66 }
67
68 if (fd < 0) {
69 fprintf(stderr, "open(%s): %s\n", filename, strerror(errno));
70 return fd;
71 }
72
73 ret = read(fd, buf, max_bytes-1);
74
75 if (ret < 0) {
76 fprintf(stderr, "read(%s): %s\n", filename, strerror(errno));
77 }
78 else {
79 buf[ret] = 0; /* Null-terminate buf. */
80 }
81
82 if (close(fd)) {
83 fprintf(stderr, "close(%s): %s\n", filename, strerror(errno));
84 }
85
86 return ret;
87 }
88
89
90
91
92 int parse_int_from_file(const char* filename) {
93 /* Read an integer from a file. We expect the file
94 to contain an integer (although in string form). */
95
96 char buf[MAX_FILE_CONTENTS_SIZE];
97 int ret = slurp_file(filename, buf, sizeof(buf));
98
99 if (ret < 0) {
100 /* Why did we read fewer than 0 bytes? */
101 return ret;
102 }
103 else {
104 /* If we read more than 0 bytes, hopefully we can
105 count on atoi to succeed. */
106 return atoi(buf);
107 }
108 }