movemail.c 12.4 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
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 2003, 2005, 2006, 2007, 2008,
   2009 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, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
   MA 02110-1301 USA */

#if defined(HAVE_CONFIG_H)
# include <config.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <grp.h>
#include <unistd.h>
#include <mailutils/mailutils.h>
#include <mailutils/tls.h>
#include <mu_asprintf.h>
#include "mailutils/libargp.h"
#include <muaux.h>

const char *program_version = "movemail (" PACKAGE_STRING ")";
static char doc[] = N_("GNU movemail");
static char args_doc[] = N_("inbox-url destfile [POP-password]");

#define OPT_EMACS 256

static struct argp_option options[] = {
  { "preserve", 'p', NULL, 0, N_("Preserve the source mailbox"), 0 },
  { "keep-messages", 0, NULL, OPTION_ALIAS, NULL },
  { "reverse",  'r', NULL, 0, N_("Reverse the sorting order"), 0 },
  { "emacs", OPT_EMACS, NULL, 0,
    N_("Output information used by Emacs rmail interface"), 0 },
  { "copy-permissions", 'P', NULL, 0,
    N_("Copy original mailbox permissions and ownership when applicable"),
    0 },
  { "uidl", 'u', NULL, 0,
    N_("Use UIDLs to avoid downloading the same message twice"),
    0 },
  { "verbose", 'v', NULL, 0,
    N_("Increase verbosity level"),
    0 },
  { NULL,      0, NULL, 0, NULL, 0 }
};

static int reverse_order;
static int preserve_mail; 
static int emacs_mode;
static int copy_meta;
static int uidl_option;
static int verbose_option;

static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
  static struct mu_argp_node_list lst;

  switch (key)
    {
    case 'r':
      mu_argp_node_list_new (&lst, "reverse", "yes");
      break;

    case 'p':
      mu_argp_node_list_new (&lst, "preserve", "yes");
      break;

    case 'P':
      copy_meta = 1;
      break;

    case 'u':
      mu_argp_node_list_new (&lst, "uidl", "yes");
      break;

    case 'v':
      verbose_option++;
      break;
      
    case OPT_EMACS:
      mu_argp_node_list_new (&lst, "emacs", "yes");
      break;
      
    case ARGP_KEY_INIT:
      mu_argp_node_list_init (&lst);
      break;
      
    case ARGP_KEY_FINI:
      mu_argp_node_list_finish (&lst, NULL, NULL);
      break;
      
    default:
      return ARGP_ERR_UNKNOWN;
    }
  return 0;
}

static struct argp argp = {
  options,
  parse_opt,
  args_doc,
  doc,
  NULL,
  NULL, NULL
};


struct mu_cfg_param movemail_cfg_param[] = {
  { "preserve", mu_cfg_bool, &preserve_mail, 0, NULL,
    N_("Do not remove messages from the source mailbox.") },
  { "reverse",  mu_cfg_bool, &reverse_order, 0, NULL,
    N_("Reverse message sorting order.") },
  { "emacs", mu_cfg_bool, &emacs_mode, 0, NULL,
    N_("Output information used by Emacs rmail interface.") },
  { "uidl", mu_cfg_bool, &uidl_option, 0, NULL,
    N_("Use UIDLs to avoid downloading the same message twice.") },
  { "verbose", mu_cfg_int, &verbose_option, 0, NULL,
    N_("Increase verbosity level.") },
  { NULL }
};


static const char *movemail_capa[] = {
  "common",
  "debug",
  "license",
  "locking",
  "mailbox",
  "auth",
  NULL 
};

void
die (mu_mailbox_t mbox, const char *msg, int status)
{
  mu_url_t url = NULL;
  
  mu_mailbox_get_url (mbox, &url);
  if (emacs_mode)
    mu_error (_("%s:mailbox `%s': %s: %s"),
	      mu_errname (status),
	      mu_url_to_string (url),
	      msg,
	      mu_strerror (status));
  else
    mu_error (_("mailbox `%s': %s: %s"),
	      mu_url_to_string (url), msg, mu_strerror (status));
  exit (1);
}

void
lock_mailbox (mu_mailbox_t mbox)
{
  mu_locker_t lock;
  int status;
  
  status = mu_mailbox_get_locker (mbox, &lock);
  if (status)
    die (mbox, _("Cannot retrieve locker"), status);
      
  if (!lock)
    /* Remote mailboxes have no lockers */
    return;

  status = mu_locker_lock (lock);

  if (status)
    die (mbox, _("Cannot lock"), status);
}


