Source

python-inotify / inotify / _inotify.c

  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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
/*
 * _inotify.c - Python extension interfacing to the Linux inotify subsystem
 *
 * Copyright 2006 Bryan O'Sullivan <bos@serpentine.com>
 * Copyright 2012-2013 Jan Kanis <jan.code@jankanis.nl>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of version 2.1 of the GNU Lesser General
 * Public License, incorporated herein by reference.
 * 
 * Additionally, code written by Jan Kanis may also be redistributed and/or 
 * modified under the terms of any version of the GNU Lesser General Public 
 * License greater than 2.1. 
 */

#include <Python.h>
#include <alloca.h>
#include <sys/inotify.h>
#include <stdint.h>
#include <sys/ioctl.h>
#include <unistd.h>

/* for older pythons */
#ifndef Py_TYPE
	#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif

/* for Python 2.5 and below */
#ifndef PyVarObject_HEAD_INIT
	#define PyVarObject_HEAD_INIT(type, size) \
		PyObject_HEAD_INIT(type) size,
#endif


static PyObject *init(PyObject *self, PyObject *args)
{
	PyObject *ret = NULL;
	int fd = -1;

	 if (!PyArg_ParseTuple(args, ":init"))
		goto bail;

	Py_BEGIN_ALLOW_THREADS
	fd = inotify_init();
	Py_END_ALLOW_THREADS

	if (fd == -1) {
		PyErr_SetFromErrno(PyExc_OSError);
		goto bail;
	}

	ret = PyLong_FromLong(fd);
	if (ret == NULL)
		goto bail;

	goto done;

bail:
	if (fd != -1)
		close(fd);

	Py_CLEAR(ret);

done:
	return ret;
}

PyDoc_STRVAR(
	init_doc,
	"init() -> fd\n"
	"\n"
	"Initialise an inotify instance.\n"
	"Return a file descriptor associated with a new inotify event queue.");

static PyObject *add_watch(PyObject *self, PyObject *args)
{
	PyObject *ret = NULL;
	uint32_t mask;
	int wd = -1;
	char *path;
	int fd;

	if (!PyArg_ParseTuple(args, "isI:add_watch", &fd, &path, &mask))
		goto bail;

	Py_BEGIN_ALLOW_THREADS
	wd = inotify_add_watch(fd, path, mask);
	Py_END_ALLOW_THREADS

	if (wd == -1) {
		PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
		goto bail;
	}

	ret = PyLong_FromLong(wd);
	if (ret == NULL)
		goto bail;

	goto done;

bail:
	if (wd != -1)
		inotify_rm_watch(fd, wd);

	Py_CLEAR(ret);

done:
	return ret;
}

PyDoc_STRVAR(
	add_watch_doc,
	"add_watch(fd, path, mask) -> wd\n"
	"\n"
	"Add a watch to an inotify instance, or modify an existing watch.\n"
	"\n"
	"        fd: file descriptor returned by init()\n"
	"        path: path to watch\n"
	"        mask: mask of events to watch for\n"
	"\n"
	"Return a unique numeric watch descriptor for the inotify instance\n"
	"mapped by the file descriptor.");

static PyObject *remove_watch(PyObject *self, PyObject *args)
{
	uint32_t wd;
	int fd;
	int r;

	if (!PyArg_ParseTuple(args, "iI:remove_watch", &fd, &wd))
		goto bail;

	Py_BEGIN_ALLOW_THREADS
	r = inotify_rm_watch(fd, wd);
	Py_END_ALLOW_THREADS

	if (r == -1) {
		PyErr_SetFromErrno(PyExc_OSError);
		goto bail;
	}

	Py_RETURN_NONE;

bail:
	return NULL;
}

PyDoc_STRVAR(
	remove_watch_doc,
	"remove_watch(fd, wd)\n"
	"\n"
	"        fd: file descriptor returned by init()\n"
	"        wd: watch descriptor returned by add_watch()\n"
	"\n"
	"Remove a watch associated with the watch descriptor wd from the\n"
	"inotify instance associated with the file descriptor fd.\n"
	"\n"
	"Removing a watch causes an IN_IGNORED event to be generated for this\n"
	"watch descriptor.");

#define bit_name(x) {x, #x}

static struct {
	int bit;
	const char *name;
	PyObject *pyname;
} bit_names[] = {
	bit_name(IN_ACCESS),
	bit_name(IN_MODIFY),
	bit_name(IN_ATTRIB),
	bit_name(IN_CLOSE_WRITE),
	bit_name(IN_CLOSE_NOWRITE),
	bit_name(IN_OPEN),
	bit_name(IN_MOVED_FROM),
	bit_name(IN_MOVED_TO),
	bit_name(IN_CREATE),
	bit_name(IN_DELETE),
	bit_name(IN_DELETE_SELF),
	bit_name(IN_MOVE_SELF),
	bit_name(IN_UNMOUNT),
	bit_name(IN_Q_OVERFLOW),
	bit_name(IN_IGNORED),
	bit_name(IN_ONLYDIR),
	bit_name(IN_DONT_FOLLOW),
	bit_name(IN_MASK_ADD),
	bit_name(IN_ISDIR),
	bit_name(IN_ONESHOT),
	bit_name(IN_EXCL_UNLINK),
	{0}
};

