monitor.c 11.1 KB
Newer Older
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
/* * Copyright (C) 2018 Gero Treuner <gero@70t.de>
 *
 *     This program 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 2 of the License, or
 *     (at your option) any later version.
 *
 *     This program 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 this program; if not, write to the Free Software
 *     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#if HAVE_CONFIG_H
# include "config.h"
#endif

#if HAVE_SYS_INOTIFY_H
# include <sys/types.h>
# include <sys/inotify.h>
# include <unistd.h>
# include <poll.h>
#endif

#include "mutt.h"
#include "buffy.h"
#include "monitor.h"
#include "mx.h"
33
#include "mutt_curses.h"
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

#include <errno.h>
#include <sys/stat.h>

typedef struct monitor_t
{
  struct monitor_t *next;
  char *mh_backup_path;
  dev_t st_dev;
  ino_t st_ino;
  short magic;
  int descr;
}
MONITOR;

static int INotifyFd = -1;
static MONITOR *Monitor = NULL;
static size_t PollFdsCount = 0;
static size_t PollFdsLen = 0;
static struct pollfd *PollFds;

55 56
static int MonitorContextDescriptor = -1;

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
typedef struct monitorinfo_t
{
  short magic;
  short isdir;
  const char *path;
  dev_t st_dev;
  ino_t st_ino;
  MONITOR *monitor;
  char _pathbuf[_POSIX_PATH_MAX]; /* access via path only (maybe not initialized) */
}
MONITORINFO;

#define INOTIFY_MASK_DIR  (IN_MOVED_TO | IN_ATTRIB | IN_CLOSE_WRITE | IN_ISDIR)
#define INOTIFY_MASK_FILE IN_CLOSE_WRITE

static void mutt_poll_fd_add(int fd, short events)
{
  int i = 0;
  for (i = 0; i < PollFdsCount && PollFds[i].fd != fd; ++i);

  if (i == PollFdsCount)
  {
    if (PollFdsCount == PollFdsLen)
    {
      PollFdsLen += 2;
      safe_realloc (&PollFds, PollFdsLen * sizeof(struct pollfd));
    }
    ++PollFdsCount;
    PollFds[i].fd = fd;
    PollFds[i].events = events;
  }
  else
    PollFds[i].events |= events;
}

static int mutt_poll_fd_remove(int fd)
{
  int i = 0, d;
  for (i = 0; i < PollFdsCount && PollFds[i].fd != fd; ++i);
  if (i == PollFdsCount)
    return -1;
  d = PollFdsCount - i - 1;
  if (d)
    memmove (&PollFds[i], &PollFds[i + 1], d * sizeof(struct pollfd));
  --PollFdsCount;
  return 0;
}

static int monitor_init ()
{
  if (INotifyFd == -1)
  {
    INotifyFd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
    if (INotifyFd == -1)
    {
      dprint (2, (debugfile, "monitor: inotify_init1 failed, errno=%d %s\n", errno, strerror(errno)));
      return -1;
    }
    mutt_poll_fd_add(0, POLLIN);
    mutt_poll_fd_add(INotifyFd, POLLIN);
  }
  return 0;
}

static void monitor_check_free ()
{
  if (!Monitor && INotifyFd != -1)
  {
    mutt_poll_fd_remove(INotifyFd);
    close (INotifyFd);
    INotifyFd = -1;
    MonitorFilesChanged = 0;
  }
}

static MONITOR *monitor_create (MONITORINFO *info, int descriptor)
{
  MONITOR *monitor = (MONITOR *) safe_calloc (1, sizeof (MONITOR));
  monitor->magic  = info->magic;
  monitor->st_dev = info->st_dev;
  monitor->st_ino = info->st_ino;
  monitor->descr  = descriptor;
  monitor->next   = Monitor;
  if (info->magic == MUTT_MH)
    monitor->mh_backup_path = safe_strdup(info->path);

  Monitor = monitor;

  return monitor;
}

static void monitor_delete (MONITOR *monitor)
{
  MONITOR **ptr = &Monitor;

  if (!monitor)
    return;

  FOREVER
  {
    if (!*ptr)
      return;
    if (*ptr == monitor)
      break;
    ptr = &(*ptr)->next;
  }

  FREE (&monitor->mh_backup_path); /* __FREE_CHECKED__ */
  monitor = monitor->next;
  FREE (ptr); /* __FREE_CHECKED__ */
  *ptr = monitor;
}