void
attach_passwd_ticket (mu_mailbox_t mbx, char *passwd)
{
  mu_folder_t folder = NULL;
  mu_authority_t auth = NULL;
  mu_secret_t secret;
  mu_ticket_t t;
  int rc;

  rc = mu_secret_create (&secret, passwd, strlen (passwd));
  if (rc)
    {
      mu_error ("mu_secret_create: %s", mu_strerror (rc));
      exit (1);
    }
  
  mu_ticket_create (&t, NULL);
  mu_ticket_set_secret (t, secret);

  if ((rc = mu_mailbox_get_folder (mbx, &folder)))
    die (mbx, _("mu_mailbox_get_folder failed"), rc);

  if ((rc = mu_folder_get_authority (folder, &auth)))
    die (mbx, _("mu_folder_get_authority failed"), rc);

  if (auth && (rc = mu_authority_set_ticket (auth, t)))
    die (mbx, _("mu_authority_set_ticket failed"), rc);
}


/* Create and open a mailbox associated with the given URL,
   flags and (optionally) password */
void
open_mailbox (mu_mailbox_t *mbx, char *name, int flags, char *passwd)
{
  int status = mu_mailbox_create_default (mbx, name);

  if (status)
    {
      if (name)
	mu_error (_("Could not create mailbox `%s': %s"),
		  name,
		  mu_strerror (status));
      else
	mu_error (_("Could not create default mailbox: %s"),
		  mu_strerror (status));
      exit (1);
    }

  if (passwd)
    attach_passwd_ticket (*mbx, passwd);
  status = mu_mailbox_open (*mbx, flags);
  if (status)
    die (*mbx, _("Cannot open"), status);
  lock_mailbox (*mbx);
}

int
move_message (mu_mailbox_t src, mu_mailbox_t dst, size_t msgno)
{
  int rc;
  mu_message_t msg;

  if ((rc = mu_mailbox_get_message (src, msgno, &msg)) != 0)
    {
      mu_error (_("Cannot read message %lu: %s"),
		(unsigned long) msgno, mu_strerror (rc));
      return rc;
    }
  if ((rc = mu_mailbox_append_message (dst, msg)) != 0)
    {
      mu_error (_("Cannot append message %lu: %s\n"),
		(unsigned long) msgno, mu_strerror (rc));
      return rc;
    }
  if (!preserve_mail)
    {
      mu_attribute_t attr;
      mu_message_get_attribute (msg, &attr);
      mu_attribute_set_deleted (attr);
    }
  return rc;
}

/* Open source mailbox using compatibility syntax. Source_name is
   of the form:

     po:USERNAME[:POP-SERVER]

   if POP-SERVER part is omitted, the MAILHOST environment variable
   will be consulted. */
void
compatibility_mode (mu_mailbox_t *mbx, char *source_name, char *password,
		    int flags)
{
  char *tmp;
  char *user_name = strtok (source_name+3, ":");
  char *host = strtok (NULL, ":");
  if (!host)
    host = getenv ("MAILHOST");
  if (!host)
    {
      mu_error (_("Hostname of the POP3 server is unknown"));
      exit (1);
    }
  asprintf (&tmp, "pop://%s@%s", user_name, host);
  open_mailbox (mbx, tmp, flags, password);
  free (tmp);
}

static mu_mailbox_t source, dest;

static void
close_mailboxes (void)
{
  mu_mailbox_close (dest);
  mu_mailbox_close (source);
}  

static void
set_permissions (mu_mailbox_t mbox)
{
  mu_url_t url = NULL;
  const char *s;
  int rc;
  uid_t uid;
  gid_t gid;
  
  if (getuid () != 0)
    {
      mu_error (_("must be root to use --copy-permissions"));
      exit (1);
    }
  mu_mailbox_get_url (mbox, &url);
  rc = mu_url_sget_scheme  (url, &s);
  if (rc)
    die (mbox, _("Cannot get scheme"), rc);
  if (strcmp (s, "/") == 0
      || strcmp (s, "mbox") == 0
      || strcmp (s, "mh") == 0
      || strcmp (s, "maildir") == 0)
    {
      struct stat st;
      
      rc = mu_url_sget_path  (url, &s);
      if (rc)
	die (mbox, _("Cannot get path"), rc);
      if (stat (s, &st))
	{
	  mu_error (_("Cannot stat mailbox `%s': %s"), s,
		    mu_strerror (errno));
	  exit (1);
	}
      uid = st.st_uid;
      gid = st.st_gid;
    }
  else
    {
      struct mu_auth_data *auth;
      
      rc = mu_url_sget_user (url, &s);
      if (rc)
	die (mbox, _("Cannot get user"), rc);
      
      auth = mu_get_auth_by_name (s);
      if (!auth)
	{
	  mu_error (_("No such user: %s"), s);
	  exit (1);
	}
      else
	{
	  uid = auth->uid;
	  gid = auth->gid;
	}
      mu_auth_data_free (auth);
    }

  if (mu_switch_to_privs (uid, gid, NULL))
    exit (1);
}

static int
_compare_uidls (const void *item, const void *value)
{
  const struct mu_uidl *a = item;
  const struct mu_uidl *b = value;

  return strcmp (a->uidl, b->uidl);
}