static PyObject *decode_mask(int mask)
{
	PyObject *ret = PyList_New(0);
	int i;

	if (ret == NULL)
		goto bail;

	for (i = 0; bit_names[i].bit; i++) {
		if (mask & bit_names[i].bit) {
			if (bit_names[i].pyname == NULL) {
				bit_names[i].pyname = PyUnicode_FromString(bit_names[i].name);
				if (bit_names[i].pyname == NULL)
					goto bail;
			}
			Py_INCREF(bit_names[i].pyname);
			if (PyList_Append(ret, bit_names[i].pyname) == -1)
				goto bail;
		}
	}

	goto done;

bail:
	Py_CLEAR(ret);

done:
	return ret;
}

static PyObject *pydecode_mask(PyObject *self, PyObject *args)
{
	int mask;

	if (!PyArg_ParseTuple(args, "i:decode_mask", &mask))
		return NULL;

	return decode_mask(mask);
}

PyDoc_STRVAR(
	decode_mask_doc,
	"decode_mask(mask) -> list_of_strings\n"
	"\n"
	"Decode an inotify mask value into a list of strings that give the\n"
	"name of each bit set in the mask.");

static char doc[] = "Low-level inotify interface wrappers.";

static void define_const(PyObject *dict, const char *name, uint32_t val)
{
	PyObject *pyval = PyLong_FromLong(val);
	PyObject *pyname = PyUnicode_FromString(name);

	if (!pyname || !pyval)
		goto bail;

	PyDict_SetItem(dict, pyname, pyval);

bail:
	Py_XDECREF(pyname);
	Py_XDECREF(pyval);
}

static void define_consts(PyObject *dict)
{
	define_const(dict, "IN_ACCESS", IN_ACCESS);
	define_const(dict, "IN_MODIFY", IN_MODIFY);
	define_const(dict, "IN_ATTRIB", IN_ATTRIB);
	define_const(dict, "IN_CLOSE_WRITE", IN_CLOSE_WRITE);
	define_const(dict, "IN_CLOSE_NOWRITE", IN_CLOSE_NOWRITE);
	define_const(dict, "IN_OPEN", IN_OPEN);
	define_const(dict, "IN_MOVED_FROM", IN_MOVED_FROM);
	define_const(dict, "IN_MOVED_TO", IN_MOVED_TO);

	define_const(dict, "IN_CLOSE", IN_CLOSE);
	define_const(dict, "IN_MOVE", IN_MOVE);

	define_const(dict, "IN_CREATE", IN_CREATE);
	define_const(dict, "IN_DELETE", IN_DELETE);
	define_const(dict, "IN_DELETE_SELF", IN_DELETE_SELF);
	define_const(dict, "IN_MOVE_SELF", IN_MOVE_SELF);
	define_const(dict, "IN_UNMOUNT", IN_UNMOUNT);
	define_const(dict, "IN_Q_OVERFLOW", IN_Q_OVERFLOW);
	define_const(dict, "IN_IGNORED", IN_IGNORED);

	define_const(dict, "IN_ONLYDIR", IN_ONLYDIR);
	define_const(dict, "IN_DONT_FOLLOW", IN_DONT_FOLLOW);
	define_const(dict, "IN_MASK_ADD", IN_MASK_ADD);
	define_const(dict, "IN_ISDIR", IN_ISDIR);
	define_const(dict, "IN_EXCL_UNLINK", IN_EXCL_UNLINK);
	define_const(dict, "IN_ONESHOT", IN_ONESHOT);
	define_const(dict, "IN_ALL_EVENTS", IN_ALL_EVENTS);
}

// the event struct is not really doing anything that couldn't be done with a
// python named tuple, it should be replaced.
struct event {
	PyObject_HEAD
	PyObject *wd;
	PyObject *mask;
	PyObject *cookie;
	PyObject *name;
};

static PyObject *event_wd(PyObject *self, void *x)
{
	struct event *evt = (struct event *) self;
	Py_INCREF(evt->wd);
	return evt->wd;
}

static PyObject *event_mask(PyObject *self, void *x)
{
	struct event *evt = (struct event *) self;
	Py_INCREF(evt->mask);
	return evt->mask;
}

