sendlib.c 69.8 KB
Newer Older
Thomas Roessler's avatar
Thomas Roessler committed
1
/*
2
 * Copyright (C) 1996-2002,2009-2012 Michael R. Elkins <me@mutt.org>
3
 *
Thomas Roessler's avatar
Thomas Roessler committed
4 5 6 7
 *     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.
8
 *
Thomas Roessler's avatar
Thomas Roessler committed
9 10 11 12
 *     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.
13
 *
Thomas Roessler's avatar
Thomas Roessler committed
14 15
 *     You should have received a copy of the GNU General Public License
 *     along with this program; if not, write to the Free Software
16
 *     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17
 */
Thomas Roessler's avatar
Thomas Roessler committed
18

19 20
#define _SENDLIB_C 1

21 22 23 24
#if HAVE_CONFIG_H
# include "config.h"
#endif

Thomas Roessler's avatar
Thomas Roessler committed
25 26 27
#include "mutt.h"
#include "mutt_curses.h"
#include "rfc2047.h"
Thomas Roessler's avatar
Thomas Roessler committed
28
#include "rfc2231.h"
Thomas Roessler's avatar
Thomas Roessler committed
29 30 31 32
#include "mx.h"
#include "mime.h"
#include "mailbox.h"
#include "copy.h"
33
#include "pager.h"
34
#include "charset.h"
35
#include "mutt_crypt.h"
36
#include "mutt_idna.h"
37
#include "buffy.h"
38

Thomas Roessler's avatar
Thomas Roessler committed
39 40 41 42 43 44 45 46 47 48
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <sys/stat.h>
#include <signal.h>
#include <sys/wait.h>
#include <fcntl.h>

Thomas Roessler's avatar
Thomas Roessler committed
49 50
#ifdef HAVE_SYSEXITS_H
#include <sysexits.h>
Thomas Roessler's avatar
Thomas Roessler committed
51 52
#else /* Make sure EX_OK is defined <philiph@pobox.com> */
#define EX_OK 0
Thomas Roessler's avatar
Thomas Roessler committed
53
#endif
Thomas Roessler's avatar
Thomas Roessler committed
54

55
/* If you are debugging this file, comment out the following line. */
56
#define NDEBUG
57 58 59 60 61 62 63

#ifdef NDEBUG
#define assert(x)
#else
#include <assert.h>
#endif

64 65
extern char RFC822Specials[];

66
const char MimeSpecials[] = "@.,;:<>[]\\\"()?/= \t";
Thomas Roessler's avatar
Thomas Roessler committed
67

68
const char B64Chars[64] = {
Thomas Roessler's avatar
Thomas Roessler committed
69 70 71 72 73 74 75 76 77 78 79
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
  'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
  't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
  '8', '9', '+', '/'
};

static char MsgIdPfx = 'A';

static void transform_to_7bit (BODY *a, FILE *fpin);

80
static void encode_quoted (FGETCONV * fc, FILE *fout, int istext)
Thomas Roessler's avatar
Thomas Roessler committed
81 82 83 84
{
  int c, linelen = 0;
  char line[77], savechar;

85
  while ((c = fgetconv (fc)) != EOF)
Thomas Roessler's avatar
Thomas Roessler committed
86 87 88 89 90 91 92 93 94 95 96
  {
    /* Wrap the line if needed. */
    if (linelen == 76 && ((istext && c != '\n') || !istext))
    {
      /* If the last character is "quoted", then be sure to move all three
       * characters to the next line.  Otherwise, just move the last
       * character...
       */
      if (line[linelen-3] == '=')
      {
        line[linelen-3] = 0;
97
        fputs (line, fout);
Thomas Roessler's avatar
Thomas Roessler committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
        fputs ("=\n", fout);
        line[linelen] = 0;
        line[0] = '=';
        line[1] = line[linelen-2];
        line[2] = line[linelen-1];
        linelen = 3;
      }
      else
      {
        savechar = line[linelen-1];
        line[linelen-1] = '=';
        line[linelen] = 0;
        fputs (line, fout);
        fputc ('\n', fout);
        line[0] = savechar;
        linelen = 1;
      }
    }

Thomas Roessler's avatar
Thomas Roessler committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    /* Escape lines that begin with/only contain "the message separator". */
    if (linelen == 4 && !mutt_strncmp ("From", line, 4))
    {
      strfcpy (line, "=46rom", sizeof (line));
      linelen = 6;
    }
    else if (linelen == 4 && !mutt_strncmp ("from", line, 4))
    {
      strfcpy (line, "=66rom", sizeof (line));
      linelen = 6;
    }
    else if (linelen == 1 && line[0] == '.')
    {
      strfcpy (line, "=2E", sizeof (line));
      linelen = 3;
    }


Thomas Roessler's avatar
Thomas Roessler committed
135 136 137
    if (c == '\n' && istext)
    {
      /* Check to make sure there is no trailing space on this line. */
Thomas Roessler's avatar
Thomas Roessler committed
138
      if (linelen > 0 && (line[linelen-1] == ' ' || line[linelen-1] == '\t'))
Thomas Roessler's avatar
Thomas Roessler committed
139 140 141
      {
        if (linelen < 74)
	{
Thomas Roessler's avatar
Thomas Roessler committed
142
          sprintf (line+linelen-1, "=%2.2X", (unsigned char) line[linelen-1]);
Thomas Roessler's avatar
Thomas Roessler committed
143 144 145 146 147 148 149 150 151
          fputs (line, fout);
        }
        else
	{
          int savechar = line[linelen-1];

          line[linelen-1] = '=';
          line[linelen] = 0;
          fputs (line, fout);
Thomas Roessler's avatar
Thomas Roessler committed
152
          fprintf (fout, "\n=%2.2X", (unsigned char) savechar);
Thomas Roessler's avatar
Thomas Roessler committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
        }
      }
      else
      {
        line[linelen] = 0;
        fputs (line, fout);
      }
      fputc ('\n', fout);
      linelen = 0;
    }
    else if (c != 9 && (c < 32 || c > 126 || c == '='))
    {
      /* Check to make sure there is enough room for the quoted character.
       * If not, wrap to the next line.
       */
      if (linelen > 73)
      {
        line[linelen++] = '=';
        line[linelen] = 0;
        fputs (line, fout);
        fputc ('\n', fout);
        linelen = 0;
      }
Thomas Roessler's avatar
Thomas Roessler committed
176
      sprintf (line+linelen,"=%2.2X", (unsigned char) c);
Thomas Roessler's avatar
Thomas Roessler committed
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
      linelen += 3;
    }
    else
    {
      /* Don't worry about wrapping the line here.  That will happen during
       * the next iteration when I'll also know what the next character is.
       */
      line[linelen++] = c;
    }
  }

  /* Take care of anything left in the buffer */
  if (linelen > 0)
  {
    if (line[linelen-1] == ' ' || line[linelen-1] == '\t')
    {
      /* take care of trailing whitespace */
      if (linelen < 74)
Thomas Roessler's avatar
Thomas Roessler committed
195
        sprintf (line+linelen-1, "=%2.2X", (unsigned char) line[linelen-1]);
Thomas Roessler's avatar
Thomas Roessler committed
196 197 198 199 200 201 202
      else
      {
        savechar = line[linelen-1];
        line[linelen-1] = '=';
        line[linelen] = 0;
        fputs (line, fout);
        fputc ('\n', fout);
Thomas Roessler's avatar
Thomas Roessler committed
203
        sprintf (line, "=%2.2X", (unsigned char) savechar);
Thomas Roessler's avatar
Thomas Roessler committed
204 205 206 207 208 209 210 211
      }
    }
    else
      line[linelen] = 0;
    fputs (line, fout);
  }
}

