burst.c 15.5 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 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 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Free Software
   Foundation, Inc.

   GNU Mailutils 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, or (at your option)
   any later version.

   GNU Mailutils 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 GNU Mailutils.  If not, see <http://www.gnu.org/licenses/>. */

/* MH burst command */

#include <mh.h>
#define obstack_chunk_alloc malloc
#define obstack_chunk_free free
#include <obstack.h>

static char doc[] = N_("GNU MH burst")"\v"
N_("Options marked with `*' are not yet implemented.\n\
Use -help to obtain the list of traditional MH options.");
static char args_doc[] = N_("[MSGLIST]");

/* GNU options */
static struct argp_option options[] = {
  {"folder",        ARG_FOLDER,        N_("FOLDER"), 0,
   N_("specify folder to operate upon")},
  {"inplace",      ARG_INPLACE,      N_("BOOL"), OPTION_ARG_OPTIONAL,
   N_("replace the source message with the table of contents, insert extracted messages after it") },
  {"noinplace",    ARG_NOINPLACE,    0, OPTION_HIDDEN, ""},
  {"quiet",        ARG_QUIET,        N_("BOOL"), OPTION_ARG_OPTIONAL,
   N_("be quiet about the messages that are not in digest format") },
  {"noquiet",      ARG_NOQUIET,      0, OPTION_HIDDEN, ""},
  {"verbose",      ARG_VERBOSE,      N_("BOOL"), OPTION_ARG_OPTIONAL,
   N_("verbosely list the actions taken") },
  {"noverbose",    ARG_NOVERBOSE,    0, OPTION_HIDDEN, ""},
  {"recursive",    ARG_RECURSIVE,    N_("BOOL"), OPTION_ARG_OPTIONAL,
   N_("recursively expand MIME messages") },
  {"norecursive",  ARG_NORECURSIVE,  0, OPTION_HIDDEN, ""},
  {"length",       ARG_LENGTH,       N_("NUMBER"), 0,
   N_("set minimal length of digest encapsulation boundary (default 1)") },
  { NULL }
};

/* Traditional MH options */
struct mh_option mh_option[] = {
  { "inplace",    MH_OPT_BOOL },
  { "quiet",      MH_OPT_BOOL },
  { "verbose",    MH_OPT_BOOL },
  { NULL }
};

/* Command line switches */
int inplace; 
int quiet;
int verbose;
int recursive;
int eb_min_length = 1;  /* Minimal length of encapsulation boundary */

#define VERBOSE(c) do { if (verbose) { printf c; putchar ('\n'); } } while (0)

static error_t
opt_handler (int key, char *arg, struct argp_state *state)
{
  switch (key)
    {
    case ARG_FOLDER: 
      mh_set_current_folder (arg);
      break;

    case ARG_INPLACE:
      inplace = is_true (arg);
      break;

    case ARG_NOINPLACE:
      inplace = 0;
      break;

    case ARG_LENGTH:
      eb_min_length = strtoul (arg, NULL, 0);
      if (eb_min_length == 0)
	eb_min_length = 1;
      break;
      
    case ARG_VERBOSE:
      verbose = is_true (arg);
      break;

    case ARG_NOVERBOSE:
      verbose = 0;
      break;

    case ARG_RECURSIVE:
      recursive = is_true (arg);
      break;
      
    case ARG_NORECURSIVE:
      recursive = 0;
      break;
      
    case ARG_QUIET:
      quiet = is_true (arg);
      break;

    case ARG_NOQUIET:
      quiet = 0;
      break;
      
    default:
      return ARGP_ERR_UNKNOWN;
    }
  return 0;
}


/* General-purpose data structures */
struct burst_map
{
  int mime;            /* Is mime? */
  size_t msgno;        /* Number of the original message */
  /* Following numbers refer to tmpbox */
  size_t first;        /* Number of the first bursted message */
  size_t count;        /* Number of bursted messages */
};


/* Global data */
struct burst_map map;        /* Currently built map */
struct burst_map *burst_map; /* Finished burst map */
size_t burst_count;          /* Number of items in burst_map */
mu_mailbox_t tmpbox;         /* Temporary mailbox */
struct obstack stk;          /* Stack for building burst_map, etc. */

static int burst_or_copy (mu_message_t msg, int recursive, int copy);


/* MIME messages */
int 
burst_mime (mu_message_t msg)
{
  size_t i, nparts;
  
  mu_message_get_num_parts (msg, &nparts);

  for (i = 1; i <= nparts; i++)
    {
      mu_message_t mpart;
      if (mu_message_get_part (msg, i, &mpart) == 0)
	{
	  if (!map.first)
	    mu_mailbox_uidnext (tmpbox, &map.first);
	  burst_or_copy (mpart, recursive, 1);
	}
    }
  return 0;
}


