File: inevent.c

package info (click to toggle)
conman 0.2.7-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, stretch
  • size: 1,424 kB
  • sloc: ansic: 11,173; sh: 4,072; exp: 2,132; makefile: 153; perl: 122
file content (545 lines) | stat: -rw-r--r-- 16,240 bytes parent folder | download | duplicates (3)
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
/*****************************************************************************
 *  $Id: inevent.c 1033 2011-04-06 21:53:48Z chris.m.dunlap $
 *****************************************************************************
 *  Written by Chris Dunlap <cdunlap@llnl.gov>.
 *  Copyright (C) 2007-2011 Lawrence Livermore National Security, LLC.
 *  Copyright (C) 2001-2007 The Regents of the University of California.
 *  UCRL-CODE-2002-009.
 *
 *  This file is part of ConMan: The Console Manager.
 *  For details, see <http://conman.googlecode.com/>.
 *
 *  ConMan is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option)
 *  any later version.
 *
 *  ConMan is distributed in the hope that it will be useful, but WITHOUT
 *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 *  for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with ConMan.  If not, see <http://www.gnu.org/licenses/>.
 *****************************************************************************/


/*  FIXME:
 *  This code does not fully handle the following cases:
 *  - when the watched directory does not yet exist
 *  - when the watched directory is later deleted
 *  In the event of the watched directory not yet existing, this code should
 *    watch the parent directory for its subsequent creation; if the parent
 *    does not yet exist, it should watch the parent's parent, etc., up to the
 *    root.  This might be best accomplished by initially registering all of
 *    parent directories up to the root for the directory being watched.
 *  In the event of the watched directory being deleted (event IN_IGNORED),
 *    once the existing watch has been removed, this should degenerate into the
 *    case above where the watched directory does not yet exist.
 *
 *  Currently, inotify works as expected as long as the parent directory being
 *    watched persists for the lifetime of the daemon.  But once that
 *    directory's inode is removed, the daemon falls back to using timers to
 *    periodically resurrect downed objects.
 */

#if HAVE_CONFIG_H
#  include <config.h>
#endif /* HAVE_CONFIG_H */


/*****************************************************************************
 *  Stubbed Routines for building without <sys/inotify.h>.
 *
 *  These routines preserve type-checking while allowing any decent compiler
 *    to optimize the case of simply returning a constant integer such that
 *    no function call overhead is incurred.
 *****************************************************************************/

#if ! HAVE_SYS_INOTIFY_H

#include "inevent.h"


int
inevent_add (const char *filename, inevent_cb_f cb_fnc, void *cb_arg)
{
    return (-1);
}


int
inevent_remove (const char *filename)
{
    return (-1);
}


int
inevent_get_fd (void)
{
    return (-1);
}


int inevent_process (void)
{
    return (-1);
}


/*****************************************************************************
 *  Routines for building with <sys/inotify.h> (Linux 2.6.13+).
 *****************************************************************************/

#else  /* HAVE_SYS_INOTIFY_H */

#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>
#include "inevent.h"
#include "list.h"
#include "log.h"
#include "util-file.h"


/*****************************************************************************
 *  Constants
 *****************************************************************************/

/*  Number of bytes for the average inotify event (w/ 16 bytes for name).
 */
#define INEVENT_SIZE            ((sizeof (struct inotify_event)) + 16)

/*  Number of average inotify events to process per read invocation.
 */
#define INEVENT_NUM             128

/*  Number of bytes to allocate for the inotify event buffer.
 */
#define INEVENT_BUF_LEN         ((INEVENT_SIZE) * (INEVENT_NUM))


/*****************************************************************************
 *  Internal Data Types
 *****************************************************************************/

struct inevent {
    char         *pathname;             /* pathname being watched            */
    char         *dirname;              /* directory component of pathname   */
    char         *filename;             /* filename component of pathname    */
    inevent_cb_f  cb_fnc;               /* callback function                 */
    void         *cb_arg;               /* callback function arg             */
    int           wd;                   /* inotify watch descriptor          */
};