212 213 214 215 216
static char b64_buffer[3];
static short b64_num;
static short b64_linelen;

static void b64_flush(FILE *fout)
Thomas Roessler's avatar
Thomas Roessler committed
217
{
218
  short i;
Thomas Roessler's avatar
Thomas Roessler committed
219

220 221 222 223
  if(!b64_num)
    return;

  if(b64_linelen >= 72)
Thomas Roessler's avatar
Thomas Roessler committed
224
  {
225 226 227
    fputc('\n', fout);
    b64_linelen = 0;
  }
228

229 230
  for(i = b64_num; i < 3; i++)
    b64_buffer[i] = '\0';
231 232

  fputc(B64Chars[(b64_buffer[0] >> 2) & 0x3f], fout);
233 234 235
  b64_linelen++;
  fputc(B64Chars[((b64_buffer[0] & 0x3) << 4) | ((b64_buffer[1] >> 4) & 0xf) ], fout);
  b64_linelen++;
236

237 238 239 240 241
  if(b64_num > 1)
  {
    fputc(B64Chars[((b64_buffer[1] & 0xf) << 2) | ((b64_buffer[2] >> 6) & 0x3) ], fout);
    b64_linelen++;
    if(b64_num > 2)
Thomas Roessler's avatar
Thomas Roessler committed
242
    {
243 244
      fputc(B64Chars[b64_buffer[2] & 0x3f], fout);
      b64_linelen++;
Thomas Roessler's avatar
Thomas Roessler committed
245 246
    }
  }
247

248 249 250 251 252
  while(b64_linelen % 4)
  {
    fputc('=', fout);
    b64_linelen++;
  }
253

254 255
  b64_num = 0;
}
256 257


258 259 260 261
static void b64_putc(char c, FILE *fout)
{
  if(b64_num == 3)
    b64_flush(fout);
262

263 264
  b64_buffer[b64_num++] = c;
}
265 266


267
static void encode_base64 (FGETCONV * fc, FILE *fout, int istext)
268 269
{
  int ch, ch1 = EOF;
270

271
  b64_num = b64_linelen = 0;
272

273
  while ((ch = fgetconv (fc)) != EOF)
274
  {
275
    if (istext && ch == '\n' && ch1 != '\r')
276 277 278 279 280
      b64_putc('\r', fout);
    b64_putc(ch, fout);
    ch1 = ch;
  }
  b64_flush(fout);
Thomas Roessler's avatar
Thomas Roessler committed
281 282 283
  fputc('\n', fout);
}

284
static void encode_8bit (FGETCONV *fc, FILE *fout, int istext)
285
{
286
  int ch;
287

288 289
  while ((ch = fgetconv (fc)) != EOF)
    fputc (ch, fout);
290
}
291

292

Thomas Roessler's avatar
Thomas Roessler committed
293 294 295 296 297 298 299 300
int mutt_write_mime_header (BODY *a, FILE *f)
{
  PARAMETER *p;
  char buffer[STRING];
  char *t;
  char *fn;
  int len;
  int tmplen;
Thomas Roessler's avatar
Thomas Roessler committed
301
  int encode;
302

Thomas Roessler's avatar
Thomas Roessler committed
303
  fprintf (f, "Content-Type: %s/%s", TYPE (a), a->subtype);
Thomas Roessler's avatar
Thomas Roessler committed
304 305 306

  if (a->parameter)
  {
307
    len = 25 + mutt_strlen (a->subtype); /* approximate len. of content-type */
Thomas Roessler's avatar
Thomas Roessler committed
308

309
    for(p = a->parameter; p; p = p->next)
Thomas Roessler's avatar
Thomas Roessler committed
310
    {
311
      char *tmp;
312

313 314
      if(!p->value)
	continue;
315

Thomas Roessler's avatar
Thomas Roessler committed
316 317 318
      fputc (';', f);

      buffer[0] = 0;
319 320
      tmp = safe_strdup (p->value);
      encode = rfc2231_encode_string (&tmp);
Thomas Roessler's avatar
Thomas Roessler committed
321
      rfc822_cat (buffer, sizeof (buffer), tmp, MimeSpecials);
Thomas Roessler's avatar
Thomas Roessler committed
322

323
      /* Dirty hack to make messages readable by Outlook Express
324 325 326 327
       * for the Mac: force quotes around the boundary parameter
       * even when they aren't needed.
       */

328
      if (!ascii_strcasecmp (p->attribute, "boundary") && !strcmp (buffer, tmp))
329
	snprintf (buffer, sizeof (buffer), "\"%s\"", tmp);
330

331
      FREE (&tmp);
332

333
      tmplen = mutt_strlen (buffer) + mutt_strlen (p->attribute) + 1;
Thomas Roessler's avatar
Thomas Roessler committed
334 335 336 337 338 339 340 341 342 343 344 345

      if (len + tmplen + 2 > 76)
      {
	fputs ("\n\t", f);
	len = tmplen + 8;
      }
      else
      {
	fputc (' ', f);
	len += tmplen + 1;
      }

Thomas Roessler's avatar
Thomas Roessler committed
346
      fprintf (f, "%s%s=%s", p->attribute, encode ? "*" : "", buffer);
Thomas Roessler's avatar
Thomas Roessler committed
347 348 349 350 351 352 353 354 355

    }
  }

  fputc ('\n', f);

  if (a->description)
    fprintf(f, "Content-Description: %s\n", a->description);

356
  if (a->disposition != DISPNONE)
357
  {
358 359 360 361 362
    const char *dispstr[] = {
      "inline",
      "attachment",
      "form-data"
    };
363

364
    if (a->disposition < sizeof(dispstr)/sizeof(char*))
Thomas Roessler's avatar
Thomas Roessler committed
365
    {
366
      fprintf (f, "Content-Disposition: %s", dispstr[a->disposition]);
367

368 369 370 371
      if (a->use_disp)
      {
	if (!(fn = a->d_filename))
	  fn = a->filename;
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
	if (fn)
	{
	  char *tmp;

	  /* Strip off the leading path... */
	  if ((t = strrchr (fn, '/')))
	    t++;
	  else
	    t = fn;

	  buffer[0] = 0;
	  tmp = safe_strdup (t);
	  encode = rfc2231_encode_string (&tmp);
	  rfc822_cat (buffer, sizeof (buffer), tmp, MimeSpecials);
	  FREE (&tmp);
	  fprintf (f, "; filename%s=%s", encode ? "*" : "", buffer);
	}
      }

      fputc ('\n', f);
    }
    else
    {
      dprint(1, (debugfile, "ERROR: invalid content-disposition %d\n", a->disposition));
Thomas Roessler's avatar
Thomas Roessler committed
397 398 399
    }
  }

400 401 402
  if (a->encoding != ENC7BIT)
    fprintf(f, "Content-Transfer-Encoding: %s\n", ENCODING (a->encoding));

Thomas Roessler's avatar
Thomas Roessler committed
403 404 405 406
  /* Do NOT add the terminator here!!! */
  return (ferror (f) ? -1 : 0);
}

