inotify_c.c 2.45 KB
Newer Older
Camil Staps's avatar
Camil Staps committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>

#include "Clean.h"

char* clstocs(CleanString* cs) {
    char* s = calloc(CleanStringLength(cs) + 1, 1);
    uint8_t i;
    for (i = 0; i < CleanStringLength(cs); i++)
        s[i] = CleanStringCharacters(cs)[i];
    s[i] = 0;
    return s;
}

static struct {int length; char chars[1]; } empty_string = {0,""};

int clean_errno(int ignored) {
	return errno;
}

int clean_inotify_init(int ignored) {
	int fd;
	fd = inotify_init();
	if (fd < 0)
		return 0;
	fcntl(fd, IN_NONBLOCK);
	return fd;
}

void clean_inotify_add_watch(int fd, CleanString* fname_, int mask, int *re_watch, int *re_fd) {
	char* fname = clstocs(fname_);
	*re_watch = inotify_add_watch(fd, fname, mask);
	free(fname);
	*re_fd = fd;
}

void clean_inotify_rm_watch(int fd, int watch, int *re_code, int *re_fd) {
	*re_fd = fd;
	*re_code = inotify_rm_watch(fd, watch);
}

void clean_poll(int fd, int *re_nrevents, int *re_fd) {
	struct pollfd pfd = {fd, POLLIN, 0};
	*re_nrevents = poll(&pfd, 1, -1);
	*re_fd = fd;
}

static CleanStringVariable(wds_string, 1024);
static CleanStringVariable(masks_string, 1024);

void clean_inotify_check(int fd,
		int *re_ok, CleanString* re_wds, CleanString* re_masks, int *re_fd) {
	char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event))));
	const struct inotify_event *ev;
	ssize_t len;
	char *ptr;

	struct pollfd pfd = {fd, POLLIN, 0};
	int poll_n;

	char *wds_ptr = CleanStringCharacters(wds_string);
	char *masks_ptr = CleanStringCharacters(masks_string);
	CleanStringLength(wds_string) = 0;
	CleanStringLength(masks_string) = 0;

	*re_ok = 0;
	*re_fd = fd;

	*re_wds = (CleanString) &empty_string;
	*re_masks = (CleanString) &empty_string;

	for (;;) {
		poll_n = poll(&pfd, 1, 50);
		if (poll_n < 0) {
			return;
		} else if (poll_n == 0) {
			break;
		}

		len = read(fd, buf, sizeof buf);
		if (len == -1 && errno != EAGAIN) {
			return;
		}
		if (len <= 0) {
			break;
		}

		for (ptr = buf; ptr < buf + len;
				ptr += sizeof(struct inotify_event) + ev->len) {
			ev = (const struct inotify_event*) ptr;

			memcpy(masks_ptr, &ev->mask, 4);
			masks_ptr += 4;
			CleanStringLength(masks_string) += 4;

			memcpy(wds_ptr, &ev->wd, sizeof(int));
			wds_ptr += sizeof(int);
			CleanStringLength(wds_string) += sizeof(int);
		}
	}

	*re_wds = (CleanString) wds_string;
	*re_masks = (CleanString) masks_string;

	*re_ok = 1;
}