typedef struct inevent inevent_t;


/*****************************************************************************
 *  Private Function Prototypes
 *****************************************************************************/

static int _inevent_init (void);

static void _inevent_fini (void);

static inevent_t * _inevent_create (const char *pathname,
    inevent_cb_f cb_fnc, void *cb_arg);

static void _inevent_destroy (inevent_t *inevent_ptr);

static int _list_find_by_path (const inevent_t *inevent_ptr,
    const char *pathname);

static int _list_find_by_wd (const inevent_t *inevent_ptr,
    const int *wd_ptr);

static int _list_find_by_event (const inevent_t *inevent_ptr,
    const struct inotify_event *event_ptr);


/*****************************************************************************
 *  Internal Data Variables
 *****************************************************************************/

static int  inevent_fd = -1;            /* inotify file descriptor           */
static List inevent_list = NULL;        /* list of inevent structs           */


/*****************************************************************************
 *  Public Functions
 *****************************************************************************/

int
inevent_add (const char *pathname, inevent_cb_f cb_fnc, void *cb_arg)
{
/*  Adds an inotify event for [pathname], causing [cb_fnc] to be invoked with
 *    [cb_arg] whenever the specified file is created.
 *  Returns 0 on success, or -1 on error.
 */
    inevent_t *inevent_ptr;

    if (pathname == NULL) {
        log_msg (LOG_ERR, "inotify event pathname not specified");
        return (-1);
    }
    if (cb_fnc == NULL) {
        log_msg (LOG_ERR, "inotify event callback not specified");
        return (-1);
    }
    if (pathname[0] != '/') {
        log_msg (LOG_ERR, "inotify event path \"%s\" is not absolute",
            pathname);
        return (-1);
    }
    if (inevent_fd == -1) {
        if (_inevent_init () < 0) {
            log_msg (LOG_ERR, "unable to initialize inotify: %s",
                strerror (errno));
            return (-1);
        }
    }
    if (list_find_first (inevent_list, (ListFindF) _list_find_by_path,
            (void *) pathname)) {
        log_msg (LOG_ERR, "inotify event path \"%s\" already specified",
            pathname);
        return (-1);
    }
    inevent_ptr = _inevent_create (pathname, cb_fnc, cb_arg);
    if (inevent_ptr == NULL) {
        return (-1);
    }
    list_append (inevent_list, inevent_ptr);
    return (0);
}


int
inevent_remove (const char *pathname)
{
/*  Removes the inotify event (if present) for [pathname].
 *  Returns 0 on success, or -1 on error.
 */
    ListIterator  li = NULL;
    inevent_t    *inevent_ptr;
    int           wd_cnt;

    if (pathname == NULL) {
        return (0);
    }
    if (inevent_list == NULL) {
        return (0);
    }
    li = list_iterator_create (inevent_list);
    inevent_ptr = list_find (li, (ListFindF) _list_find_by_path,
            (void *) pathname);
    if (inevent_ptr == NULL) {
        log_msg (LOG_ERR, "inotify event path \"%s\" not registered",
                pathname);
        list_iterator_destroy (li);
        return (0);
    }
    (void) list_remove (li);

    list_iterator_reset (li);
    wd_cnt = 0;
    while (list_find (li, (ListFindF) _list_find_by_wd, &(inevent_ptr->wd))) {
        wd_cnt++;
    }
    list_iterator_destroy (li);

    /*  If no other inevents were found with a matching wd, then this inevent
     *    is the only one associated with this watch descriptor.  As such, the
     *    watch associated with this watch descriptor can be removed since no
     *    other objects are relying on it.
     *  Note that multiple files may share the same watch descriptor since it
     *    is the file's directory that is watched.
     */
    if ((inevent_ptr->wd >= 0) && (wd_cnt == 0)) {
        (void) inotify_rm_watch (inevent_fd, inevent_ptr->wd);
        DPRINTF((10, "Removed inotify watch wd=%d for directory \"%s\".\n",
                inevent_ptr->wd, inevent_ptr->dirname));
    }
    _inevent_destroy (inevent_ptr);

    if (list_is_empty (inevent_list)) {
        _inevent_fini ();
    }
    return (0);
}