/* Digest messages */

/* Bursting FSA states accoring to RFC 934:
   
      S1 ::   "-" S3
            | CRLF {CRLF} S1
            | c {c} S2

      S2 ::   CRLF {CRLF} S1
            | c {c} S2

      S3 ::   " " S2
            | c S4     ;; the bursting agent should consider the current
	               ;; message ended.  

      S4 ::   CRLF S5
            | c S4

      S5 ::   CRLF S5
            | c {c} S2 ;; The bursting agent should consider a new
	               ;; message started
*/

#define S1 1
#define S2 2
#define S3 3
#define S4 4
#define S5 5

/* Negative state means no write */
int transtab[][4] = {
/*          DEF    '\n'   ' '   '-' */
/* S1 */ {  S2,    S1,    S2,   -S3 },
/* S2 */ {  S2,    S1,    S2,    S2 },
/* S3 */ { -S4,   -S4,   -S2,   -S4 }, 
/* S4 */ { -S4,   -S5,   -S4,   -S4 },
/* S5 */ {  S2,   -S5,    S2,    S2 }
};

static int
token_num(int c)
{
  switch (c)
    {
    case '\n':
      return 1;
    case ' ':
      return 2;
    case '-':
      return 3;
    default:
      return 0;
    }
}

#define F_FIRST  0x01  /* First part of the message (no EB seen so far) */
#define F_ENCAPS 0x02  /* Within encapsulated part */

struct burst_stream
{
  mu_stream_t stream;  /* Output stream */
  int flags;           /* See F_ flags above */
  size_t msgno;        /* Number of the current message */
  size_t partno;       /* Number of the part within the message */
};

static void
finish_stream (struct burst_stream *bs)
{
  if (bs->stream)
    {
      mu_message_t msg;
      
      mu_stream_seek (bs->stream, 0, SEEK_SET, NULL);
      msg = mh_stream_to_message (bs->stream);
      if (!map.first)
	mu_mailbox_uidnext (tmpbox, &map.first);
      burst_or_copy (msg, recursive, 1);
      mu_message_destroy (&msg, mu_message_get_owner (msg));
      mu_stream_unref (bs->stream);
      bs->stream = 0;
      
      bs->partno++;
      bs->flags &= ~F_FIRST;
    }
}  

static void
flush_stream (struct burst_stream *bs, char *buf, size_t size)
{
  int rc;

  if (size == 0)
    return;
  if (!bs->stream)
    {
      if ((rc = mu_temp_file_stream_create (&bs->stream, NULL))) 
	{
	  mu_error (_("Cannot open temporary file: %s"),
		    mu_strerror (rc));
	  exit (1);
	}
      mu_stream_printf (bs->stream, "X-Burst-Part: %lu %lu %02x\n",
			(unsigned long) bs->msgno,
			(unsigned long) bs->partno, bs->flags);
      if (!bs->flags)
	mu_stream_write (bs->stream, "\n", 1, NULL);

      if (verbose && !inplace)
	{
	  size_t nextuid;
	  mu_mailbox_uidnext (tmpbox, &nextuid);
	  printf (_("message %lu of digest %lu becomes message %lu\n"),
		  (unsigned long) bs->partno,
		  (unsigned long) bs->msgno,
		  (unsigned long) nextuid);
	}
    }
  rc = mu_stream_write (bs->stream, buf, size, NULL);
  if (rc)
    {
      mu_error (_("error writing temporary stream: %s"),
		mu_strerror (rc));
      exit (1); /* FIXME: better error handling please */
    }
}

