mbox_scan.c 11 KB
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
/* GNU mailutils - a suite of utilities for electronic mail
   Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Library Public License as published by
   the Free Software Foundation; either version 2, 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 Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <mailutils/error.h>
#include <mailutils/attribute.h>
#include <mailutils/sys/mbox.h>
#include "valid.h"

#define ISSTATUS(buf) (\
(buf[0] == 'S' || buf[0] == 's') \
 && (buf[1] == 'T' || buf[1] == 't') \
 && (buf[2] == 'A' || buf[2] == 'a') \
 && (buf[3] == 'T' || buf[3] == 't') \
 && (buf[4] == 'U' || buf[4] == 'u') \
 && (buf[5] == 'S' || buf[5] == 's') \
 && (buf[6] == ':' || buf[6] == ' ' || buf[6] == '\t'))

#define ISX_IMAPBASE(buf) (\
(buf[0] == 'X' || buf[0] == 'x') \
 && (buf[1] == '-') \
 && (buf[2] == 'I' || buf[2] == 'i') \
 && (buf[3] == 'M' || buf[3] == 'm') \
 && (buf[4] == 'A' || buf[4] == 'a') \
 && (buf[5] == 'P' || buf[5] == 'p') \
 && (buf[6] == 'B' || buf[6] == 'b') \
 && (buf[7] == 'A' || buf[7] == 'a') \
 && (buf[8] == 'S' || buf[8] == 's') \
 && (buf[9] == 'E' || buf[9] == 'e') \
 && (buf[10] == ':' || buf[10] == ' ' || buf[10] == '\t'))

#define ISX_UID(buf) (\
(buf[0] == 'X' || buf[0] == 'x') \
 && (buf[1] == '-') \
 && (buf[2] == 'U' || buf[2] == 'u') \
 && (buf[3] == 'I' || buf[3] == 'i') \
 && (buf[4] == 'D' || buf[4] == 'd') \
 && (buf[5] == ':' || buf[5] == ' ' || buf[5] == '\t'))


static int
mbox_parse_status (mbox_message_t mum, char *buf, size_t n)
{
  char *s = memchr (buf, ':', n);
  if (s)
    {
      s++;
      for (; *s; s++)
	{
	  switch (*s)
	    {
	    case 'r':
	    case 'R':
	      mum->attr_flags |= MU_ATTRIBUTE_READ;
	      break;

	    case 'O':
	    case 'o':
	      mum->attr_flags |= MU_ATTRIBUTE_SEEN;
	      break;

	    case 'a':
	    case 'A':
	      mum->attr_flags |= MU_ATTRIBUTE_ANSWERED;
	      break;

	    case 'd':
	    case 'D':
	      mum->attr_flags |= MU_ATTRIBUTE_DELETED;
	      break;

	    case 't':
	    case 'T':
	      mum->attr_flags |= MU_ATTRIBUTE_DRAFT;
	      break;

	    case 'f':
	    case 'F':
	      mum->attr_flags |= MU_ATTRIBUTE_FLAGGED;
	      break;

	    }
	}
    }
  return 0;
}

static int
mbox_alloc_umessages (mbox_t mbox)
{
  if (mbox->messages_count >= mbox->umessages_count)
    {
      mbox_message_t *m;
      size_t i;
      size_t num = mbox->messages_count + 32;
      m = realloc (mbox->umessages, num * sizeof (*m));
      if (m == NULL)
	return MU_ERROR_NO_MEMORY;
      mbox->umessages = m;
      mbox->umessages_count = num;
      for (i = mbox->messages_count; i < mbox->umessages_count; i++)
	{
	  mbox->umessages[i] = calloc (1, sizeof (**m));
	  if (mbox->umessages[i] == NULL)
	    return MU_ERROR_NO_MEMORY;
	}
    }
  return 0;
}

/* Parsing.
   The approach is to detect the "From " at the start of a new message, give
   the position of the header and scan until "\n" then set header and body
   position, scan until we it another "From ".  */