int
inevent_get_fd (void)
{
/*  Returns the file descriptor associated with the inotify event queue,
 *    or -1 on error.
 */
    return (inevent_fd);
}


int
inevent_process (void)
{
/*  Processes the callback functions for all available events in the inotify
 *    event queue.
 *  Returns the number of events processed on success, or -1 on error.
 */
    char buf [INEVENT_BUF_LEN];
    int  len;
    int  n = 0;

    if (inevent_fd == -1) {
        return (-1);
    }

retry_read:
    len = read (inevent_fd, buf, sizeof (buf));
    if (len < 0) {
        if (errno == EINTR) {
            goto retry_read;
        }
        log_msg (LOG_ERR, "unable to read inotify fd: %s", strerror (errno));
        return (-1);
    }
    else if (len == 0) {
        log_msg (LOG_ERR, "inotify read buffer is too small");
        return (-1);
    }
    else {
        unsigned int i = 0;
        uint32_t     event_mask = IN_CREATE | IN_MOVED_TO;

        while (i < len) {

            struct inotify_event *event_ptr;
            inevent_t            *inevent_ptr;

            event_ptr = (struct inotify_event *) &buf[i];

            DPRINTF((15,
                "Received inotify event wd=%d mask=0x%x len=%u name=\"%s\".\n",
                event_ptr->wd, event_ptr->mask, event_ptr->len,
                (event_ptr->len > 0 ? event_ptr->name : "")));

            if (event_ptr->mask & IN_IGNORED) {

                (void) list_delete_all (inevent_list,
                    (ListFindF) _list_find_by_wd, &(event_ptr->wd));
            }
            else if ((event_ptr->mask & event_mask) && (event_ptr->len > 0)) {

                inevent_ptr = list_find_first (inevent_list,
                    (ListFindF) _list_find_by_event, event_ptr);

                if ((inevent_ptr != NULL) && (inevent_ptr->cb_fnc != NULL)) {
                    inevent_ptr->cb_fnc (inevent_ptr->cb_arg);
                }
            }
            i += sizeof (struct inotify_event) + event_ptr->len;
            n++;
        }
    }
    return (n);
}


/*****************************************************************************
 *  Private Functions
 *****************************************************************************/

static int
_inevent_init (void)
{
/*  Initializes the inotify event subsystem.
 *  Returns 0 on success, or -1 on error (with errno set).
 */
    assert (inevent_fd == -1);
    assert (inevent_list == NULL);

    if (inevent_fd == -1) {
        inevent_fd = inotify_init ();
        if (inevent_fd == -1) {
            goto err;
        }
        set_fd_closed_on_exec (inevent_fd);
        set_fd_nonblocking (inevent_fd);
    }
    if (inevent_list == NULL) {
        inevent_list = list_create ((ListDelF) _inevent_destroy);
        if (inevent_list == NULL) {
            goto err;
        }
    }
    DPRINTF((5, "Initialized inotify event subsystem.\n"));
    return (inevent_fd);

err:
    _inevent_fini ();
    return (-1);
}


static void
_inevent_fini (void)
{
/*  Shuts down the inotify event subsystem.
 */
    assert (inevent_fd >= 0);
    assert (inevent_list != NULL);

    if (inevent_fd >= 0) {
        (void) close (inevent_fd);
        inevent_fd = -1;
    }
    if (inevent_list != NULL) {
        list_destroy (inevent_list);
        inevent_list = NULL;
    }
    DPRINTF((5, "Shut down inotify event subsystem.\n"));
    return;
}