/* Burst an RFC 934 digest.  Return 0 if OK, 1 if the message is not
   a valid digest.
   FIXME: On errors, cleanup and return -1.
*/
int
burst_digest (mu_message_t msg)
{
  mu_stream_t is;
  char c;
  size_t n;
  int state = S1;
  int eb_length = 0;
  struct burst_stream bs;
  int result;
  
  bs.stream = NULL;
  bs.flags = F_FIRST;
  bs.partno = 1;
  mh_message_number (msg, &bs.msgno);
  
  mu_message_get_streamref (msg, &is);
  while (mu_stream_read (is, &c, 1, &n) == 0 && n == 1)
    {
      int newstate = transtab[state - 1][token_num (c)];
      int silent = 0;
      
      if (newstate < 0)
	{
	  newstate = -newstate;
	  silent = 1;
	}

      if (state == S1)
	{
	  /* GNU extension: check if we have seen enough dashes to
	     constitute a valid encapsulation boundary. */
	  if (newstate == S3)
	    {
	      eb_length++;
	      if (eb_length < eb_min_length)
		continue; /* Ignore state change */
	      if (eb_min_length > 1)
		{
		  newstate = S4;
		  finish_stream (&bs);
		  bs.flags ^= F_ENCAPS;
		}
	    }
	  else
	    for (; eb_length; eb_length--)
	      flush_stream (&bs, "-", 1);
	  eb_length = 0;
	}
      else if (state == S5 && newstate == S2)
	{
	  /* As the automaton traverses from state S5 to S2, the
	     bursting agent should consider a new message started
	     and output the first character. */
	  finish_stream (&bs);
	}
      else if (state == S3 && newstate == S4)
	{
	  /* As the automaton traverses from state S3 to S4, the
	     bursting agent should consider the current message ended. */
	  finish_stream (&bs);
	  bs.flags ^= F_ENCAPS;
	}
      state = newstate;
      if (!silent)
	flush_stream (&bs, &c, 1);
    }
  mu_stream_destroy (&is);

  if (bs.flags == F_FIRST)
    {
      mu_stream_destroy (&bs.stream);
      result = 1;
    }
  else if (bs.stream)
    {
      mu_off_t size = 0;
      mu_stream_size (bs.stream, &size);
      if (size)
	finish_stream (&bs);
      else
	mu_stream_destroy (&bs.stream);
      result = 0;
    }
  return result;
}


int
burst_or_copy (mu_message_t msg, int recursive, int copy)
{
  if (recursive)
    {
      int mime = 0;
      mu_message_is_multipart (msg, &mime);
  
      if (mime)
	{
	  if (!map.first)
	    map.mime = 1;
	  return burst_mime (msg);
	}
      else if (burst_digest (msg) == 0)
	return 0;
    }

  if (copy)
    {
      int rc;
      
      if (map.mime)
	{
	  mu_header_t hdr;
	  char *value = NULL;
	  
	  mu_message_get_header (msg, &hdr);
	  if (mu_header_aget_value (hdr, MU_HEADER_CONTENT_TYPE, &value) == 0
	      && memcmp (value, "message/rfc822", 14) == 0)
	    {
	      mu_stream_t str;
	      mu_body_t body;
	      
	      mu_message_get_body (msg, &body);
	      mu_body_get_streamref (body, &str);
	      msg = mh_stream_to_message (str);
	    }
	  free (value);
	}

      /* FIXME:
	 if (verbose && !inplace)
	   printf(_("message %lu of digest %lu becomes message %s"),
		   (unsigned long) (j+1),
		   (unsigned long) burst_map[i].msgno, to));
      */     

      rc = mu_mailbox_append_message (tmpbox, msg);
      if (rc)
	{
	  mu_error (_("cannot append message: %s"), mu_strerror (rc));
	  exit (1);
	}
      map.count++;
      return 0;
    }      
	      
  return 1;
}

void
burst (mu_mailbox_t mbox, mu_message_t msg, size_t num, void *data)
{
  memset (&map, 0, sizeof (map));
  mh_message_number (msg, &map.msgno);
  
  if (burst_or_copy (msg, 1, 0) == 0)
    {
      VERBOSE((ngettext ("%s message exploded from digest %s",
			 "%s messages exploded from digest %s",
			 (unsigned long) map.count),
	       mu_umaxtostr (0, map.count),
	       mu_umaxtostr (1, num)));
      if (inplace)
	{
	  obstack_grow (&stk, &map, sizeof map);
	  burst_count++;
	}
    }
  else if (!quiet)
    mu_error (_("message %s not in digest format"), mu_umaxtostr (0, num));
}


/* Inplace handling */

void
burst_rename (mh_msgset_t *ms, size_t lastuid)
{
  size_t i, j;

  VERBOSE ((_("Renaming messages")));
  j = burst_count - 1;
  for (i = ms->count; i > 0; i--)
    {
      const char *from;
      const char *to;

      if (ms->list[i-1] == burst_map[j].msgno)
	{
	  lastuid -= burst_map[j].count;
	  burst_map[j].msgno = lastuid;
	  j--;
	}

      if (ms->list[i-1] == lastuid)
	continue;
      
      from = mu_umaxtostr (0, ms->list[i-1]);
      to   = mu_umaxtostr (1, lastuid);
      --lastuid;

      VERBOSE((_("message %s becomes message %s"), from, to));
	       
      if (rename (from, to))
	{
	  mu_error (_("error renaming %s to %s: %s"),
		    from, to, mu_strerror (errno));
	  exit (1);
	}
    }
}  