int
mbox_scan0 (mbox_t mbox, unsigned int msgno, unsigned int *pcount,
	    int do_notif)
{
#define MSGLINELEN 1024
  char buf[MSGLINELEN];
  int inheader;
  int inbody;
  off_t total = 0;
  mbox_message_t mum = NULL;
  int status = 0;
  unsigned int lines;
  int newline;
  size_t n = 0;
  char *sfield = NULL;
  int fd = -1;
  off_t file_size = 0;

  int zn, isfrom = 0;
  char *temp;

  mbox_debug_print (mbox, "scan(%u,%d)", msgno, do_notif);

  if (mbox == NULL)
    return MU_ERROR_INVALID_PARAMETER;

  /* Save the timestamp.  */
  status = stream_get_fd (mbox->carrier, &fd);
  if (status == 0)
    {
      struct stat statbuf;
      if (fstat (fd, &statbuf) == 0)
	{
	  /* We do not save the size here since the scan may be interrupted
	     we'll have a partial scan mailbox which does not reflect the
	     reality if expunge.  */
	  /*	  mbox->size = statbuf.st_size; */
	  file_size = statbuf.st_size;
	}
      else
	status = MU_ERROR_IO;
    }
  else
    status = MU_ERROR_IO;

  /* Move along, move along nothing to see.  */
  if (!mbox_has_newmail (mbox) && mbox->size == file_size)
    {
      if (pcount)
	*pcount = mbox->messages_count;
      return 0;
    }

  /* Bailout early on error.  */
  if (status != 0)
    return status;

  if (mbox->hcache.size == 0)
    mbox_set_default_hcache (mbox);

  /* Lock the mbox before starting.  */
  /* FIXME: Check error..  */
  lockfile_lock (mbox->lockfile);

  /* Seek to the starting point.  */
  if (mbox->umessages && msgno > 0 && mbox->messages_count > 0
      && msgno <= mbox->messages_count)
    {
      mum = mbox->umessages[msgno - 1];
      if (mum)
        total = mum->from_;
      mbox->messages_count = msgno - 1;
    }
  else
    mbox->messages_count = 0;

  newline = 1;
  errno = lines = inheader = inbody = 0;
  mum = NULL;

  while ((status = stream_readline (mbox->carrier, buf, sizeof buf,
				    total, &n)) == 0 && n > 0)
    {
      int nl;
      total += n;

      nl = (*buf == '\n') ? 1 : 0;
      VALID(buf, temp, isfrom, zn);
      isfrom = (isfrom) ? 1 : 0;

      /* Which part of the message are we in ?  */
      inheader = isfrom | ((!nl) & inheader);
      inbody = (!isfrom) & (!inheader);

      if (buf[n - 1] == '\n')
        lines++;

      if (inheader)
        {
          /* New message.  */
          if (isfrom)
            {
              /* Signal the end of the previous body.  */
              if (mum && !mum->body.end)
                {
                  mum->body.end = total - n;
                  mum->body.lines = --lines - newline;
		  /* DISPATCH_ADD_MSG(mbox); */
                  if (do_notif)
		    {
		      status = mbox_newmsg_cb (mbox, mbox->messages_count);
		      if (status)
			{
			  lockfile_unlock (mbox->lockfile);
			  return status;
			}
		    }
                }
              /* Allocate_msgs will initialize mum.  */
              status = mbox_alloc_umessages (mbox);
	      if (status != 0)
		{
		  lockfile_unlock (mbox->lockfile);
		  return status;
		}
              mbox->messages_count++;
              mum = mbox->umessages[mbox->messages_count - 1];
              mum->from_ = total - n;
              mum->header.start = total;
              mum->body.end = mum->body.start = 0;
              mum->attr_flags = 0;
              lines = 0;
            }
          else if (ISSTATUS(buf))
            {
	      mbox_parse_status (mum, buf, n);
	    }
	  else if (ISX_IMAPBASE(buf))
	    {
              char *s = memchr (buf, ':', n);
              if (s)
                {
                  s++;
		  mbox->uidvalidity = strtoul (s, &s, 10);
		  mbox->uidnext = strtoul (s, NULL, 10);
                }
            }
          else if (ISX_UID(buf))
            {
              char *s = memchr (buf, ':', n);
              if (s)
                {
                  s++;
                  mum->uid = strtoul(s, NULL, 10);
                }
            }
          else if (sfield && (buf[0] == ' ' || buf[0] == '\t'))
            {
	      if (buf[n - 1] == '\n')
		buf[n - 1] = 0;
              mbox_append_hcache (mbox, mbox->messages_count, sfield, buf);
            }
          else
            {
              char *s = memchr (buf, ':', n);
	      if (sfield)
		free (sfield);
	      sfield = NULL;
              if (s)
                {
		  *s = '\0';
                  s++;
		  while (*s == ' ') s++;
		  if (buf[n - 1] == '\n')
		    buf[n - 1] = 0;
		  mbox_append_hcache (mbox, mbox->messages_count, buf, s);
		  sfield = strdup (buf);
		}
            }
        }

      /* Body.  */
      if (inbody)
        {
          /* Set the body position.  */
          if (mum && !mum->body.start)
            {
              mum->body.start = total - n + nl;
              mum->header.end = total - n + nl;
              mum->header.lines = lines;
              lines = 0;
            }
        }

      newline = nl;

      /* Every 100 mesgs update the lock, it should be every minute.  */
      if ((mbox->messages_count % 100) == 0)
        lockfile_touchlock (mbox->lockfile);

      /* Ping them every 1000 lines. Should be tunable.  */
      if (do_notif)
        if (((lines +1) % 1000) == 0)
          mbox_progress_cb (mbox, (total/file_size)*100);

    } /* while */

  if (sfield)
    free (sfield);

  /* FIXME: use mbox->size for total. */
  mbox->size = total;

  if (mum)
    {
      mum->body.end = total;
      mum->body.lines = lines - newline;
      if (do_notif)
        mbox_newmsg_cb (mbox, mbox->messages_count);
    }
  if (pcount)
    *pcount = mbox->messages_count;
  lockfile_unlock (mbox->lockfile);

  /* Reset the uidvalidity.  */
  if (mbox->messages_count > 0)
    {
      mum = mbox->umessages[0];
      if (mbox->uidvalidity == 0)
        {
          mbox->uidvalidity = (unsigned long)time (NULL);
          mbox->uidnext = mbox->messages_count + 1;
          /* The uidvalidity was not save, flag it to be save
	     when expunging.  */
          mum->attr_flags |= MU_ATTRIBUTE_MODIFIED;
        }
    }

  /* Reset the IMAP uids, if necessary. UID according to IMAP RFC is a 32 bit
     ascending number for each messages  */
  {
    size_t uid;
    size_t ouid;
    size_t i;
    for (uid = ouid = i = 0; i < mbox->messages_count; i++)
      {
        mum = mbox->umessages[i];
        uid = mum->uid;
        if (uid <= ouid)
          {
            uid = ouid + 1;
            mum->uid = ouid = uid;
            /* UID was not ascentind, clear this when expunging by
	       setting modification flag.  */
            mum->attr_flags |= MU_ATTRIBUTE_MODIFIED;
          }
        else
          ouid = uid;
      }
    if (mbox->messages_count > 0 && uid >= mbox->uidnext)
      {
        mum = mbox->umessages[0];
        mbox->uidnext = uid + 1;
	/* The uidnext was wrong rewrite it when expunging.  */
        mum->attr_flags |= MU_ATTRIBUTE_MODIFIED;
      }
  }

  /* If reserved more memory then scan messages, realloc not
     to waste memory.  */
  if (mbox->messages_count && mbox->messages_count < mbox->umessages_count)
    {
      size_t i;
      for (i = mbox->messages_count; i < mbox->umessages_count; i++)
	{
	  if (mbox->umessages[i])
	    mbox_release_msg (mbox, i + 1);
	}
      mbox->umessages = realloc (mbox->umessages,
				 mbox->messages_count
				 * sizeof (*(mbox->umessages)));
      mbox->umessages_count = mbox->messages_count;
    }
  lockfile_unlock (mbox->lockfile);
  return status;
}

int
mbox_scan (mbox_t mbox, unsigned int msgno, unsigned int *pcount)
{
  return mbox_scan0 (mbox, msgno, pcount, 1);
}

int
mbox_count (mbox_t mbox, unsigned int *pcount)
{
  return mbox_scan0 (mbox, 1, pcount, 0);
}