static inevent_t *
_inevent_create (const char *pathname, inevent_cb_f cb_fnc, void *cb_arg)
{
/*  Creates an inotify event object for [cb_fnc] to be invoked with [cb_arg]
 *    whenever the file specified by [pathname] is created.
 *  Returns a pointer to the new object on success, or NULL on error
 *    (with errno set).
 */
    inevent_t *inevent_ptr = NULL;
    char      *p;
    uint32_t   event_mask = IN_CREATE | IN_MOVED_TO;

    assert (pathname != NULL);
    assert (pathname[0] == '/');
    assert (cb_fnc != NULL);

    inevent_ptr = malloc (sizeof (*inevent_ptr));
    if (inevent_ptr == NULL) {
        goto err;
    }
    memset (inevent_ptr, 0, sizeof (*inevent_ptr));
    inevent_ptr->wd = -1;

    inevent_ptr->pathname = strdup (pathname);
    if (inevent_ptr->pathname == NULL) {
        goto err;
    }
    inevent_ptr->dirname = strdup (pathname);
    if (inevent_ptr->dirname == NULL) {
        goto err;
    }
    p = strrchr (inevent_ptr->dirname, '/');
    inevent_ptr->filename = strdup (p + 1);
    if (inevent_ptr->filename == NULL) {
        goto err;
    }
    if (p == inevent_ptr->dirname) {    /* dirname is root directory ("/") */
        *++p = '\0';
    }
    else {
        *p = '\0';
    }
    inevent_ptr->cb_fnc = cb_fnc;
    inevent_ptr->cb_arg = cb_arg;

    inevent_ptr->wd = inotify_add_watch (inevent_fd, inevent_ptr->dirname,
            event_mask);
    if (inevent_ptr->wd == -1) {
        goto err;
    }

    DPRINTF((10, "Added inotify watch wd=%d for \"%s\".\n",
            inevent_ptr->wd, inevent_ptr->pathname));
    return (inevent_ptr);

err:
    _inevent_destroy (inevent_ptr);
    return (NULL);
}


static void
_inevent_destroy (inevent_t *inevent_ptr)
{
/*  Destroys the inotify event object referenced by [inevent_ptr].
 */
    assert (inevent_ptr != NULL);

    if (inevent_ptr == NULL) {
        return;
    }
    DPRINTF((10, "Removed inotify watch wd=%d for \"%s\".\n",
            inevent_ptr->wd, inevent_ptr->pathname));

    if (inevent_ptr->pathname != NULL) {
        free (inevent_ptr->pathname);
    }
    if (inevent_ptr->dirname != NULL) {
        free (inevent_ptr->dirname);
    }
    if (inevent_ptr->filename != NULL) {
        free (inevent_ptr->filename);
    }
    free (inevent_ptr);
    return;
}


static int
_list_find_by_path (const inevent_t *inevent_ptr, const char *pathname)
{
/*  List function helper to match items in a list of inevent_t pointers using
 *    the pathname [pathname] as the key.
 *  Returns non-zero if the key is found; o/w, returns zero.
 */
    assert (inevent_ptr != NULL);
    assert (pathname != NULL);

    return (strcmp (inevent_ptr->pathname, pathname) == 0);
}


static int
_list_find_by_wd (const inevent_t *inevent_ptr, const int *wd_ptr)
{
/*  List function helper to match items in a list of inevent_t pointers using
 *    a pointer to an inotify watch descriptor [wd_ptr] as the key.
 *  Returns non-zero if the key is found; o/w, returns zero.
 */
    assert (inevent_ptr != NULL);
    assert (wd_ptr != NULL);

    return (inevent_ptr->wd == *wd_ptr);
}


static int
_list_find_by_event (const inevent_t *inevent_ptr,
                     const struct inotify_event *event_ptr)
{
/*  List function helper to match items in a list of inevent_t pointers using
 *    a pointer to an inotify_event struct [event_ptr] as the key.
 *  Returns non-zero if the key is found; o/w, returns zero.
 */
    assert (inevent_ptr != NULL);
    assert (inevent_ptr->filename != NULL);
    assert (event_ptr != NULL);
    assert (event_ptr->len > 0);
    assert (event_ptr->name != NULL);

    return ((inevent_ptr->wd == event_ptr->wd) &&
            (strcmp (inevent_ptr->filename, event_ptr->name) == 0));
}


#endif /* HAVE_SYS_INOTIFY_H */