407 408 409
# define write_as_text_part(a)  (mutt_is_text_part(a) \
                                 || ((WithCrypto & APPLICATION_PGP)\
                                      && mutt_is_application_pgp(a)))
410

Thomas Roessler's avatar
Thomas Roessler committed
411 412 413
int mutt_write_mime_body (BODY *a, FILE *f)
{
  char *p, boundary[SHORT_STRING];
414
  char send_charset[SHORT_STRING];
Thomas Roessler's avatar
Thomas Roessler committed
415 416
  FILE *fpin;
  BODY *t;
417
  FGETCONV *fc;
418

Thomas Roessler's avatar
Thomas Roessler committed
419 420 421 422 423 424
  if (a->type == TYPEMULTIPART)
  {
    /* First, find the boundary to use */
    if (!(p = mutt_get_parameter ("boundary", a->parameter)))
    {
      dprint (1, (debugfile, "mutt_write_mime_body(): no boundary parameter found!\n"));
425
      mutt_error _("No boundary parameter found! [report this error]");
Thomas Roessler's avatar
Thomas Roessler committed
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
      return (-1);
    }
    strfcpy (boundary, p, sizeof (boundary));

    for (t = a->parts; t ; t = t->next)
    {
      fprintf (f, "\n--%s\n", boundary);
      if (mutt_write_mime_header (t, f) == -1)
	return -1;
      fputc ('\n', f);
      if (mutt_write_mime_body (t, f) == -1)
	return -1;
    }
    fprintf (f, "\n--%s--\n", boundary);
    return (ferror (f) ? -1 : 0);
  }

  /* This is pretty gross, but it's the best solution for now... */
444 445 446
  if ((WithCrypto & APPLICATION_PGP)
      && a->type == TYPEAPPLICATION
      && mutt_strcmp (a->subtype, "pgp-encrypted") == 0)
Thomas Roessler's avatar
Thomas Roessler committed
447 448 449 450 451 452 453 454
  {
    fputs ("Version: 1\n", f);
    return 0;
  }

  if ((fpin = fopen (a->filename, "r")) == NULL)
  {
    dprint(1,(debugfile, "write_mime_body: %s no longer exists!\n",a->filename));
455
    mutt_error (_("%s no longer exists!"), a->filename);
Thomas Roessler's avatar
Thomas Roessler committed
456 457 458
    return -1;
  }

459
  if (a->type == TYPETEXT && (!a->noconv))
460
    fc = fgetconv_open (fpin, a->charset,
461
			mutt_get_body_charset (send_charset, sizeof (send_charset), a),
Edmund GRIMLEY EVANS's avatar
Edmund GRIMLEY EVANS committed
462
			0);
463
  else
464
    fc = fgetconv_open (fpin, 0, 0, 0);
465

Thomas Roessler's avatar
Thomas Roessler committed
466
  if (a->encoding == ENCQUOTEDPRINTABLE)
467
    encode_quoted (fc, f, write_as_text_part (a));
Thomas Roessler's avatar
Thomas Roessler committed
468
  else if (a->encoding == ENCBASE64)
469
    encode_base64 (fc, f, write_as_text_part (a));
470
  else if (a->type == TYPETEXT && (!a->noconv))
471
    encode_8bit (fc, f, write_as_text_part (a));
Thomas Roessler's avatar
Thomas Roessler committed
472
  else
473
    mutt_copy_stream (fpin, f);
474

475
  fgetconv_close (&fc);
476
  safe_fclose (&fpin);
Thomas Roessler's avatar
Thomas Roessler committed
477 478 479 480

  return (ferror (f) ? -1 : 0);
}

481 482
#undef write_as_text_part

Thomas Roessler's avatar
Thomas Roessler committed
483
#define BOUNDARYLEN 16
484
void mutt_generate_boundary (PARAMETER **parm)
Thomas Roessler's avatar
Thomas Roessler committed
485
{
486
  char rs[BOUNDARYLEN + 1];
Thomas Roessler's avatar
Thomas Roessler committed
487 488 489 490
  char *p = rs;
  int i;

  rs[BOUNDARYLEN] = 0;
491
  for (i=0;i<BOUNDARYLEN;i++)
492
    *p++ = B64Chars[LRAND() % sizeof (B64Chars)];
Thomas Roessler's avatar
Thomas Roessler committed
493
  *p = 0;
494

495
  mutt_set_parameter ("boundary", rs, parm);
Thomas Roessler's avatar
Thomas Roessler committed
496 497
}

498 499 500 501 502 503 504 505 506 507 508
typedef struct
{
  int from;
  int whitespace;
  int dot;
  int linelen;
  int was_cr;
}
CONTENT_STATE;