static PyObject *event_cookie(PyObject *self, void *x)
{
	struct event *evt = (struct event *) self;
	Py_INCREF(evt->cookie);
	return evt->cookie;
}

static PyObject *event_name(PyObject *self, void *x)
{
	struct event *evt = (struct event *) self;
	Py_INCREF(evt->name);
	return evt->name;
}

static struct PyGetSetDef event_getsets[] = {
	{"wd", event_wd, NULL,
	 "watch descriptor"},
	{"mask", event_mask, NULL,
	 "event mask"},
	{"cookie", event_cookie, NULL,
	 "rename cookie, if rename-related event"},
	{"name", event_name, NULL,
	 "file name"},
	{NULL}
};

PyDoc_STRVAR(
	event_doc,
	"event: Structure describing an inotify event.");

static PyObject *event_new(PyTypeObject *t, PyObject *a, PyObject *k)
{
	return (*t->tp_alloc)(t, 0);
}

static void event_dealloc(struct event *evt)
{
	Py_XDECREF(evt->wd);
	Py_XDECREF(evt->mask);
	Py_XDECREF(evt->cookie);
	Py_XDECREF(evt->name);

	(Py_TYPE(evt)->tp_free)(evt);
}

static PyObject *event_repr(struct event *evt)
{
	int wd = PyLong_AsLong(evt->wd);
	uint32_t cookie = evt->cookie == Py_None ? 0 : PyLong_AsLong(evt->cookie);
	PyObject *ret = NULL, *pymasks = NULL, *pymask = NULL;
	PyObject *join = NULL;

	join = PyUnicode_FromString("|");
	if (join == NULL)
		goto bail;

	pymasks = decode_mask(PyLong_AsLong(evt->mask));
	if (pymasks == NULL)
		goto bail;

	pymask = PyUnicode_Join(join, pymasks);
	if (pymask == NULL)
		goto bail;

	if (evt->name != Py_None) {
		PyObject *pyname = PyObject_Repr(evt->name);

		if (cookie == 0)
			ret = PyUnicode_FromFormat("event(wd=%d, mask=%U, name=%V)",
										wd, pymask, pyname, "???");
		else
			ret = PyUnicode_FromFormat("event(wd=%d, mask=%U, "
										"cookie=0x%x, name=%V)",
									wd, pymask, cookie, pyname, "???");

		Py_XDECREF(pyname);
	} else {
		if (cookie == 0)
			ret = PyUnicode_FromFormat("event(wd=%d, mask=%U)",
									  wd, pymask);
		else {
			ret = PyUnicode_FromFormat("event(wd=%d, mask=%U, cookie=0x%x)",
									  wd, pymask, cookie);
		}
	}

	goto done;
bail:
	Py_CLEAR(ret);
	
done:
	Py_XDECREF(pymask);
	Py_XDECREF(pymasks);
	Py_XDECREF(join);

	return ret;
}

static PyTypeObject event_type = {
	PyVarObject_HEAD_INIT(NULL, 0)
	"_inotify.event",             /*tp_name*/
	sizeof(struct event), /*tp_basicsize*/
	0,                         /*tp_itemsize*/
	(destructor)event_dealloc, /*tp_dealloc*/
	0,                         /*tp_print*/
	0,                         /*tp_getattr*/
	0,                         /*tp_setattr*/
	0,                         /*tp_compare*/
	(reprfunc)event_repr,      /*tp_repr*/
	0,                         /*tp_as_number*/
	0,                         /*tp_as_sequence*/
	0,                         /*tp_as_mapping*/
	0,                         /*tp_hash */
	0,                         /*tp_call*/
	0,                         /*tp_str*/
	0,                         /*tp_getattro*/
	0,                         /*tp_setattro*/
	0,                         /*tp_as_buffer*/
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
	event_doc,           /* tp_doc */
	0,                         /* tp_traverse */
	0,                         /* tp_clear */
	0,                         /* tp_richcompare */
	0,                         /* tp_weaklistoffset */
	0,                         /* tp_iter */
	0,                         /* tp_iternext */
	0,                         /* tp_methods */
	0,                         /* tp_members */
	event_getsets,      /* tp_getset */
	0,                         /* tp_base */
	0,                         /* tp_dict */
	0,                         /* tp_descr_get */
	0,                         /* tp_descr_set */
	0,                         /* tp_dictoffset */
	0,                         /* tp_init */
	0,                         /* tp_alloc */
	event_new,          /* tp_new */
};
	