static int
_compare_msgno (const void *item, const void *value)
{
  const struct mu_uidl *a = item;
  const struct mu_uidl *b = value;

  if (a->msgno < b->msgno)
    return -1;
  if (a->msgno > b->msgno)
    return 1;
  return 0;
}

static int
msgno_in_list (mu_list_t list, size_t num)
{
  struct mu_uidl t;
  t.msgno = num;
  return mu_list_locate (list, &t, NULL) == 0;
}  

int
main (int argc, char **argv)
{
  int index;
  size_t i, total;
  int rc = 0;
  char *source_name, *dest_name;
  int flags;
  mu_list_t src_uidl_list = NULL;
  size_t msg_count = 0;
  
  /* Native Language Support */
  MU_APP_INIT_NLS ();
  MU_AUTH_REGISTER_ALL_MODULES ();
  
  /* Register the desired mailbox formats.  */
  mu_register_all_mbox_formats ();

  /* argument parsing */
  
#ifdef WITH_TLS
  mu_gocs_register ("tls", mu_tls_module_init);
#endif
  mu_argp_init (program_version, NULL);
  if (mu_app_init (&argp, movemail_capa, movemail_cfg_param, 
		   argc, argv, 0, &index, NULL))
    exit (1);

  argc -= index;
  argv += index;

  if (argc < 2 || argc > 3)
    {
      mu_error (_("Wrong number of arguments"));
      return 1;
    }

  atexit (close_mailboxes);
  
  source_name = argv[0];
  dest_name = argv[1];

  flags = preserve_mail ? MU_STREAM_READ : MU_STREAM_RDWR;
  
  if (strncmp (source_name, "po:", 3) == 0)
    compatibility_mode (&source, source_name, argv[2], flags);
  else
    open_mailbox (&source, source_name, flags, argv[2]);

  if (copy_meta) 
    set_permissions (source);
  
  open_mailbox (&dest, dest_name, MU_STREAM_RDWR | MU_STREAM_CREAT, NULL);

  rc = mu_mailbox_messages_count (source, &total);
  if (rc)
    {
      mu_error(_("Cannot count messages: %s"), mu_strerror (rc));
      exit (1);
    }
  
  if (verbose_option)
    mu_diag_output (MU_DIAG_INFO,
		    _("Number of messages in source mailbox: %lu"),
		    (unsigned long) total);

  if (uidl_option)
    {
      mu_iterator_t itr;
      mu_list_t dst_uidl_list = NULL;

      rc = mu_mailbox_get_uidls (source, &src_uidl_list);
      if (rc)
	die (source, _("Cannot get UIDLs"), rc);
      rc = mu_mailbox_get_uidls (dest, &dst_uidl_list);
      if (rc)
	die (dest, _("Cannot get UIDLs"), rc);

      mu_list_set_comparator (src_uidl_list, NULL);
      mu_list_set_comparator (dst_uidl_list, _compare_uidls);
      
      mu_list_get_iterator (src_uidl_list, &itr);
      for (mu_iterator_first (itr); !mu_iterator_is_done (itr);
	   mu_iterator_next (itr))
	{
	  struct mu_uidl *uidl;
	      
	  mu_iterator_current (itr, (void **)&uidl);
	  if (mu_list_locate (dst_uidl_list, uidl, NULL) == 0)
	    mu_list_remove (src_uidl_list, uidl);
	}
      mu_iterator_destroy (&itr);
      mu_list_destroy (&dst_uidl_list);
      mu_list_set_comparator (src_uidl_list, _compare_msgno);
    }
  
  if (reverse_order)
    {
      for (i = total; i > 0; i--)
	{
	  if (src_uidl_list && !msgno_in_list (src_uidl_list, i))
	    {
	      if (verbose_option > 1)
		mu_diag_output (MU_DIAG_INFO, _("Ignoring message %lu"),
				(unsigned long) i);
	      continue;
	    }
	  rc = move_message (source, dest, i);
	  if (rc == 0)
	    msg_count++;
	  else
	    break;
	}
    }
  else
    {
      for (i = 1; i <= total; i++)
	{
	  if (src_uidl_list && !msgno_in_list (src_uidl_list, i))
	    {
	      if (verbose_option > 1)
		mu_diag_output (MU_DIAG_INFO, _("Ignoring message %lu"),
				(unsigned long) i);
	      continue;
	    }
	  rc = move_message (source, dest, i);
	  if (rc == 0)
	    msg_count++;
	  else
	    break;
	}
    }
  
  if (verbose_option)
    mu_diag_output (MU_DIAG_INFO,
		    _("Number of processed messages: %lu"),
		    (unsigned long) msg_count);
  
  if (rc)
    return rc;
  
  mu_mailbox_sync (dest);
  rc = mu_mailbox_close (dest);
  mu_mailbox_destroy (&dest);
  if (rc)
    mu_error (_("Cannot close destination mailbox: %s"), mu_strerror (rc));
  else
    mu_mailbox_flush (source, 1);

  mu_mailbox_close (source);
  mu_mailbox_destroy (&source);

  return rc;
}