void
msg_copy (size_t num, const char *file)
{
  mu_message_t msg;
  mu_attribute_t attr = NULL;
  mu_stream_t istream, ostream;
  int rc;
  
  if ((rc = mu_file_stream_create (&ostream,
				   file,
				   MU_STREAM_WRITE|MU_STREAM_CREAT))) 
    {
      mu_error (_("Cannot open output file `%s': %s"),
		file, mu_strerror (rc));
      exit (1);
    }

  mu_mailbox_get_message (tmpbox, num, &msg);
  mu_message_get_streamref (msg, &istream);
  rc = mu_stream_copy (ostream, istream, 0, NULL);
  if (rc)
    {
      mu_error (_("copy stream error: %s"), mu_strerror (rc));
      exit (1);
    }
  
  mu_stream_destroy (&istream);

  mu_stream_close (ostream);
  mu_stream_destroy (&ostream);

  /* Mark message as deleted */
  mu_message_get_attribute (msg, &attr);
  mu_attribute_set_deleted (attr);
}

void
finalize_inplace (size_t lastuid)
{
  size_t i;

  VERBOSE ((_("Moving bursted out messages in place")));

  for (i = 0; i < burst_count; i++)
    {
      size_t j;

      /* FIXME: toc handling */
      for (j = 0; j < burst_map[i].count; j++)
	{
	  const char *to = mu_umaxtostr (0, burst_map[i].msgno + 1 + j);
	  VERBOSE((_("message %s of digest %s becomes message %s"),
		   mu_umaxtostr (1, j + 1),
		   mu_umaxtostr (2, burst_map[i].msgno), to));
	  msg_copy (burst_map[i].first + j, to);
	}
    }
}

int
main (int argc, char **argv)
{
  int index, rc;
  mu_mailbox_t mbox;
  mh_msgset_t msgset;
  const char *tempfolder = mh_global_profile_get ("Temp-Folder", ".temp");
  
  /* Native Language Support */
  MU_APP_INIT_NLS ();

  mh_argp_init ();
  mh_argp_parse (&argc, &argv, 0, options, mh_option, args_doc, doc,
		 opt_handler, NULL, &index);

  argc -= index;
  argv += index;

  VERBOSE ((_("Opening folder `%s'"), mh_current_folder ()));
  mbox = mh_open_folder (mh_current_folder (), 0);
  mh_msgset_parse (mbox, &msgset, argc, argv, "cur");

  if (inplace)
    {
      size_t i, count;
      
      VERBOSE ((_("Opening temporary folder `%s'"), tempfolder));
      tmpbox = mh_open_folder (tempfolder, 1);
      VERBOSE ((_("Cleaning up temporary folder")));
      mu_mailbox_messages_count (tmpbox, &count);
      for (i = 1; i <= count; i++)
	{
	  mu_attribute_t attr = NULL;
	  mu_message_t msg = NULL;
	  mu_mailbox_get_message (tmpbox, i, &msg);
	  mu_message_get_attribute (msg, &attr);
	  mu_attribute_set_deleted (attr);
	}
      mu_mailbox_expunge (tmpbox);
      obstack_init (&stk);
    }
  else
    tmpbox = mbox;

  rc = mh_iterate (mbox, &msgset, burst, NULL);
  if (rc)
    return rc;

  if (inplace && burst_count)
    {
      mu_url_t dst_url = NULL;
      size_t i, next_uid, last_uid;
      mh_msgset_t ms;
      char *xargv[2];
      const char *dir;
      
      burst_map = obstack_finish (&stk);

      mu_mailbox_uidnext (mbox, &next_uid);
      for (i = 0, last_uid = next_uid-1; i < burst_count; i++)
	last_uid += burst_map[i].count;
      VERBOSE ((_("Estimated last UID: %s"), mu_umaxtostr (0, last_uid)));

      mu_asprintf (&xargv[0], "%s-last", mu_umaxtostr (0, burst_map[0].msgno));
      xargv[1] = NULL;
      mh_msgset_parse (mbox, &ms, 1, xargv, NULL);
      free (xargv[0]);
      mh_msgset_uids (mbox, &ms);
	
      mu_mailbox_get_url (mbox, &dst_url);
      mu_url_sget_path (dst_url, &dir);
      VERBOSE ((_("changing to `%s'"), dir));
      if (chdir (dir))
	{
	  mu_error (_("cannot change to `%s': %s"), dir, mu_strerror (errno));
	  exit (1);
	}
      mu_mailbox_close (mbox);

      burst_rename (&ms, last_uid);
      mh_msgset_free (&ms);

      finalize_inplace (last_uid);

      VERBOSE ((_("Expunging temporary folder")));
      mu_mailbox_expunge (tmpbox);
      mu_mailbox_close (tmpbox);
      mu_mailbox_destroy (&tmpbox);
    }
  else
    mu_mailbox_close (mbox);

  mu_mailbox_destroy (&mbox);
  VERBOSE ((_("Finished bursting")));
  return rc;
}