1 ;;; rfc2047.el --- functions for encoding and decoding rfc2047 messages
2 ;; Copyright (C) 1998, 1999, 2000, 2002, 2003 Free Software Foundation, Inc.
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; This file is part of GNU Emacs.
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING. If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
25 ;; RFC 2047 is "MIME (Multipurpose Internet Mail Extensions) Part
26 ;; Three: Message Header Extensions for Non-ASCII Text".
32 (defvar message-posting-charset))
36 ;; Fixme: Avoid this (used for mail-parse-charset) mm dependence on gnus.
39 (autoload 'mm-body-7-or-8 "mm-bodies")
41 (defvar rfc2047-header-encoding-alist
42 '(("Newsgroups" . nil)
45 ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\
46 \\|Mail-Followup-To\\|Mail-Copies-To\\|Approved\\)" . address-mime)
48 "*Header/encoding method alist.
49 The list is traversed sequentially. The keys can either be
54 1) nil, in which case no encoding is done;
55 2) `mime', in which case the header will be encoded according to RFC2047;
56 3) `address-mime', like `mime', but takes account of the rules for address
57 fields (where quoted strings and comments must be treated separately);
58 4) a charset, in which case it will be encoded as that charset;
59 5) `default', in which case the field will be encoded as the rest
62 (defvar rfc2047-charset-encoding-alist
86 "Alist of MIME charsets to RFC2047 encodings.
87 Valid encodings are nil, `Q' and `B'. These indicate binary (no) encoding,
88 quoted-printable and base64 respectively.")
90 (defvar rfc2047-encoding-function-alist
91 '((Q . rfc2047-q-encode-region)
92 (B . rfc2047-b-encode-region)
94 "Alist of RFC2047 encodings to encoding functions.")
97 ;;; Functions for encoding RFC2047 messages
100 (defun rfc2047-qp-or-base64 ()
101 "Return the type with which to encode the buffer.
102 This is either `base64' or `quoted-printable'."
104 (let ((limit (min (point-max) (+ 2000 (point-min))))
106 (goto-char (point-min))
107 (skip-chars-forward "\x20-\x7f\r\n\t" limit)
108 (while (< (point) limit)
111 (skip-chars-forward "\x20-\x7f\r\n\t" limit))
112 (if (or (< (* 6 n8bit) (- limit (point-min)))
113 ;; Don't base64, say, a short line with a single
114 ;; non-ASCII char when splitting parts by charset.
119 (defun rfc2047-narrow-to-field ()
120 "Narrow the buffer to the header on the current line."
126 (if (re-search-forward "^[^ \n\t]" nil t)
129 (goto-char (point-min)))
131 (defun rfc2047-field-value ()
132 "Return the value of the field at point."
135 (rfc2047-narrow-to-field)
136 (re-search-forward ":[ \t\n]*" nil t)
137 (buffer-substring (point) (point-max)))))
139 (defvar rfc2047-encoding-type 'address-mime
140 "The type of encoding done by `rfc2047-encode-region'.
141 This should be dynamically bound around calls to
142 `rfc2047-encode-region' to either `mime' or `address-mime'. See
143 `rfc2047-header-encoding-alist', for definitions.")
145 (defun rfc2047-encode-message-header ()
146 "Encode the message header according to `rfc2047-header-encoding-alist'.
147 Should be called narrowed to the head of the message."
150 (goto-char (point-min))
151 (let (alist elem method)
154 (rfc2047-narrow-to-field)
155 (if (not (rfc2047-encodable-p))
157 (if (and (eq (mm-body-7-or-8) '8bit)
160 (car message-posting-charset)))
161 ;; 8 bit must be decoded.
162 (mm-encode-coding-region
163 (point-min) (point-max)
164 (mm-charset-to-coding-system
165 (car message-posting-charset))))
166 ;; No encoding necessary, but folding is nice
169 (goto-char (point-min))
170 (skip-chars-forward "^:")
171 (when (looking-at ": ")
175 ;; We found something that may perhaps be encoded.
177 alist rfc2047-header-encoding-alist)
178 (while (setq elem (pop alist))
179 (when (or (and (stringp (car elem))
180 (looking-at (car elem)))
184 (goto-char (point-min))
185 (re-search-forward "^[^:]+: *" nil t)
187 ((eq method 'address-mime)
188 (rfc2047-encode-region (point) (point-max)))
190 (let ((rfc2047-encoding-type 'mime))
191 (rfc2047-encode-region (point) (point-max))))
192 ((eq method 'default)
193 (if (and (featurep 'mule)
194 (if (boundp 'default-enable-multibyte-characters)
195 default-enable-multibyte-characters)
197 (mm-encode-coding-region (point) (point-max)
198 mail-parse-charset)))
199 ;; We get this when CC'ing messsages to newsgroups with
200 ;; 8-bit names. The group name mail copy just got
201 ;; unconditionally encoded. Previously, it would ask
202 ;; whether to encode, which was quite confusing for the
203 ;; user. If the new behaviour is wrong, tell me. I have
204 ;; left the old code commented out below.
205 ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
206 ;; Modified by Dave Love, with the commented-out code changed
207 ;; in accordance with changes elsewhere.
209 (rfc2047-encode-region (point) (point-max)))
211 ;;; (if (or (message-options-get
212 ;;; 'rfc2047-encode-message-header-encode-any)
213 ;;; (message-options-set
214 ;;; 'rfc2047-encode-message-header-encode-any
216 ;;; "Some texts are not encoded. Encode anyway?")))
217 ;;; (rfc2047-encode-region (point-min) (point-max))
218 ;;; (error "Cannot send unencoded text")))
219 ((mm-coding-system-p method)
220 (if (and (featurep 'mule)
221 (if (boundp 'default-enable-multibyte-characters)
222 default-enable-multibyte-characters))
223 (mm-encode-coding-region (point) (point-max) method)))
226 (goto-char (point-max)))))))
228 ;; Fixme: This, and the require below may not be the Right Thing, but
229 ;; should be safe just before release. -- fx 2001-02-08
230 (eval-when-compile (defvar message-posting-charset))
232 (defun rfc2047-encodable-p ()
233 "Return non-nil if any characters in current buffer need encoding in headers.
234 The buffer may be narrowed."
235 (require 'message) ; for message-posting-charset
237 (mm-find-mime-charset-region (point-min) (point-max))))
239 (not (equal charsets (list (car message-posting-charset)))))))
241 ;; Use this syntax table when parsing into regions that may need
242 ;; encoding. Double quotes are string delimiters, backslash is
243 ;; character quoting, and all other RFC 2822 special characters are
244 ;; treated as punctuation so we can use forward-sexp/forward-word to
245 ;; skip to the end of regions appropriately. Nb. ietf-drums does
246 ;; things differently.
247 (defconst rfc2047-syntax-table
248 ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
249 (let ((table (make-syntax-table)))
250 ;; The following is done to work for setting all elements of the table
251 ;; in Emacs 21 and 22 and XEmacs; it appears to be the cleanest way.
252 ;; Play safe and don't assume the form of the word syntax entry --
254 (if (fboundp 'set-char-table-range) ; Emacs
255 (funcall (intern "set-char-table-range")
256 table t (aref (standard-syntax-table) ?a))
257 (if (fboundp 'put-char-table)
258 (if (fboundp 'get-char-table) ; warning avoidance
259 (put-char-table t (get-char-table ?a (standard-syntax-table))
261 (modify-syntax-entry ?\\ "\\" table)
262 (modify-syntax-entry ?\" "\"" table)
263 (modify-syntax-entry ?\( "." table)
264 (modify-syntax-entry ?\) "." table)
265 (modify-syntax-entry ?\< "." table)
266 (modify-syntax-entry ?\> "." table)
267 (modify-syntax-entry ?\[ "." table)
268 (modify-syntax-entry ?\] "." table)
269 (modify-syntax-entry ?: "." table)
270 (modify-syntax-entry ?\; "." table)
271 (modify-syntax-entry ?, "." table)
272 (modify-syntax-entry ?@ "." table)
275 (defun rfc2047-encode-region (b e)
276 "Encode words in region B to E that need encoding.
277 By default, the region is treated as containing RFC2822 addresses.
278 Dynamically bind `rfc2047-encoding-type' to change that."
280 (narrow-to-region b e)
281 (if (eq 'mime rfc2047-encoding-type)
282 ;; Simple case. Treat as single word after any initial ASCII
283 ;; part and before any tailing ASCII part. The leading ASCII
284 ;; is relevant for instance in Subject headers with `Re:' for
285 ;; interoperability with non-MIME clients, and we might as
286 ;; well avoid the tail too.
288 (goto-char (point-min))
289 ;; Does it need encoding?
290 (skip-chars-forward "\000-\177")
292 (skip-chars-backward "^ \n") ; beginning of space-delimited word
293 (rfc2047-encode (point) (progn
295 (skip-chars-backward "\000-\177")
296 (skip-chars-forward "^ \n")
297 ;; end of space-delimited word
299 ;; `address-mime' case -- take care of quoted words, comments.
300 (with-syntax-table rfc2047-syntax-table
301 (let ((start) ; start of current token
302 end ; end of current token
303 ;; Whether there's an encoded word before the current
304 ;; token, either immediately or separated by space.
306 (goto-char (point-min))
307 (condition-case nil ; in case of unbalanced quotes
308 ;; Look for rfc2822-style: sequences of atoms, quoted
309 ;; strings, specials, whitespace. (Specials mustn't be
314 (unless (= 0 (skip-chars-forward " \t\n"))
315 (setq start (point)))
317 ((not (char-after))) ; eob
319 ((eq ?\" (char-syntax (char-after)))
323 ;; Does it need encoding?
325 (skip-chars-forward "\000-\177" end)
327 (setq last-encoded nil)
328 ;; It needs encoding. Strip the quotes first,
329 ;; since encoded words can't occur in quotes.
331 (delete-backward-char 1)
335 ;; There was a preceding quoted word. We need
336 ;; to include any separating whitespace in this
337 ;; word to avoid it getting lost.
338 (skip-chars-backward " \t")
339 ;; A space is needed between the encoded words.
343 ;; Adjust the end position for the deleted quotes.
344 (rfc2047-encode start (- end 2))
345 (setq last-encoded t))) ; record that it was encoded
346 ((eq ?. (char-syntax (char-after)))
347 ;; Skip other delimiters, but record that they've
348 ;; potentially separated quoted words.
350 (setq last-encoded nil))
351 (t ; normal token/whitespace sequence
354 (skip-chars-backward " \t")
356 ;; Deal with encoding and leading space as for
359 (skip-chars-forward "\000-\177" end)
361 (setq last-encoded nil)
364 (skip-chars-backward " \t")
368 (rfc2047-encode start end)
369 (setq last-encoded t)))))
371 (error "Invalid data for rfc2047 encoding: %s"
372 (buffer-substring b e)))))))
373 (rfc2047-fold-region b (point))))
375 (defun rfc2047-encode-string (string)
376 "Encode words in STRING.
377 By default, the string is treated as containing addresses (see
378 `rfc2047-encoding-type')."
381 (rfc2047-encode-region (point-min) (point-max))
384 (defun rfc2047-encode (b e)
385 "Encode the word(s) in the region B to E.
386 By default, the region is treated as containing addresses (see
387 `rfc2047-encoding-type')."
388 (let* ((mime-charset (mm-find-mime-charset-region b e))
389 (cs (if (> (length mime-charset) 1)
390 ;; Fixme: Instead of this, try to break region into
391 ;; parts that can be encoded separately.
392 (error "Can't rfc2047-encode `%s'"
393 (buffer-substring b e))
394 (setq mime-charset (car mime-charset))
395 (mm-charset-to-coding-system mime-charset)))
396 ;; Fixme: Better, calculate the number of non-ASCII
397 ;; characters, at least for 8-bit charsets.
398 (encoding (or (cdr (assq mime-charset
399 rfc2047-charset-encoding-alist))
400 ;; For the charsets that don't have a preferred
401 ;; encoding, choose the one that's shorter.
403 (narrow-to-region b e)
404 (if (eq (rfc2047-qp-or-base64) 'base64)
408 "=?" (downcase (symbol-name mime-charset)) "?"
409 (downcase (symbol-name encoding)) "?"))
410 (factor (case mime-charset
411 ((iso-8859-5 iso-8859-7 iso-8859-8 koi8-r) 1)
412 ((big5 gb2312 euc-kr) 2)
415 (pre (- b (save-restriction
418 ;; encoded-words must not be longer than 75 characters,
419 ;; including charset, encoding etc. This leaves us with
420 ;; 75 - (length start) - 2 - 2 characters. The last 2 is for
421 ;; possible base64 padding. In the worst case (iso-2022-*)
422 ;; each character expands to 8 bytes which is expanded by a
423 ;; factor of 4/3 by base64 encoding.
424 (length (floor (- 75 (length start) 4) (* factor (/ 4.0 3.0))))
425 ;; Limit line length to 76 characters.
426 (length1 (max 1 (floor (- 76 (length start) 4 pre)
427 (* factor (/ 4.0 3.0)))))
431 (narrow-to-region b e)
432 (when (eq encoding 'B)
433 ;; break into lines before encoding
434 (goto-char (point-min))
438 (goto-char (min (point-max) (+ length1 (point))))
440 (goto-char (min (point-max) (+ length (point)))))
444 (if (and (mm-multibyte-p)
445 (mm-coding-system-p cs))
446 (mm-encode-coding-region (point-min) (point-max) cs))
447 (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
448 (point-min) (point-max))
449 (goto-char (point-min))
457 (forward-line 1))))))
459 (defun rfc2047-fold-field ()
460 "Fold the current header field."
463 (rfc2047-narrow-to-field)
464 (rfc2047-fold-region (point-min) (point-max)))))
466 (defun rfc2047-fold-region (b e)
467 "Fold long lines in region B to E."
469 (narrow-to-region b e)
470 (goto-char (point-min))
474 (bol (save-restriction
478 (when (and (or break qword-break)
479 (> (- (point) bol) 76))
480 (goto-char (or break qword-break))
483 (if (looking-at "[ \t]")
486 (setq bol (1- (point)))
487 ;; Don't break before the first non-LWSP characters.
488 (skip-chars-forward " \t")
492 ((eq (char-after) ?\n)
497 (skip-chars-forward " \t")
498 (unless (or (eobp) (eq (char-after) ?\n))
500 ((eq (char-after) ?\r)
502 ((memq (char-after) '(? ?\t))
503 (skip-chars-forward " \t")
505 ;; Don't break just after the header name.
507 (setq break (1- (point)))))
509 (if (not (looking-at "=\\?[^=]"))
510 (if (eq (char-after) ?=)
512 (skip-chars-forward "^ \t\n\r="))
513 ;; Don't break at the start of the field.
514 (unless (= (point) b)
515 (setq qword-break (point)))
516 (skip-chars-forward "^ \t\n\r")))
518 (skip-chars-forward "^ \t\n\r"))))
519 (when (and (or break qword-break)
520 (> (- (point) bol) 76))
521 (goto-char (or break qword-break))
524 (if (looking-at "[ \t]")
527 (setq bol (1- (point)))
528 ;; Don't break before the first non-LWSP characters.
529 (skip-chars-forward " \t")
531 (forward-char 1))))))
533 (defun rfc2047-unfold-field ()
534 "Fold the current line."
537 (rfc2047-narrow-to-field)
538 (rfc2047-unfold-region (point-min) (point-max)))))
540 (defun rfc2047-unfold-region (b e)
541 "Unfold lines in region B to E."
543 (narrow-to-region b e)
544 (goto-char (point-min))
545 (let ((bol (save-restriction
548 (eol (point-at-eol)))
551 (if (and (looking-at "[ \t]")
552 (< (- (point-at-eol) bol) 76))
553 (delete-region eol (progn
555 (skip-chars-forward "\r\n")
557 (setq bol (point-at-bol)))
558 (setq eol (point-at-eol))
561 (defun rfc2047-b-encode-region (b e)
562 "Base64-encode the header contained in region B to E."
564 (narrow-to-region (goto-char b) e)
566 (base64-encode-region (point) (progn (end-of-line) (point)) t)
567 (if (and (bolp) (eolp))
568 (delete-backward-char 1))
571 (defun rfc2047-q-encode-region (b e)
572 "Quoted-printable-encode the header in region B to E."
575 (narrow-to-region (goto-char b) e)
576 (let ((bol (save-restriction
579 (quoted-printable-encode-region
581 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
582 ;; Avoid using 8bit characters.
583 ;; This list excludes `especials' (see the RFC2047 syntax),
584 ;; meaning that some characters in non-structured fields will
585 ;; get encoded when they con't need to be. The following is
586 ;; what it used to be.
587 ;;; ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
588 ;;; "\010\012\014\040-\074\076\100-\136\140-\177")
589 "-\b\n\f !#-'*+0-9A-Z\\^`-~\d")
590 (subst-char-in-region (point-min) (point-max) ? ?_)
591 ;; The size of QP encapsulation is about 20, so set limit to
593 (unless (< (- (point-max) (point-min)) 56)
594 ;; Don't break if it could fit in one line.
595 ;; Let rfc2047-encode-region break it later.
596 (goto-char (1+ (point-min)))
597 (while (and (not (bobp)) (not (eobp)))
598 (goto-char (min (point-max) (+ 56 bol)))
599 (search-backward "=" (- (point) 2) t)
600 (unless (or (bobp) (eobp))
602 (setq bol (point)))))))))
605 ;;; Functions for decoding RFC2047 messages
609 (defconst rfc2047-encoded-word-regexp
610 "=\\?\\([^][\000-\040()<>@,\;:*\\\"/?.=]+\\)\\(?:\\*[^?]+\\)?\
611 \\?\\(B\\|Q\\)\\?\\([!->@-~ +]*\\)\\?="))
613 ;; Fixme: This should decode in place, not cons intermediate strings.
614 ;; Also check whether it needs to worry about delimiting fields like
617 ;; In fact it's reported that (invalid) encoding of mailboxes in
618 ;; addr-specs is in use, so delimiting fields might help. Probably
619 ;; not decoding a word which isn't properly delimited is good enough
620 ;; and worthwhile (is it more correct or not?), e.g. something like
621 ;; `=?iso-8859-1?q?foo?=@'.
623 (defun rfc2047-decode-region (start end)
624 "Decode MIME-encoded words in region between START and END."
626 (let ((case-fold-search t)
630 (narrow-to-region start end)
631 (goto-char (point-min))
632 ;; Remove whitespace between encoded words.
633 (while (re-search-forward
635 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
637 "\\(" rfc2047-encoded-word-regexp "\\)"))
639 (delete-region (goto-char (match-end 1)) (match-beginning 6)))
640 ;; Decode the encoded words.
641 (setq b (goto-char (point-min)))
642 (while (re-search-forward rfc2047-encoded-word-regexp nil t)
643 (setq e (match-beginning 0))
644 (insert (rfc2047-parse-and-decode
647 (delete-region (match-beginning 0) (match-end 0)))))
648 ;; Remove newlines between decoded words, though such things
649 ;; essentially must not be there.
651 (narrow-to-region e (point))
653 (while (re-search-forward "[\n\r]+" nil t)
655 (goto-char (point-max)))
656 (when (and (mm-multibyte-p)
658 (not (eq mail-parse-charset 'us-ascii))
659 (not (eq mail-parse-charset 'gnus-decoded)))
660 (mm-decode-coding-region b e mail-parse-charset))
662 (when (and (mm-multibyte-p)
664 (not (eq mail-parse-charset 'us-ascii))
665 (not (eq mail-parse-charset 'gnus-decoded)))
666 (mm-decode-coding-region b (point-max) mail-parse-charset))))))
668 (defun rfc2047-decode-string (string)
669 "Decode the quoted-printable-encoded STRING and return the results."
670 (let ((m (mm-multibyte-p)))
671 (if (string-match "=\\?" string)
673 ;; Fixme: This logic is wrong, but seems to be required by
674 ;; Gnus summary buffer generation. The value of `m' depends
675 ;; on the current buffer, not global multibyteness or that
676 ;; of the string. Also the string returned should always be
677 ;; multibyte in a multibyte session, i.e. the buffer should
678 ;; be multibyte before `buffer-string' is called.
680 (mm-enable-multibyte))
683 (rfc2047-decode-region (point-min) (point-max)))
685 ;; Fixme: As above, `m' here is inappropriate.
688 (not (eq mail-parse-charset 'us-ascii))
689 (not (eq mail-parse-charset 'gnus-decoded)))
690 ;; `decode-coding-string' in Emacs offers a third optional
691 ;; arg NOCOPY to avoid consing a new string if the decoding
692 ;; is "trivial". Unfortunately it currently doesn't
693 ;; consider anything else than a `nil' coding system
695 ;; `rfc2047-decode-string' is called multiple times for each
696 ;; article during summary buffer generation, and we really
697 ;; want to avoid unnecessary consing. So we bypass
698 ;; `decode-coding-string' if the string is purely ASCII.
699 (if (and (fboundp 'detect-coding-string)
700 ;; string is purely ASCII
701 (eq (detect-coding-string string t) 'undecided))
703 (mm-decode-coding-string string mail-parse-charset))
704 (mm-string-as-multibyte string)))))
706 (defun rfc2047-parse-and-decode (word)
707 "Decode WORD and return it if it is an encoded word.
708 Return WORD if it is not not an encoded word or if the charset isn't
710 (if (not (string-match rfc2047-encoded-word-regexp word))
715 (match-string 1 word)
716 (string-to-char (match-string 2 word))
717 (match-string 3 word))
719 word))) ; un-decodable
721 (defun rfc2047-pad-base64 (string)
722 "Pad STRING to quartets."
723 ;; Be more liberal to accept buggy base64 strings. If
724 ;; base64-decode-string accepts buggy strings, this function could
725 ;; be aliased to identity.
726 (if (= 0 (mod (length string) 4))
728 (when (string-match "=+$" string)
729 (setq string (substring string 0 (match-beginning 0))))
730 (case (mod (length string) 4)
732 (1 string) ;; Error, don't pad it.
733 (2 (concat string "=="))
734 (3 (concat string "=")))))
736 (defun rfc2047-decode (charset encoding string)
737 "Decode STRING from the given MIME CHARSET in the given ENCODING.
738 Valid ENCODINGs are the characters \"B\" and \"Q\".
739 If your Emacs implementation can't decode CHARSET, return nil."
740 (if (stringp charset)
741 (setq charset (intern (downcase charset))))
742 (if (or (not charset)
743 (eq 'gnus-all mail-parse-ignored-charsets)
744 (memq 'gnus-all mail-parse-ignored-charsets)
745 (memq charset mail-parse-ignored-charsets))
746 (setq charset mail-parse-charset))
747 (let ((cs (mm-charset-to-coding-system charset)))
748 (if (and (not cs) charset
749 (listp mail-parse-ignored-charsets)
750 (memq 'gnus-unknown mail-parse-ignored-charsets))
751 (setq cs (mm-charset-to-coding-system mail-parse-charset)))
753 (when (and (eq cs 'ascii)
755 (setq cs mail-parse-charset))
756 (mm-decode-coding-string
758 ((char-equal ?B encoding)
759 (base64-decode-string
760 (rfc2047-pad-base64 string)))
761 ((char-equal ?Q encoding)
762 (quoted-printable-decode-string
763 (mm-subst-char-in-string ?_ ? string t)))
764 (t (error "Invalid encoding: %c" encoding)))
769 ;;; rfc2047.el ends here