PyObject *read_events(PyObject *self, PyObject *args)
{
	PyObject *ctor_args = NULL;
	PyObject *pybufsize = NULL;
	PyObject *ret = NULL;
	int bufsize = 65536;
	char *buf = NULL;
	int nread, pos;
	int fd;

	if (!PyArg_ParseTuple(args, "i|O:read", &fd, &pybufsize))
		goto bail;

	if (pybufsize && pybufsize != Py_None)
		bufsize = PyLong_AsLong(pybufsize);
	
	ret = PyList_New(0);
	if (ret == NULL)
		goto bail;
	
	if (bufsize <= 0) {
		int r;
		
		Py_BEGIN_ALLOW_THREADS
		r = ioctl(fd, FIONREAD, &bufsize);
		Py_END_ALLOW_THREADS
		
		if (r == -1) {
			PyErr_SetFromErrno(PyExc_OSError);
			goto bail;
		}
		if (bufsize == 0)
			goto done;
	}
	else {
		static long name_max;
		static long name_fd = -1;
		long min;
		
		if (name_fd != fd) {
			name_fd = fd;
			Py_BEGIN_ALLOW_THREADS
			name_max = fpathconf(fd, _PC_NAME_MAX);
			Py_END_ALLOW_THREADS
		}
		
		min = sizeof(struct inotify_event) + name_max + 1;
		
		if (bufsize < min) {
			PyErr_Format(PyExc_ValueError, "bufsize must be at least %d",
						 (int) min);
			goto bail;
		}
	}

	buf = alloca(bufsize);
	
	Py_BEGIN_ALLOW_THREADS
	nread = read(fd, buf, bufsize);
	Py_END_ALLOW_THREADS

	if (nread == -1) {
		PyErr_SetFromErrno(PyExc_OSError);
		goto bail;
	}

	ctor_args = PyTuple_New(0);

	if (ctor_args == NULL)
		goto bail;
	
	pos = 0;
	
	while (pos < nread) {
		struct inotify_event *in = (struct inotify_event *) (buf + pos);
		struct event *evt;
		PyObject *obj;

		obj = PyObject_CallObject((PyObject *) &event_type, ctor_args);

		if (obj == NULL)
			goto bail;

		evt = (struct event *) obj;

		evt->wd = PyLong_FromLong(in->wd);
		evt->mask = PyLong_FromLong(in->mask);
		if (in->mask & IN_MOVE)
			evt->cookie = PyLong_FromLong(in->cookie);
		else {
			Py_INCREF(Py_None);
			evt->cookie = Py_None;
		}
		if (in->len)
			evt->name = PyUnicode_FromString(in->name);
		else {
			Py_INCREF(Py_None);
			evt->name = Py_None;
		}

		if (!evt->wd || !evt->mask || !evt->cookie || !evt->name)
			goto mybail;

		if (PyList_Append(ret, obj) == -1)
			goto mybail;

		pos += sizeof(struct inotify_event) + in->len;
		Py_DECREF(obj);
		continue;

	mybail:
		Py_CLEAR(evt->wd);
		Py_CLEAR(evt->mask);
		Py_CLEAR(evt->cookie);
		Py_CLEAR(evt->name);
		Py_DECREF(obj);

		goto bail;
	}
	
	goto done;

bail:
	Py_CLEAR(ret);
	
done:
	Py_XDECREF(ctor_args);

	return ret;
}

PyDoc_STRVAR(
	read_doc,
	"read(fd, bufsize[=65536]) -> list_of_events\n"
	"\n"
	"\nRead inotify events from a file descriptor.\n"
	"\n"
	"        fd: file descriptor returned by init()\n"
	"        bufsize: size of buffer to read into, in bytes\n"
	"\n"
	"Return a list of event objects.\n"
	"\n"
	"If bufsize is > 0, block until events are available to be read.\n"
	"Otherwise, immediately return all events that can be read without\n"
	"blocking.");


static PyMethodDef methods[] = {
	{"init", init, METH_VARARGS, init_doc},
	{"add_watch", add_watch, METH_VARARGS, add_watch_doc},
	{"remove_watch", remove_watch, METH_VARARGS, remove_watch_doc},
	{"read", read_events, METH_VARARGS, read_doc},
	{"decode_mask", pydecode_mask, METH_VARARGS, decode_mask_doc},
	{NULL},
};


#if PY_MAJOR_VERSION >= 3
PyMODINIT_FUNC PyInit__inotify(void)
{
	PyObject *mod, *dict;
	static struct PyModuleDef moduledef = {
		PyModuleDef_HEAD_INIT, "_inotify", doc, -1, methods, };

	if (PyType_Ready(&event_type) == -1)
		return NULL;

	mod = PyModule_Create(&moduledef);

	dict = PyModule_GetDict(mod);
	
	if (dict)
		define_consts(dict);

	return mod;
}

#else
void init_inotify(void)
{
	PyObject *mod, *dict;

	if (PyType_Ready(&event_type) == -1)
		return;

	mod = Py_InitModule3("_inotify", methods, doc);

	dict = PyModule_GetDict(mod);
	
	if (dict)
		define_consts(dict);

	return;
}
#endif
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.