static int monitor_handle_ignore (int descr)
{
  int new_descr = -1;
  MONITOR *iter = Monitor;
  struct stat sb;

  while (iter && iter->descr != descr)
    iter = iter->next;

  if (iter)
  {
    if (iter->magic == MUTT_MH && stat (iter->mh_backup_path, &sb) == 0)
    {
      if ((new_descr = inotify_add_watch (INotifyFd, iter->mh_backup_path, INOTIFY_MASK_FILE)) == -1)
        dprint (2, (debugfile, "monitor: inotify_add_watch failed for '%s', errno=%d %s\n", iter->mh_backup_path, errno, strerror(errno)));
      else
      {
        dprint (3, (debugfile, "monitor: inotify_add_watch descriptor=%d for '%s'\n", descr, iter->mh_backup_path));
        iter->st_dev = sb.st_dev;
        iter->st_ino = sb.st_ino;
        iter->descr = new_descr;
      }
    }
    else
    {
195
      dprint (3, (debugfile, "monitor: cleanup watch (implicitly removed) - descriptor=%d\n", descr));
196 197
    }

198 199 200
    if (MonitorContextDescriptor == descr)
      MonitorContextDescriptor = new_descr;

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    if (new_descr == -1)
    {
      monitor_delete (iter);
      monitor_check_free ();
    }
  }

  return new_descr;
}

#define EVENT_BUFLEN MAX(4096, sizeof(struct inotify_event) + NAME_MAX + 1)

/* mutt_monitor_poll: Waits for I/O ready file descriptors or signals.
 *
 * return values:
 *      -3   unknown/unexpected events: poll timeout / fds not handled by us
 *      -2   monitor detected changes, no STDIN input
 *      -1   error (see errno)
 *       0   (1) input ready from STDIN, or (2) monitoring inactive -> no poll()
 * MonitorFilesChanged also reflects changes to monitored files.
 *
 * Only STDIN and INotify file handles currently expected/supported.
 * More would ask for common infrastructur (sockets?).
 */
225
int mutt_monitor_poll (void)
226 227 228 229 230 231 232 233 234
{
  int rc = 0, fds, i, inputReady;
  char buf[EVENT_BUFLEN]
    __attribute__ ((aligned(__alignof__(struct inotify_event))));

  MonitorFilesChanged = 0;

  if (INotifyFd != -1)
  {
235
    fds = poll (PollFds, PollFdsLen, MuttGetchTimeout);
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

    if (fds == -1)
    {
      rc = -1;
      if (errno != EINTR)
      {
        dprint (2, (debugfile, "monitor: poll() failed, errno=%d %s\n", errno, strerror(errno)));
      }
    }
    else
    {
      inputReady = 0;
      for (i = 0; fds && i < PollFdsCount; ++i)
      {
        if (PollFds[i].revents)
        {
          --fds;
          if (PollFds[i].fd == 0)
          {
            inputReady = 1;
          }
          else if (PollFds[i].fd == INotifyFd)
          {
            MonitorFilesChanged = 1;
            dprint (3, (debugfile, "monitor: file change(s) detected\n"));
            int len;
            char *ptr = buf;
            const struct inotify_event *event;

            FOREVER
            {
              len = read (INotifyFd, buf, sizeof(buf));
              if (len == -1)
              {
                if (errno != EAGAIN)
                  dprint (2, (debugfile, "monitor: read inotify events failed, errno=%d %s\n",
                              errno, strerror(errno)));
                break;
              }

              while (ptr < buf + len)
              {
                event = (const struct inotify_event *) ptr;
                dprint (5, (debugfile, "monitor:  + detail: descriptor=%d mask=0x%x\n",
                            event->wd, event->mask));
                if (event->mask & IN_IGNORED)
                  monitor_handle_ignore (event->wd);
283 284
                else if (event->wd == MonitorContextDescriptor)
                  MonitorContextChanged = 1;
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
                ptr += sizeof(struct inotify_event) + event->len;
              }
            }
          }
        }
      }
      if (!inputReady)
        rc = MonitorFilesChanged ? -2 : -3;
    }
  }

  return rc;
}

#define RESOLVERES_OK_NOTEXISTING  0
#define RESOLVERES_OK_EXISTING     1
#define RESOLVERES_FAIL_NOMAILBOX -3
#define RESOLVERES_FAIL_NOMAGIC   -2
#define RESOLVERES_FAIL_STAT      -1