509
static void update_content_info (CONTENT *info, CONTENT_STATE *s, char *d, size_t dlen)
Thomas Roessler's avatar
Thomas Roessler committed
510
{
511 512 513 514 515
  int from = s->from;
  int whitespace = s->whitespace;
  int dot = s->dot;
  int linelen = s->linelen;
  int was_cr = s->was_cr;
Thomas Roessler's avatar
Thomas Roessler committed
516

517
  if (!d) /* This signals EOF */
Thomas Roessler's avatar
Thomas Roessler committed
518
  {
519 520
    if (was_cr)
      info->binary = 1;
521 522 523
    if (linelen > info->linemax)
      info->linemax = linelen;

524
    return;
Thomas Roessler's avatar
Thomas Roessler committed
525 526
  }

527
  for (; dlen; d++, dlen--)
Thomas Roessler's avatar
Thomas Roessler committed
528
  {
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
    char ch = *d;

    if (was_cr)
    {
      was_cr = 0;
      if (ch != '\n')
      {
        info->binary = 1;
      }
      else
      {
        if (whitespace) info->space = 1;
	if (dot) info->dot = 1;
        if (linelen > info->linemax) info->linemax = linelen;
        whitespace = 0;
	dot = 0;
        linelen = 0;
	continue;
      }
    }

Thomas Roessler's avatar
Thomas Roessler committed
550 551 552
    linelen++;
    if (ch == '\n')
    {
553
      info->crlf++;
Thomas Roessler's avatar
Thomas Roessler committed
554 555 556 557 558 559 560 561 562
      if (whitespace) info->space = 1;
      if (dot) info->dot = 1;
      if (linelen > info->linemax) info->linemax = linelen;
      whitespace = 0;
      linelen = 0;
      dot = 0;
    }
    else if (ch == '\r')
    {
563
      info->crlf++;
564
      info->cr = 1;
565 566
      was_cr = 1;
      continue;
Thomas Roessler's avatar
Thomas Roessler committed
567 568 569 570 571 572 573 574
    }
    else if (ch & 0x80)
      info->hibin++;
    else if (ch == '\t' || ch == '\f')
    {
      info->ascii++;
      whitespace++;
    }
575 576 577 578 579
    else if (ch == 0)
    {
      info->nulbin++;
      info->lobin++;
    }
Thomas Roessler's avatar
Thomas Roessler committed
580 581 582 583 584 585
    else if (ch < 32 || ch == 127)
      info->lobin++;
    else
    {
      if (linelen == 1)
      {
586
        if ((ch == 'F') || (ch == 'f'))
Thomas Roessler's avatar
Thomas Roessler committed
587 588 589 590 591 592 593 594 595 596 597 598
          from = 1;
        else
          from = 0;
        if (ch == '.')
          dot = 1;
        else
          dot = 0;
      }
      else if (from)
      {
        if (linelen == 2 && ch != 'r') from = 0;
        else if (linelen == 3 && ch != 'o') from = 0;
599
        else if (linelen == 4)
Thomas Roessler's avatar
Thomas Roessler committed
600
	{
601
          if (ch == 'm') info->from = 1;
Thomas Roessler's avatar
Thomas Roessler committed
602 603 604 605 606 607
          from = 0;
        }
      }
      if (ch == ' ') whitespace++;
      info->ascii++;
    }
608

Thomas Roessler's avatar
Thomas Roessler committed
609 610 611
    if (linelen > 1) dot = 0;
    if (ch != ' ' && ch != '\t') whitespace = 0;
  }
612

613 614 615 616 617
  s->from = from;
  s->whitespace = whitespace;
  s->dot = dot;
  s->linelen = linelen;
  s->was_cr = was_cr;
618

619 620 621 622 623 624 625 626 627 628 629 630 631
}

/* Define as 1 if iconv sometimes returns -1(EILSEQ) instead of transcribing. */
#define BUGGY_ICONV 1

/*
 * Find the best charset conversion of the file from fromcode into one
 * of the tocodes. If successful, set *tocode and CONTENT *info and
 * return the number of characters converted inexactly. If no
 * conversion was possible, return -1.
 *
 * We convert via UTF-8 in order to avoid the condition -1(EINVAL),
 * which would otherwise prevent us from knowing the number of inexact
632 633 634
 * conversions. Where the candidate target charset is UTF-8 we avoid
 * doing the second conversion because iconv_open("UTF-8", "UTF-8")
 * fails with some libraries.
635 636 637 638 639 640 641 642 643
 *
 * We assume that the output from iconv is never more than 4 times as
 * long as the input for any pair of charsets we might be interested
 * in.
 */
static size_t convert_file_to (FILE *file, const char *fromcode,
			       int ncodes, const char **tocodes,
			       int *tocode, CONTENT *info)
{
Lars Hecking's avatar
Lars Hecking committed
644
#ifdef HAVE_ICONV
645 646
  iconv_t cd1, *cd;
  char bufi[256], bufu[512], bufo[4 * sizeof (bufi)];
647
  ICONV_CONST char *ib, *ub;
648 649 650 651
  char *ob;
  size_t ibl, obl, ubl, ubl1, n, ret;
  int i;
  CONTENT *infos;
652
  CONTENT_STATE *states;
653 654
  size_t *score;

655
  cd1 = mutt_iconv_open ("utf-8", fromcode, 0);
656 657 658
  if (cd1 == (iconv_t)(-1))
    return -1;

659 660 661 662
  cd     = safe_calloc (ncodes, sizeof (iconv_t));
  score  = safe_calloc (ncodes, sizeof (size_t));
  states = safe_calloc (ncodes, sizeof (CONTENT_STATE));
  infos  = safe_calloc (ncodes, sizeof (CONTENT));
663

664
  for (i = 0; i < ncodes; i++)
665 666
    if (ascii_strcasecmp (tocodes[i], "utf-8"))
      cd[i] = mutt_iconv_open (tocodes[i], "utf-8", 0);
667 668 669
    else
      /* Special case for conversion to UTF-8 */
      cd[i] = (iconv_t)(-1), score[i] = (size_t)(-1);
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703

  rewind (file);
  ibl = 0;
  for (;;)
  {

    /* Try to fill input buffer */
    n = fread (bufi + ibl, 1, sizeof (bufi) - ibl, file);
    ibl += n;

    /* Convert to UTF-8 */
    ib = bufi;
    ob = bufu, obl = sizeof (bufu);
    n = iconv (cd1, ibl ? &ib : 0, &ibl, &ob, &obl);
    assert (n == (size_t)(-1) || !n || ICONV_NONTRANS);
    if (n == (size_t)(-1) &&
	((errno != EINVAL && errno != E2BIG) || ib == bufi))
    {
      assert (errno == EILSEQ ||
	      (errno == EINVAL && ib == bufi && ibl < sizeof (bufi)));
      ret = (size_t)(-1);
      break;
    }
    ubl1 = ob - bufu;

    /* Convert from UTF-8 */
    for (i = 0; i < ncodes; i++)
      if (cd[i] != (iconv_t)(-1) && score[i] != (size_t)(-1))
      {
	ub = bufu, ubl = ubl1;
	ob = bufo, obl = sizeof (bufo);
	n = iconv (cd[i], (ibl || ubl) ? &ub : 0, &ubl, &ob, &obl);
	if (n == (size_t)(-1))
	{
704 705
	  assert (errno == E2BIG ||
		  (BUGGY_ICONV && (errno == EILSEQ || errno == ENOENT)));
706
	  score[i] = (size_t)(-1);
707 708 709 710
	}
	else
	{
	  score[i] += n;
711
	  update_content_info (&infos[i], &states[i], bufo, ob - bufo);
712 713
	}
      }
714 715 716
      else if (cd[i] == (iconv_t)(-1) && score[i] == (size_t)(-1))
	/* Special case for conversion to UTF-8 */
	update_content_info (&infos[i], &states[i], bufu, ubl1);
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733

    if (ibl)
      /* Save unused input */
      memmove (bufi, ib, ibl);
    else if (!ubl1 && ib < bufi + sizeof (bufi))
    {
      ret = 0;
      break;
    }
  }

  if (!ret)
  {
    /* Find best score */
    ret = (size_t)(-1);
    for (i = 0; i < ncodes; i++)
    {
734 735 736 737 738 739 740
      if (cd[i] == (iconv_t)(-1) && score[i] == (size_t)(-1))
      {
	/* Special case for conversion to UTF-8 */
	*tocode = i;
	ret = 0;
	break;
      }
741
      else if (cd[i] == (iconv_t)(-1) || score[i] == (size_t)(-1))
742
	continue;
743
      else if (ret == (size_t)(-1) || score[i] < ret)
744 745 746 747 748 749 750 751 752 753
      {
	*tocode = i;
	ret = score[i];
	if (!ret)
	  break;
      }
    }
    if (ret != (size_t)(-1))
    {
      memcpy (info, &infos[*tocode], sizeof(CONTENT));
754
      update_content_info (info, &states[*tocode], 0, 0); /* EOF */
755 756 757 758 759 760
    }
  }

  for (i = 0; i < ncodes; i++)
    if (cd[i] != (iconv_t)(-1))
      iconv_close (cd[i]);
761

762
  iconv_close (cd1);
763 764 765 766
  FREE (&cd);
  FREE (&infos);
  FREE (&score);
  FREE (&states);
767 768

  return ret;
Lars Hecking's avatar
Lars Hecking committed
769 770 771
#else
  return -1;
#endif /* !HAVE_ICONV */
772 773 774 775 776 777 778 779
}

