aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

diskutil_linux.c (9492B)


      1 /* see LICENSE file for copyright and license details */
      2 #ifndef _DEFAULT_SOURCE
      3 #define _DEFAULT_SOURCE /* realpath, sync */
      4 #endif
      5 #include "../diskutil.h"
      6 #include "../util.h"
      7 
      8 #if defined(__linux__) && !defined(ARUU_FORCE_POSIX)
      9 #include <dirent.h>
     10 #include <errno.h>
     11 #include <fcntl.h>
     12 #include <limits.h>
     13 #include <linux/fs.h>
     14 #include <stdio.h>
     15 #include <stdlib.h>
     16 #include <string.h>
     17 #include <sys/ioctl.h>
     18 #include <sys/mount.h>
     19 #include <sys/stat.h>
     20 #include <unistd.h>
     21 
     22 #define SYS_BLOCK ARUU_LINUX_PATH_SYS "/block"
     23 
     24 void
     25 blockdev_sys_size(struct BlockDev *dev)
     26 {
     27   uint64_t size_bytes = 0;
     28   int      sec_size   = 0;
     29 
     30 #pragma GCC diagnostic push
     31 #pragma GCC diagnostic ignored "-Woverflow"
     32   if (ioctl(dev->fd, BLKGETSIZE64, &size_bytes) >= 0)
     33     dev->size = size_bytes;
     34   if (ioctl(dev->fd, BLKSSZGET, &sec_size) >= 0)
     35     dev->sec_size = sec_size;
     36 #pragma GCC diagnostic pop
     37 }
     38 
     39 /* sysfs exposes the backing path of each attached loop, including unmounted ones. */
     40 void
     41 blockdev_check_loop(const struct stat *target, const char *name)
     42 {
     43   struct dirent *de;
     44   struct stat    st;
     45   char           entry[PATH_MAX], *path = NULL;
     46   size_t         cap = 0;
     47   ssize_t        n;
     48   DIR           *dir;
     49   FILE          *f;
     50 
     51   dir = opendir(ARUU_LINUX_PATH_SYS_BLOCK);
     52   if (!dir) {
     53     if (errno == ENOENT)
     54       return;
     55     eprintf("%s:", ARUU_LINUX_PATH_SYS_BLOCK);
     56   }
     57   for (;;) {
     58     errno = 0;
     59     if (!(de = readdir(dir))) {
     60       if (errno)
     61         eprintf("%s:", ARUU_LINUX_PATH_SYS_BLOCK);
     62       break;
     63     }
     64     if (strncmp(de->d_name, "loop", 4))
     65       continue;
     66     if (snprintf(
     67             entry, sizeof entry, "%s/%s/loop/backing_file", ARUU_LINUX_PATH_SYS_BLOCK, de->d_name
     68         )
     69         >= (int)sizeof entry)
     70       eprintf("%s: loop path too long\n", name);
     71     if (!(f = fopen(entry, "r"))) {
     72       if (errno == ENOENT)
     73         continue;
     74       eprintf("%s:", entry);
     75     }
     76     n = getdelim(&path, &cap, '\0', f);
     77     if (n < 0 && !feof(f))
     78       eprintf("%s:", entry);
     79     fclose(f);
     80     if (n > 0 && path[n - 1] == '\n')
     81       path[n - 1] = '\0';
     82     if (n > 0 && stat(path, &st) == 0 && st.st_dev == target->st_dev && st.st_ino == target->st_ino)
     83       eprintf("%s: attached to a loop device\n", name);
     84   }
     85   free(path);
     86   closedir(dir);
     87 }
     88 
     89 void
     90 blockdev_sys_reread(struct BlockDev *dev)
     91 {
     92   struct stat st;
     93 
     94   // the kernel keeps the partition table it read when the disk appeared:
     95   // a table written here has no device nodes until it is asked to read
     96   // again, which fails harmlessly while a partition is in use
     97   if (fstat(dev->fd, &st) == 0 && S_ISBLK(st.st_mode))
     98     ioctl(dev->fd, BLKRRPART);
     99 }
    100 
    101 /* the model the disk reports, without the blanks firmware pads it with */
    102 static void
    103 disk_model(const char *name, char *out, size_t n)
    104 {
    105   char   path[128];
    106   FILE  *f;
    107   size_t len;
    108 
    109   out[0] = '\0';
    110   snprintf(path, sizeof(path), "/sys/block/%s/device/model", name);
    111   if (!(f = fopen(path, "r")))
    112     return;
    113   if (fgets(out, (int)n, f)) {
    114     out[strcspn(out, "\n")] = '\0';
    115     for (len = strlen(out); len > 0 && out[len - 1] == ' '; len--)
    116       out[len - 1] = '\0';
    117   }
    118   fclose(f);
    119 }
    120 
    121 /* a disk the kernel calls removable is a card reader or a disc drive;
    122  * a USB stick or an SD card often says it is not, so the bus it hangs
    123  * from counts as well */
    124 static int
    125 disk_removable(const char *name)
    126 {
    127   char  path[PATH_MAX];
    128   char  real[PATH_MAX];
    129   FILE *f;
    130   int   c = 0;
    131 
    132   snprintf(path, sizeof(path), SYS_BLOCK "/%s/removable", name);
    133   if ((f = fopen(path, "r"))) {
    134     c = fgetc(f);
    135     fclose(f);
    136   }
    137   if (c == '1')
    138     return 1;
    139   snprintf(path, sizeof(path), SYS_BLOCK "/%s", name);
    140   if (!realpath(path, real))
    141     return 0;
    142   return strstr(real, "/usb") || strstr(real, "/mmc_host/");
    143 }
    144 
    145 /* the mounts file writes a blank, a tab, a newline and a backslash in a
    146  * path as octal escapes, which are undone in place */
    147 static void
    148 unescape_mount(char *s)
    149 {
    150   char *w = s;
    151 
    152   for (; *s; s++) {
    153     if (s[0] == '\\' && s[1] >= '0' && s[1] <= '3' && s[2] >= '0' && s[2] <= '7' && s[3] >= '0'
    154         && s[3] <= '7') {
    155       *w++ = (char)((s[1] - '0') << 6 | (s[2] - '0') << 3 | (s[3] - '0'));
    156       s += 3;
    157     } else {
    158       *w++ = *s;
    159     }
    160   }
    161   *w = '\0';
    162 }
    163 
    164 struct BlockDevInfo *
    165 blockdev_get_list(void)
    166 {
    167   FILE                *fp;
    168   FILE                *mfile;
    169   char                 line[256];
    170   char                 mline[512];
    171   char                 devpath[128];
    172   char                 mnt[256];
    173   char                 fs[64];
    174   struct BlockDevInfo *head = NULL;
    175   struct BlockDevInfo *tail = NULL;
    176   struct BlockDevInfo *info;
    177   struct BlockDevInfo *curr;
    178   unsigned int         major, minor;
    179   unsigned long long   blocks;
    180   char                 name[64];
    181   int                  is_part;
    182 
    183   fp = fopen(ARUU_LINUX_PATH_PROC_PARTITIONS, "r");
    184   if (!fp)
    185     return NULL;
    186 
    187   while (fgets(line, sizeof(line), fp)) {
    188     if (sscanf(line, " %u %u %llu %63s", &major, &minor, &blocks, name) != 4)
    189       continue;
    190 
    191     info = ecalloc(1, sizeof(*info));
    192 
    193     strlcpy(info->name, name, sizeof(info->name));
    194     snprintf(info->path, sizeof(info->path), "%s/%s", ARUU_PATH_DEV, name);
    195     info->size  = blocks * 1024;
    196     info->major = major;
    197     info->minor = minor;
    198 
    199     /* search tree topology to link partition node under proper
    200      * target parent disk */
    201     is_part = 0;
    202     for (curr = head; curr; curr = curr->next) {
    203       size_t len = strlen(curr->name);
    204       if (strncmp(name, curr->name, len) == 0) {
    205         char c = name[len];
    206         if (curr->name[len - 1] >= '0' && curr->name[len - 1] <= '9') {
    207           if (c == 'p' && name[len + 1] >= '0' && name[len + 1] <= '9')
    208             is_part = 1;
    209         } else {
    210           if (c >= '0' && c <= '9')
    211             is_part = 1;
    212         }
    213         if (is_part) {
    214           strlcpy(info->type, "part", sizeof(info->type));
    215           info->removable        = curr->removable;
    216           struct BlockDevInfo *p = curr->parts;
    217           if (!p) {
    218             curr->parts = info;
    219           } else {
    220             while (p->next)
    221               p = p->next;
    222             p->next = info;
    223           }
    224           break;
    225         }
    226       }
    227     }
    228 
    229     if (!is_part) {
    230       strlcpy(info->type, "disk", sizeof(info->type));
    231       disk_model(info->name, info->model, sizeof(info->model));
    232       info->removable = disk_removable(info->name);
    233       if (!head) {
    234         head = info;
    235       } else {
    236         tail->next = info;
    237       }
    238       tail = info;
    239     }
    240   }
    241   fclose(fp);
    242 
    243   mfile = fopen(ARUU_LINUX_PATH_PROC_MOUNTS, "r");
    244   if (mfile) {
    245     while (fgets(mline, sizeof(mline), mfile)) {
    246       if (sscanf(mline, "%127s %255s %63s", devpath, mnt, fs) == 3) {
    247         unescape_mount(mnt);
    248         char  *devname = devpath;
    249         size_t dev_len = strlen(ARUU_PATH_DEV);
    250         if (strncmp(devpath, ARUU_PATH_DEV, dev_len) == 0 && devpath[dev_len] == '/')
    251           devname = devpath + dev_len + 1;
    252         struct BlockDevInfo *curr;
    253         for (curr = head; curr; curr = curr->next) {
    254           if (strcmp(curr->name, devname) == 0) {
    255             strlcpy(curr->mountpoint, mnt, sizeof(curr->mountpoint));
    256             strlcpy(curr->fstype, fs, sizeof(curr->fstype));
    257           }
    258           struct BlockDevInfo *part;
    259           for (part = curr->parts; part; part = part->next) {
    260             if (strcmp(part->name, devname) == 0) {
    261               strlcpy(part->mountpoint, mnt, sizeof(part->mountpoint));
    262               strlcpy(part->fstype, fs, sizeof(part->fstype));
    263             }
    264           }
    265         }
    266       }
    267     }
    268     fclose(mfile);
    269   }
    270 
    271   return head;
    272 }
    273 int
    274 blockdev_mount(const char *dev, const char *dir, const char *fstype, int flags, const char *data)
    275 {
    276   unsigned long mf = 0;
    277 
    278   if (flags & BLOCKDEV_RDONLY)
    279     mf |= MS_RDONLY;
    280   if (flags & BLOCKDEV_NOSUID)
    281     mf |= MS_NOSUID;
    282   if (flags & BLOCKDEV_NODEV)
    283     mf |= MS_NODEV;
    284   if (flags & BLOCKDEV_NOEXEC)
    285     mf |= MS_NOEXEC;
    286   return mount(dev, dir, fstype, mf, data);
    287 }
    288 
    289 int
    290 blockdev_unmount(const char *dir)
    291 {
    292   return umount(dir);
    293 }
    294 
    295 static int
    296 sys_write1(const char *path)
    297 {
    298   int fd, n;
    299 
    300   if ((fd = open(path, O_WRONLY)) < 0)
    301     return -1;
    302   n = write(fd, "1", 1);
    303   close(fd);
    304   return n == 1 ? 0 : -1;
    305 }
    306 
    307 /* the USB device a disk hangs from: the nearest folder above it in sysfs
    308  * that has an idVendor, as a device has and its interfaces do not */
    309 static int
    310 usb_parent(const char *real, char *out, size_t n)
    311 {
    312   char  path[PATH_MAX];
    313   char *slash;
    314 
    315   strlcpy(out, real, n);
    316   while ((slash = strrchr(out, '/')) && slash != out) {
    317     *slash = '\0';
    318     snprintf(path, sizeof(path), "%s/idVendor", out);
    319     if (access(path, F_OK) == 0)
    320       return 0;
    321   }
    322   return -1;
    323 }
    324 
    325 int
    326 blockdev_poweroff(const char *disk)
    327 {
    328   char path[PATH_MAX];
    329   char real[PATH_MAX];
    330   char usb[PATH_MAX];
    331   int  have_usb;
    332 
    333   if (strchr(disk, '/') || disk[0] == '.') {
    334     errno = EINVAL;
    335     return -1;
    336   }
    337   snprintf(path, sizeof(path), SYS_BLOCK "/%s", disk);
    338   if (!realpath(path, real))
    339     return -1;
    340   /* found before the disk is let go, which takes its sysfs folders away */
    341   have_usb = usb_parent(real, usb, sizeof(usb)) == 0;
    342   sync();
    343   /* the disk let go of: the kernel flushes its cache and forgets it */
    344   snprintf(path, sizeof(path), SYS_BLOCK "/%s/device/delete", disk);
    345   if (sys_write1(path) < 0 && !have_usb)
    346     return -1;
    347   if (!have_usb)
    348     return 0;
    349   /* the port cuts the unit's power, as a hub does for a device it removes */
    350   snprintf(path, sizeof(path), "%s/remove", usb);
    351   return sys_write1(path);
    352 }
    353 #endif