/* monitor_resolve: resolve monitor entry match by BUFFY, or - if NULL - by Context.
 *
 * return values:
 *      >=0   mailbox is valid and locally accessible:
 *              0: no monitor / 1: preexisting monitor
 *       -3   no mailbox (MONITORINFO: no fields set)
 *       -2   magic not set
 *       -1   stat() failed (see errno; MONITORINFO fields: magic, isdir, path)
 */
static int monitor_resolve (MONITORINFO *info, BUFFY *buffy)
{
  MONITOR *iter;
  char *fmt = NULL;
  struct stat sb;

  if (buffy)
  {
    info->magic = buffy->magic;
    info->path  = buffy->realpath;
  }
  else if (Context)
  {
    info->magic = Context->magic;
    info->path  = Context->realpath;
  }
  else
  {
    return RESOLVERES_FAIL_NOMAILBOX;
  }

  if (!info->magic)
  {
    return RESOLVERES_FAIL_NOMAGIC;
  }
  else if (info->magic == MUTT_MAILDIR)
  {
    info->isdir = 1;
    fmt = "%s/new";
  }
  else
  {
    info->isdir = 0;
    if (info->magic == MUTT_MH)
      fmt = "%s/.mh_sequences";
  }

  if (fmt)
  {
    snprintf (info->_pathbuf, sizeof(info->_pathbuf), fmt, info->path);
    info->path = info->_pathbuf;
  }
  if (stat (info->path, &sb) != 0)
    return RESOLVERES_FAIL_STAT;

  iter = Monitor;
  while (iter && (iter->st_ino != sb.st_ino || iter->st_dev != sb.st_dev))
    iter = iter->next;

  info->st_dev = sb.st_dev;
  info->st_ino = sb.st_ino;
  info->monitor = iter;

  return iter ? RESOLVERES_OK_EXISTING : RESOLVERES_OK_NOTEXISTING;
}

/* mutt_monitor_add: add file monitor from BUFFY, or - if NULL - from Context.
 *
 * return values:
 *       0   success: new or already existing monitor
 *      -1   failed:  no mailbox, inaccessible file, create monitor/watcher failed
 */
int mutt_monitor_add (BUFFY *buffy)
{
  MONITORINFO info;
  uint32_t mask;
  int descr;

  descr = monitor_resolve (&info, buffy);
  if (descr != RESOLVERES_OK_NOTEXISTING)
384 385 386
  {
    if (!buffy && (descr == RESOLVERES_OK_EXISTING))
      MonitorContextDescriptor = info.monitor->descr;
387
    return descr == RESOLVERES_OK_EXISTING ? 0 : -1;
388
  }
389 390 391 392 393 394 395 396 397 398

  mask = info.isdir ? INOTIFY_MASK_DIR : INOTIFY_MASK_FILE;
  if ((INotifyFd == -1 && monitor_init () == -1)
      || (descr = inotify_add_watch (INotifyFd, info.path, mask)) == -1)
  {
    dprint (2, (debugfile, "monitor: inotify_add_watch failed for '%s', errno=%d %s\n", info.path, errno, strerror(errno)));
    return -1;
  }

  dprint (3, (debugfile, "monitor: inotify_add_watch descriptor=%d for '%s'\n", descr, info.path));
399 400 401
  if (!buffy)
    MonitorContextDescriptor = descr;

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
  monitor_create (&info, descr);
  return 0;
}

/* mutt_monitor_remove: remove file monitor from BUFFY, or - if NULL - from Context.
 *
 * return values:
 *       0   monitor removed (not shared)
 *       1   monitor not removed (shared)
 *       2   no monitor
 */
int mutt_monitor_remove (BUFFY *buffy)
{
  MONITORINFO info, info2;

417 418 419 420 421 422
  if (!buffy)
  {
    MonitorContextDescriptor = -1;
    MonitorContextChanged = 0;
  }

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
  if (monitor_resolve (&info, buffy) != RESOLVERES_OK_EXISTING)
    return 2;

  if (Context)
  {
    if (buffy)
    {
      if (monitor_resolve (&info2, NULL) == RESOLVERES_OK_EXISTING
          && info.st_ino == info2.st_ino && info.st_dev == info2.st_dev)
        return 1;
    }
    else
    {
      if (mutt_find_mailbox (Context->realpath))
        return 1;
    }
  }

  inotify_rm_watch(info.monitor->descr, INotifyFd);
  dprint (3, (debugfile, "monitor: inotify_rm_watch for '%s' descriptor=%d\n", info.path, info.monitor->descr));

  monitor_delete (info.monitor);
  monitor_check_free ();
  return 0;
}