/*
 * Find the first of the fromcodes that gives a valid conversion and
 * the best charset conversion of the file into one of the tocodes. If
 * successful, set *fromcode and *tocode to dynamically allocated
 * strings, set CONTENT *info, and return the number of characters
 * converted inexactly. If no conversion was possible, return -1.
780 781 782 783
 *
 * Both fromcodes and tocodes may be colon-separated lists of charsets.
 * However, if fromcode is zero then fromcodes is assumed to be the
 * name of a single charset even if it contains a colon.
784 785 786 787 788
 */
static size_t convert_file_from_to (FILE *file,
				    const char *fromcodes, const char *tocodes,
				    char **fromcode, char **tocode, CONTENT *info)
{
789
  char *fcode = NULL;
790 791
  char **tcode;
  const char *c, *c1;
792
  size_t ret;
Thomas Roessler's avatar
Thomas Roessler committed
793
  int ncodes, i, cn;
794 795 796 797 798

  /* Count the tocodes */
  ncodes = 0;
  for (c = tocodes; c; c = c1 ? c1 + 1 : 0)
  {
799
    if ((c1 = strchr (c, ':')) == c)
800 801 802 803 804 805 806 807
      continue;
    ++ncodes;
  }

  /* Copy them */
  tcode = safe_malloc (ncodes * sizeof (char *));
  for (c = tocodes, i = 0; c; c = c1 ? c1 + 1 : 0, i++)
  {
808
    if ((c1 = strchr (c, ':')) == c)
809
      continue;
810
    tcode[i] = mutt_substrdup (c, c1);
811 812
  }

Thomas Roessler's avatar
Thomas Roessler committed
813
  ret = (size_t)(-1);
814
  if (fromcode)
815
  {
816 817 818
    /* Try each fromcode in turn */
    for (c = fromcodes; c; c = c1 ? c1 + 1 : 0)
    {
819
      if ((c1 = strchr (c, ':')) == c)
820
	continue;
821
      fcode = mutt_substrdup (c, c1);
822

823 824 825 826 827 828 829 830 831
      ret = convert_file_to (file, fcode, ncodes, (const char **)tcode,
			     &cn, info);
      if (ret != (size_t)(-1))
      {
	*fromcode = fcode;
	*tocode = tcode[cn];
	tcode[cn] = 0;
	break;
      }
832
      FREE (&fcode);
833 834 835 836 837 838
    }
  }
  else
  {
    /* There is only one fromcode */
    ret = convert_file_to (file, fromcodes, ncodes, (const char **)tcode,
839
			   &cn, info);
840 841
    if (ret != (size_t)(-1))
    {
842 843 844 845 846 847 848
      *tocode = tcode[cn];
      tcode[cn] = 0;
    }
  }

  /* Free memory */
  for (i = 0; i < ncodes; i++)
849
    FREE (&tcode[i]);
850

851 852
  FREE (&tcode);

853 854 855
  return ret;
}

856
/*
857
 * Analyze the contents of a file to determine which MIME encoding to use.
858 859 860 861 862
 * Also set the body charset, sometimes, or not.
 */
CONTENT *mutt_get_content_info (const char *fname, BODY *b)
{
  CONTENT *info;
863
  CONTENT_STATE state;
864
  FILE *fp = NULL;
Fabian Groffen's avatar
Fabian Groffen committed
865
  char *fromcode = NULL;
866
  char *tocode;
867
  char buffer[100];
868
  char chsbuf[STRING];
869
  size_t r;
870

871
  struct stat sb;
872

873
  if(b && !fname) fname = b->filename;
874 875 876

  if (stat (fname, &sb) == -1)
  {
877
    mutt_error (_("Can't stat %s: %s"), fname, strerror (errno));
878 879
    return NULL;
  }
880

881 882 883 884 885
  if (!S_ISREG(sb.st_mode))
  {
    mutt_error (_("%s isn't a regular file."), fname);
    return NULL;
  }
886

887 888 889 890 891 892 893 894
  if ((fp = fopen (fname, "r")) == NULL)
  {
    dprint (1, (debugfile, "mutt_get_content_info: %s: %s (errno %d).\n",
		fname, strerror (errno), errno));
    return (NULL);
  }

  info = safe_calloc (1, sizeof (CONTENT));
895
  memset (&state, 0, sizeof (state));
896

897
  if (b != NULL && b->type == TYPETEXT && (!b->noconv && !b->force_charset))
898 899
  {
    char *chs = mutt_get_parameter ("charset", b->parameter);
900 901
    char *fchs = b->use_disp ? ((AttachCharset && *AttachCharset) ?
                                AttachCharset : Charset) : Charset;
902
    if (Charset && (chs || SendCharset) &&
903 904
        convert_file_from_to (fp, fchs, chs ? chs : SendCharset,
                              &fromcode, &tocode, info) != (size_t)(-1))
905 906
    {
      if (!chs)
907 908
      {
	mutt_canonical_charset (chsbuf, sizeof (chsbuf), tocode);
909
	mutt_set_parameter ("charset", chsbuf, &b->parameter);
910
      }
911
      FREE (&b->charset);
912
      b->charset = fromcode;
913
      FREE (&tocode);
914
      safe_fclose (&fp);
915 916 917 918
      return info;
    }
  }

919 920 921 922
  rewind (fp);
  while ((r = fread (buffer, 1, sizeof(buffer), fp)))
    update_content_info (info, &state, buffer, r);
  update_content_info (info, &state, 0, 0);
923

924
  safe_fclose (&fp);
925

926
  if (b != NULL && b->type == TYPETEXT && (!b->noconv && !b->force_charset))
927
    mutt_set_parameter ("charset", (!info->hibin ? "us-ascii" :
928
				    Charset  && !mutt_is_us_ascii (Charset) ? Charset : "unknown-8bit"),
929 930 931
			&b->parameter);

  return info;
Thomas Roessler's avatar
Thomas Roessler committed
932 933 934 935 936 937 938 939 940
}

/* Given a file with path ``s'', see if there is a registered MIME type.
 * returns the major MIME type, and copies the subtype to ``d''.  First look
 * for ~/.mime.types, then look in a system mime.types if we can find one.
 * The longest match is used so that we can match `ps.gz' when `gz' also
 * exists.
 */

941
int mutt_lookup_mime_type (BODY *att, const char *path)
Thomas Roessler's avatar
Thomas Roessler committed
942 943
{
  FILE *f;
944 945 946
  char *p, *q, *ct;
  char buf[LONG_STRING];
  char subtype[STRING], xtype[STRING];
Thomas Roessler's avatar
Thomas Roessler committed
947
  int count;
948 949
  int szf, sze, cur_sze;
  int type;
Thomas Roessler's avatar
Thomas Roessler committed
950

951 952 953 954 955 956
  *subtype = '\0';
  *xtype   = '\0';
  type     = TYPEOTHER;
  cur_sze  = 0;

  szf      = mutt_strlen (path);
Thomas Roessler's avatar
Thomas Roessler committed
957

958
  for (count = 0 ; count < 3 ; count++)
Thomas Roessler's avatar
Thomas Roessler committed
959 960 961 962 963 964 965 966
  {
    /*
     * can't use strtok() because we use it in an inner loop below, so use
     * a switch statement here instead.
     */
    switch (count)
    {
      case 0:
Thomas Roessler's avatar
Thomas Roessler committed
967
	snprintf (buf, sizeof (buf), "%s/.mime.types", NONULL(Homedir));
Thomas Roessler's avatar
Thomas Roessler committed
968 969
	break;
      case 1:
970 971
	strfcpy (buf, SYSCONFDIR"/mime.types", sizeof(buf));
	break;
972
      case 2:
973
	strfcpy (buf, PKGDATADIR"/mime.types", sizeof (buf));
Thomas Roessler's avatar
Thomas Roessler committed
974 975
	break;
      default:
976
        dprint (1, (debugfile, "mutt_lookup_mime_type: Internal error, count = %d.\n", count));
977
	goto bye;	/* shouldn't happen */
Thomas Roessler's avatar
Thomas Roessler committed
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    }

    if ((f = fopen (buf, "r")) != NULL)
    {
      while (fgets (buf, sizeof (buf) - 1, f) != NULL)
      {
	/* weed out any comments */
	if ((p = strchr (buf, '#')))
	  *p = 0;

	/* remove any leading space. */
	ct = buf;
	SKIPWS (ct);

	/* position on the next field in this line */
	if ((p = strpbrk (ct, " \t")) == NULL)
	  continue;
	*p++ = 0;
	SKIPWS (p);

	/* cycle through the file extensions */
	while ((p = strtok (p, " \t\n")))
	{
1001
	  sze = mutt_strlen (p);
Thomas Roessler's avatar
Thomas Roessler committed
1002
	  if ((sze > cur_sze) && (szf >= sze) &&
1003
	      (mutt_strcasecmp (path + szf - sze, p) == 0 || ascii_strcasecmp (path + szf - sze, p) == 0) &&
1004
	      (szf == sze || path[szf - sze - 1] == '.'))
Thomas Roessler's avatar
Thomas Roessler committed
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
	  {
	    /* get the content-type */

	    if ((p = strchr (ct, '/')) == NULL)
	    {
	      /* malformed line, just skip it. */
	      break;
	    }
	    *p++ = 0;

1015 1016
	    for (q = p; *q && !ISSPACE (*q); q++)
	      ;
1017

1018 1019 1020 1021
	    mutt_substrcpy (subtype, p, q, sizeof (subtype));

	    if ((type = mutt_check_mime_type (ct)) == TYPEOTHER)
	      strfcpy (xtype, ct, sizeof (xtype));
Thomas Roessler's avatar
Thomas Roessler committed
1022 1023 1024 1025 1026 1027

	    cur_sze = sze;
	  }
	  p = NULL;
	}
      }
1028
      safe_fclose (&f);
Thomas Roessler's avatar
Thomas Roessler committed
1029 1030
    }
  }
1031

1032 1033 1034 1035 1036 1037 1038 1039
 bye:

  if (type != TYPEOTHER || *xtype != '\0')
  {
    att->type = type;
    mutt_str_replace (&att->subtype, subtype);
    mutt_str_replace (&att->xtype, xtype);
  }
1040

1041
  return (type);
Thomas Roessler's avatar
Thomas Roessler committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
}

void mutt_message_to_7bit (BODY *a, FILE *fp)
{
  char temp[_POSIX_PATH_MAX];
  char *line = NULL;
  FILE *fpin = NULL;
  FILE *fpout = NULL;
  struct stat sb;

  if (!a->filename && fp)
    fpin = fp;
  else if (!a->filename || !(fpin = fopen (a->filename, "r")))
  {
1056
    mutt_error (_("Could not open %s"), a->filename ? a->filename : "(null)");
Thomas Roessler's avatar
Thomas Roessler committed
1057
    return;
1058
  }
Thomas Roessler's avatar
Thomas Roessler committed
1059 1060 1061 1062 1063 1064
  else
  {
    a->offset = 0;
    if (stat (a->filename, &sb) == -1)
    {
      mutt_perror ("stat");
1065
      safe_fclose (&fpin);
Thomas Roessler's avatar
Thomas Roessler committed
1066 1067 1068 1069
    }
    a->length = sb.st_size;
  }

1070
  mutt_mktemp (temp, sizeof (temp));
Thomas Roessler's avatar
Thomas Roessler committed
1071 1072 1073 1074 1075 1076
  if (!(fpout = safe_fopen (temp, "w+")))
  {
    mutt_perror ("fopen");
    goto cleanup;
  }

1077
  fseeko (fpin, a->offset, 0);
Thomas Roessler's avatar
Thomas Roessler committed
1078 1079 1080
  a->parts = mutt_parse_messageRFC822 (fpin, a);

  transform_to_7bit (a->parts, fpin);
1081 1082

  mutt_copy_hdr (fpin, fpout, a->offset, a->offset + a->length,
Thomas Roessler's avatar
Thomas Roessler committed
1083 1084
		 CH_MIME | CH_NONEWLINE | CH_XMIT, NULL);

1085
  fputs ("MIME-Version: 1.0\n", fpout);
Thomas Roessler's avatar
Thomas Roessler committed
1086 1087 1088
  mutt_write_mime_header (a->parts, fpout);
  fputc ('\n', fpout);
  mutt_write_mime_body (a->parts, fpout);
1089

Thomas Roessler's avatar
Thomas Roessler committed
1090
 cleanup:
1091
  FREE (&line);
Thomas Roessler's avatar
Thomas Roessler committed
1092

1093
  if (fpin && fpin != fp)
1094
    safe_fclose (&fpin);
Thomas Roessler's avatar
Thomas Roessler committed
1095
  if (fpout)
1096
    safe_fclose (&fpout);
Thomas Roessler's avatar
Thomas Roessler committed
1097 1098
  else
    return;
1099

Thomas Roessler's avatar
Thomas Roessler committed
1100
  a->encoding = ENC7BIT;
1101
  FREE (&a->d_filename);
Thomas Roessler's avatar
Thomas Roessler committed
1102 1103 1104 1105 1106
  a->d_filename = a->filename;
  if (a->filename && a->unlink)
    unlink (a->filename);
  a->filename = safe_strdup (temp);
  a->unlink = 1;
1107
  if(stat (a->filename, &sb) == -1)
Thomas Roessler's avatar
Thomas Roessler committed
1108 1109 1110 1111 1112 1113
  {
    mutt_perror ("stat");
    return;
  }
  a->length = sb.st_size;
  mutt_free_body (&a->parts);
1114
  a->hdr->content = NULL;
Thomas Roessler's avatar
Thomas Roessler committed
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
}

static void transform_to_7bit (BODY *a, FILE *fpin)
{
  char buff[_POSIX_PATH_MAX];
  STATE s;
  struct stat sb;

  memset (&s, 0, sizeof (s));
  for (; a; a = a->next)
  {
    if (a->type == TYPEMULTIPART)
    {
      if (a->encoding != ENC7BIT)
	a->encoding = ENC7BIT;

      transform_to_7bit (a->parts, fpin);
1132
    }
1133
    else if (mutt_is_message_type(a->type, a->subtype))
Thomas Roessler's avatar
Thomas Roessler committed
1134 1135 1136
    {
      mutt_message_to_7bit (a, fpin);
    }
1137
    else
Thomas Roessler's avatar
Thomas Roessler committed
1138
    {
Thomas Roessler's avatar
Thomas Roessler committed
1139 1140
      a->noconv = 1;
      a->force_charset = 1;
1141

1142
      mutt_mktemp (buff, sizeof (buff));
1143
      if ((s.fpout = safe_fopen (buff, "w")) == NULL)
Thomas Roessler's avatar
Thomas Roessler committed
1144 1145 1146 1147 1148 1149
      {
	mutt_perror ("fopen");
	return;
      }
      s.fpin = fpin;
      mutt_decode_attachment (a, &s);
1150
      safe_fclose (&s.fpout);
1151
      FREE (&a->d_filename);
Thomas Roessler's avatar
Thomas Roessler committed
1152 1153 1154
      a->d_filename = a->filename;
      a->filename = safe_strdup (buff);
      a->unlink = 1;
1155
      if (stat (a->filename, &sb) == -1)
Thomas Roessler's avatar
Thomas Roessler committed
1156 1157 1158 1159 1160 1161
      {
	mutt_perror ("stat");
	return;
      }
      a->length = sb.st_size;

1162
      mutt_update_encoding (a);
Thomas Roessler's avatar
Thomas Roessler committed
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
      if (a->encoding == ENC8BIT)
	a->encoding = ENCQUOTEDPRINTABLE;
      else if(a->encoding == ENCBINARY)
	a->encoding = ENCBASE64;
    }
  }
}

/* determine which Content-Transfer-Encoding to use */
static void mutt_set_encoding (BODY *b, CONTENT *info)
{
1174 1175
  char send_charset[SHORT_STRING];

Thomas Roessler's avatar
Thomas Roessler committed
1176 1177
  if (b->type == TYPETEXT)
  {
1178
    char *chsname = mutt_get_body_charset (send_charset, sizeof (send_charset), b);
1179
    if ((info->lobin && ascii_strncasecmp (chsname, "iso-2022", 8)) || info->linemax > 990 || (info->from && option (OPTENCODEFROM)))
Thomas Roessler's avatar
Thomas Roessler committed
1180 1181 1182 1183 1184 1185
      b->encoding = ENCQUOTEDPRINTABLE;
    else if (info->hibin)
      b->encoding = option (OPTALLOW8BIT) ? ENC8BIT : ENCQUOTEDPRINTABLE;
    else
      b->encoding = ENC7BIT;
  }
1186
  else if (b->type == TYPEMESSAGE || b->type == TYPEMULTIPART)
Thomas Roessler's avatar
Thomas Roessler committed
1187 1188 1189 1190
  {
    if (info->lobin || info->hibin)
    {
      if (option (OPTALLOW8BIT) && !info->lobin)
1191
	b->encoding = ENC8BIT;
Thomas Roessler's avatar
Thomas Roessler committed
1192 1193 1194 1195 1196 1197
      else
	mutt_message_to_7bit (b, NULL);
    }
    else
      b->encoding = ENC7BIT;
  }
1198 1199
  else if (b->type == TYPEAPPLICATION && ascii_strcasecmp (b->subtype, "pgp-keys") == 0)
    b->encoding = ENC7BIT;
1200 1201 1202
  else
#if 0
    if (info->lobin || info->hibin || info->binary || info->linemax > 990
1203
	   || info->cr || (/* option (OPTENCODEFROM) && */ info->from))
1204
#endif
Thomas Roessler's avatar
Thomas Roessler committed
1205 1206
  {
    /* Determine which encoding is smaller  */
1207
    if (1.33 * (float)(info->lobin+info->hibin+info->ascii) <
1208
	 3.0 * (float)(info->lobin + info->hibin) + (float)info->ascii)
Thomas Roessler's avatar
Thomas Roessler committed
1209 1210 1211 1212
      b->encoding = ENCBASE64;
    else
      b->encoding = ENCQUOTEDPRINTABLE;
  }
1213
#if 0
Thomas Roessler's avatar
Thomas Roessler committed
1214 1215
  else
    b->encoding = ENC7BIT;
1216
#endif
Thomas Roessler's avatar
Thomas Roessler committed
1217 1218
}

Thomas Roessler's avatar
Thomas Roessler committed
1219 1220 1221 1222 1223
void mutt_stamp_attachment(BODY *a)
{
  a->stamp = time(NULL);
}

1224
/* Get a body's character set */
1225

1226
char *mutt_get_body_charset (char *d, size_t dlen, BODY *b)
1227 1228 1229 1230 1231 1232
{
  char *p = NULL;

  if (b && b->type != TYPETEXT)
    return NULL;

1233
  if (b)
1234 1235 1236
    p = mutt_get_parameter ("charset", b->parameter);

  if (p)
1237
    mutt_canonical_charset (d, dlen, NONULL(p));
1238 1239
  else
    strfcpy (d, "us-ascii", dlen);
1240

1241
  return d;
1242 1243 1244
}


Thomas Roessler's avatar
Thomas Roessler committed
1245
/* Assumes called from send mode where BODY->filename points to actual file */
1246
void mutt_update_encoding (BODY *a)
Thomas Roessler's avatar
Thomas Roessler committed
1247
{
1248
  CONTENT *info;
1249 1250 1251
  char chsbuff[STRING];

  /* override noconv when it's us-ascii */
1252
  if (mutt_is_us_ascii (mutt_get_body_charset (chsbuff, sizeof (chsbuff), a)))
1253
    a->noconv = 0;
1254

1255
  if (!a->force_charset && !a->noconv)
1256
    mutt_delete_parameter ("charset", &a->parameter);
1257

1258
  if ((info = mutt_get_content_info (a->filename, a)) == NULL)
Thomas Roessler's avatar
Thomas Roessler committed
1259 1260 1261
    return;

  mutt_set_encoding (a, info);
Thomas Roessler's avatar
Thomas Roessler committed
1262
  mutt_stamp_attachment(a);
Thomas Roessler's avatar
Thomas Roessler committed
1263

1264
  FREE (&a->content);
Thomas Roessler's avatar
Thomas Roessler committed
1265 1266 1267 1268
  a->content = info;

}

Thomas Roessler's avatar
Thomas Roessler committed
1269 1270 1271 1272 1273
BODY *mutt_make_message_attach (CONTEXT *ctx, HEADER *hdr, int attach_msg)
{
  char buffer[LONG_STRING];
  BODY *body;
  FILE *fp;
1274
  int cmflags, chflags;
1275
  int pgp = WithCrypto? hdr->security : 0;
1276

1277 1278 1279 1280 1281 1282 1283
  if (WithCrypto)
  {
    if ((option(OPTMIMEFORWDECODE) || option(OPTFORWDECRYPT)) &&
        (hdr->security & ENCRYPT)) {
      if (!crypt_valid_passphrase(hdr->security))
        return (NULL);
    }
1284
  }
Thomas Roessler's avatar
Thomas Roessler committed
1285

1286
  mutt_mktemp (buffer, sizeof (buffer));
Thomas Roessler's avatar
Thomas Roessler committed
1287 1288 1289 1290 1291 1292 1293 1294 1295
  if ((fp = safe_fopen (buffer, "w+")) == NULL)
    return NULL;

  body = mutt_new_body ();
  body->type = TYPEMESSAGE;
  body->subtype = safe_strdup ("rfc822");
  body->filename = safe_strdup (buffer);
  body->unlink = 1;
  body->use_disp = 0;
1296
  body->disposition = DISPINLINE;
1297
  body->noconv = 1;
Thomas Roessler's avatar
Thomas Roessler committed
1298 1299 1300

  mutt_parse_mime_message (ctx, hdr);

1301 1302 1303
  chflags = CH_XMIT;
  cmflags = 0;

1304
  /* If we are attaching a message, ignore OPTMIMEFORWDECODE */
1305 1306 1307
  if (!attach_msg && option (OPTMIMEFORWDECODE))
  {
    chflags |= CH_MIME | CH_TXTPLAIN;
1308
    cmflags = MUTT_CM_DECODE | MUTT_CM_CHARCONV;
1309 1310 1311 1312
    if ((WithCrypto & APPLICATION_PGP))
      pgp &= ~PGPENCRYPT;
    if ((WithCrypto & APPLICATION_SMIME))
      pgp &= ~SMIMEENCRYPT;
1313
  }
1314 1315
  else if (WithCrypto
           && option (OPTFORWDECRYPT) && (hdr->security & ENCRYPT))
1316
  {
1317 1318
    if ((WithCrypto & APPLICATION_PGP)
        && mutt_is_multipart_encrypted (hdr->content))
1319 1320
    {
      chflags |= CH_MIME | CH_NONEWLINE;
1321
      cmflags = MUTT_CM_DECODE_PGP;
1322 1323
      pgp &= ~PGPENCRYPT;
    }
1324 1325
    else if ((WithCrypto & APPLICATION_PGP) &&
             ((mutt_is_application_pgp (hdr->content) & PGPENCRYPT) == PGPENCRYPT))
1326 1327
    {
      chflags |= CH_MIME | CH_TXTPLAIN;
1328
      cmflags = MUTT_CM_DECODE | MUTT_CM_CHARCONV;
1329 1330
      pgp &= ~PGPENCRYPT;
    }
1331 1332
    else if ((WithCrypto & APPLICATION_SMIME) &&
             ((mutt_is_application_smime (hdr->content) & SMIMEENCRYPT) == SMIMEENCRYPT))
1333 1334
    {
      chflags |= CH_MIME | CH_TXTPLAIN;
1335
      cmflags = MUTT_CM_DECODE | MUTT_CM_CHARCONV;
1336