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-narrow-to-field ()
101 "Narrow the buffer to the header on the current line."
107 (if (re-search-forward "^[^ \n\t]" nil t)
110 (goto-char (point-min)))
112 (defun rfc2047-field-value ()
113 "Return the value of the field at point."
116 (rfc2047-narrow-to-field)
117 (re-search-forward ":[ \t\n]*" nil t)
118 (buffer-substring (point) (point-max)))))
120 (defvar rfc2047-encoding-type 'address-mime
121 "The type of encoding done by `rfc2047-encode-region'.
122 This should be dynamically bound around calls to
123 `rfc2047-encode-region' to either `mime' or `address-mime'. See
124 `rfc2047-header-encoding-alist', for definitions.")
126 (defun rfc2047-encode-message-header ()
127 "Encode the message header according to `rfc2047-header-encoding-alist'.
128 Should be called narrowed to the head of the message."
131 (goto-char (point-min))
132 (let (alist elem method)
135 (rfc2047-narrow-to-field)
136 (if (not (rfc2047-encodable-p))
138 (if (and (eq (mm-body-7-or-8) '8bit)
141 (car message-posting-charset)))
142 ;; 8 bit must be decoded.
143 (mm-encode-coding-region
144 (point-min) (point-max)
145 (mm-charset-to-coding-system
146 (car message-posting-charset))))
147 ;; No encoding necessary, but folding is nice
150 (goto-char (point-min))
151 (skip-chars-forward "^:")
152 (when (looking-at ": ")
156 ;; We found something that may perhaps be encoded.
158 alist rfc2047-header-encoding-alist)
159 (while (setq elem (pop alist))
160 (when (or (and (stringp (car elem))
161 (looking-at (car elem)))
165 (goto-char (point-min))
166 (re-search-forward "^[^:]+: *" nil t)
168 ((eq method 'address-mime)
169 (rfc2047-encode-region (point) (point-max)))
171 (let ((rfc2047-encoding-type 'mime))
172 (rfc2047-encode-region (point) (point-max))))
173 ((eq method 'default)
174 (if (and (featurep 'mule)
175 (if (boundp 'default-enable-multibyte-characters)
176 default-enable-multibyte-characters)
178 (mm-encode-coding-region (point) (point-max)
179 mail-parse-charset)))
180 ;; We get this when CC'ing messsages to newsgroups with
181 ;; 8-bit names. The group name mail copy just got
182 ;; unconditionally encoded. Previously, it would ask
183 ;; whether to encode, which was quite confusing for the
184 ;; user. If the new behaviour is wrong, tell me. I have
185 ;; left the old code commented out below.
186 ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
187 ;; Modified by Dave Love, with the commented-out code changed
188 ;; in accordance with changes elsewhere.
190 (rfc2047-encode-region (point) (point-max)))
192 ;;; (if (or (message-options-get
193 ;;; 'rfc2047-encode-message-header-encode-any)
194 ;;; (message-options-set
195 ;;; 'rfc2047-encode-message-header-encode-any
197 ;;; "Some texts are not encoded. Encode anyway?")))
198 ;;; (rfc2047-encode-region (point-min) (point-max))
199 ;;; (error "Cannot send unencoded text")))
200 ((mm-coding-system-p method)
201 (if (and (featurep 'mule)
202 (if (boundp 'default-enable-multibyte-characters)
203 default-enable-multibyte-characters))
204 (mm-encode-coding-region (point) (point-max) method)))
207 (goto-char (point-max)))))))
209 ;; Fixme: This, and the require below may not be the Right Thing, but
210 ;; should be safe just before release. -- fx 2001-02-08
211 (eval-when-compile (defvar message-posting-charset))
213 (defun rfc2047-encodable-p ()
214 "Return non-nil if any characters in current buffer need encoding in headers.
215 The buffer may be narrowed."
216 (require 'message) ; for message-posting-charset
218 (mm-find-mime-charset-region (point-min) (point-max))))
220 (not (equal charsets (list (car message-posting-charset)))))))
222 ;; Use this syntax table when parsing into regions that may need
223 ;; encoding. Double quotes are string delimiters, backslash is
224 ;; character quoting, and all other RFC 2822 special characters are
225 ;; treated as punctuation so we can use forward-sexp/forward-word to
226 ;; skip to the end of regions appropriately. Nb. ietf-drums does
227 ;; things differently.
228 (defconst rfc2047-syntax-table
229 ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
230 (let ((table (make-syntax-table)))
231 ;; The following is done to work for setting all elements of the table
232 ;; in Emacs 21 and 22 and XEmacs; it appears to be the cleanest way.
233 ;; Play safe and don't assume the form of the word syntax entry --
235 (if (fboundp 'set-char-table-range) ; Emacs
236 (funcall (intern "set-char-table-range")
237 table t (aref (standard-syntax-table) ?a))
238 (if (fboundp 'put-char-table)
239 (if (fboundp 'get-char-table) ; warning avoidance
240 (put-char-table t (get-char-table ?a (standard-syntax-table))
242 (modify-syntax-entry ?\\ "\\" table)
243 (modify-syntax-entry ?\" "\"" table)
244 (modify-syntax-entry ?\( "." table)
245 (modify-syntax-entry ?\) "." table)
246 (modify-syntax-entry ?\< "." table)
247 (modify-syntax-entry ?\> "." table)
248 (modify-syntax-entry ?\[ "." table)
249 (modify-syntax-entry ?\] "." table)
250 (modify-syntax-entry ?: "." table)
251 (modify-syntax-entry ?\; "." table)
252 (modify-syntax-entry ?, "." table)
253 (modify-syntax-entry ?@ "." table)
256 (defun rfc2047-encode-region (b e)
257 "Encode words in region B to E that need encoding.
258 By default, the region is treated as containing RFC2822 addresses.
259 Dynamically bind `rfc2047-encoding-type' to change that."
261 (narrow-to-region b e)
262 (if (eq 'mime rfc2047-encoding-type)
263 ;; Simple case. Treat as single word after any initial ASCII
264 ;; part and before any tailing ASCII part. The leading ASCII
265 ;; is relevant for instance in Subject headers with `Re:' for
266 ;; interoperability with non-MIME clients, and we might as
267 ;; well avoid the tail too.
269 (goto-char (point-min))
270 ;; Does it need encoding?
271 (skip-chars-forward "\000-\177")
273 (skip-chars-backward "^ \n") ; beginning of space-delimited word
274 (rfc2047-encode (point) (progn
276 (skip-chars-backward "\000-\177")
277 (skip-chars-forward "^ \n")
278 ;; end of space-delimited word
280 ;; `address-mime' case -- take care of quoted words, comments.
281 (with-syntax-table rfc2047-syntax-table
282 (let ((start) ; start of current token
283 end ; end of current token
284 ;; Whether there's an encoded word before the current
285 ;; token, either immediately or separated by space.
287 (goto-char (point-min))
288 (condition-case nil ; in case of unbalanced quotes
289 ;; Look for rfc2822-style: sequences of atoms, quoted
290 ;; strings, specials, whitespace. (Specials mustn't be
295 (unless (= 0 (skip-chars-forward " \t\n"))
296 (setq start (point)))
298 ((not (char-after))) ; eob
300 ((eq ?\" (char-syntax (char-after)))
304 ;; Does it need encoding?
306 (skip-chars-forward "\000-\177" end)
308 (setq last-encoded nil)
309 ;; It needs encoding. Strip the quotes first,
310 ;; since encoded words can't occur in quotes.
312 (delete-backward-char 1)
316 ;; There was a preceding quoted word. We need
317 ;; to include any separating whitespace in this
318 ;; word to avoid it getting lost.
319 (skip-chars-backward " \t")
320 ;; A space is needed between the encoded words.
324 ;; Adjust the end position for the deleted quotes.
325 (rfc2047-encode start (- end 2))
326 (setq last-encoded t))) ; record that it was encoded
327 ((eq ?. (char-syntax (char-after)))
328 ;; Skip other delimiters, but record that they've
329 ;; potentially separated quoted words.
331 (setq last-encoded nil))
332 (t ; normal token/whitespace sequence
335 (skip-chars-backward " \t")
337 ;; Deal with encoding and leading space as for
340 (skip-chars-forward "\000-\177" end)
342 (setq last-encoded nil)
345 (skip-chars-backward " \t")
349 (rfc2047-encode start end)
350 (setq last-encoded t)))))
352 (error "Invalid data for rfc2047 encoding: %s"
353 (buffer-substring b e)))))))
354 (rfc2047-fold-region b (point))))
356 (defun rfc2047-encode-string (string)
357 "Encode words in STRING.
358 By default, the string is treated as containing addresses (see
359 `rfc2047-encoding-type')."
362 (rfc2047-encode-region (point-min) (point-max))
365 (defun rfc2047-encode (b e)
366 "Encode the word(s) in the region B to E.
367 By default, the region is treated as containing addresses (see
368 `rfc2047-encoding-type')."
369 (let* ((mime-charset (mm-find-mime-charset-region b e))
370 (cs (if (> (length mime-charset) 1)
371 ;; Fixme: Instead of this, try to break region into
372 ;; parts that can be encoded separately.
373 (error "Can't rfc2047-encode `%s'"
374 (buffer-substring b e))
375 (setq mime-charset (car mime-charset))
376 (mm-charset-to-coding-system mime-charset)))
377 ;; Fixme: Better, calculate the number of non-ASCII
378 ;; characters, at least for 8-bit charsets.
379 (encoding (or (cdr (assq mime-charset
380 rfc2047-charset-encoding-alist))
381 ;; For the charsets that don't have a preferred
382 ;; encoding, choose the one that's shorter.
384 (narrow-to-region b e)
385 (if (eq (mm-qp-or-base64) 'base64)
389 "=?" (downcase (symbol-name mime-charset)) "?"
390 (downcase (symbol-name encoding)) "?"))
391 (factor (case mime-charset
392 ((iso-8859-5 iso-8859-7 iso-8859-8 koi8-r) 1)
393 ((big5 gb2312 euc-kr) 2)
396 (pre (- b (save-restriction
399 ;; encoded-words must not be longer than 75 characters,
400 ;; including charset, encoding etc. This leaves us with
401 ;; 75 - (length start) - 2 - 2 characters. The last 2 is for
402 ;; possible base64 padding. In the worst case (iso-2022-*)
403 ;; each character expands to 8 bytes which is expanded by a
404 ;; factor of 4/3 by base64 encoding.
405 (length (floor (- 75 (length start) 4) (* factor (/ 4.0 3.0))))
406 ;; Limit line length to 76 characters.
407 (length1 (max 1 (floor (- 76 (length start) 4 pre)
408 (* factor (/ 4.0 3.0)))))
412 (narrow-to-region b e)
413 (when (eq encoding 'B)
414 ;; break into lines before encoding
415 (goto-char (point-min))
419 (goto-char (min (point-max) (+ length1 (point))))
421 (goto-char (min (point-max) (+ length (point)))))
425 (if (and (mm-multibyte-p)
426 (mm-coding-system-p cs))
427 (mm-encode-coding-region (point-min) (point-max) cs))
428 (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
429 (point-min) (point-max))
430 (goto-char (point-min))
438 (forward-line 1))))))
440 (defun rfc2047-fold-field ()
441 "Fold the current header field."
444 (rfc2047-narrow-to-field)
445 (rfc2047-fold-region (point-min) (point-max)))))
447 (defun rfc2047-fold-region (b e)
448 "Fold long lines in region B to E."
450 (narrow-to-region b e)
451 (goto-char (point-min))
455 (bol (save-restriction
459 (when (and (or break qword-break)
460 (> (- (point) bol) 76))
461 (goto-char (or break qword-break))
464 (if (looking-at "[ \t]")
467 (setq bol (1- (point)))
468 ;; Don't break before the first non-LWSP characters.
469 (skip-chars-forward " \t")
473 ((eq (char-after) ?\n)
478 (skip-chars-forward " \t")
479 (unless (or (eobp) (eq (char-after) ?\n))
481 ((eq (char-after) ?\r)
483 ((memq (char-after) '(? ?\t))
484 (skip-chars-forward " \t")
486 ;; Don't break just after the header name.
488 (setq break (1- (point)))))
490 (if (not (looking-at "=\\?[^=]"))
491 (if (eq (char-after) ?=)
493 (skip-chars-forward "^ \t\n\r="))
494 ;; Don't break at the start of the field.
495 (unless (= (point) b)
496 (setq qword-break (point)))
497 (skip-chars-forward "^ \t\n\r")))
499 (skip-chars-forward "^ \t\n\r"))))
500 (when (and (or break qword-break)
501 (> (- (point) bol) 76))
502 (goto-char (or break qword-break))
505 (if (looking-at "[ \t]")
508 (setq bol (1- (point)))
509 ;; Don't break before the first non-LWSP characters.
510 (skip-chars-forward " \t")
512 (forward-char 1))))))
514 (defun rfc2047-unfold-field ()
515 "Fold the current line."
518 (rfc2047-narrow-to-field)
519 (rfc2047-unfold-region (point-min) (point-max)))))
521 (defun rfc2047-unfold-region (b e)
522 "Unfold lines in region B to E."
524 (narrow-to-region b e)
525 (goto-char (point-min))
526 (let ((bol (save-restriction
529 (eol (point-at-eol)))
532 (if (and (looking-at "[ \t]")
533 (< (- (point-at-eol) bol) 76))
534 (delete-region eol (progn
536 (skip-chars-forward "\r\n")
538 (setq bol (point-at-bol)))
539 (setq eol (point-at-eol))
542 (defun rfc2047-b-encode-region (b e)
543 "Base64-encode the header contained in region B to E."
545 (narrow-to-region (goto-char b) e)
547 (base64-encode-region (point) (progn (end-of-line) (point)) t)
548 (if (and (bolp) (eolp))
549 (delete-backward-char 1))
552 (defun rfc2047-q-encode-region (b e)
553 "Quoted-printable-encode the header in region B to E."
556 (narrow-to-region (goto-char b) e)
557 (let ((bol (save-restriction
560 (quoted-printable-encode-region
562 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
563 ;; Avoid using 8bit characters.
564 ;; This list excludes `especials' (see the RFC2047 syntax),
565 ;; meaning that some characters in non-structured fields will
566 ;; get encoded when they con't need to be. The following is
567 ;; what it used to be.
568 ;;; ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
569 ;;; "\010\012\014\040-\074\076\100-\136\140-\177")
570 "-\b\n\f !#-'*+0-9A-Z\\^`-~\d")
571 (subst-char-in-region (point-min) (point-max) ? ?_)
572 ;; The size of QP encapsulation is about 20, so set limit to
574 (unless (< (- (point-max) (point-min)) 56)
575 ;; Don't break if it could fit in one line.
576 ;; Let rfc2047-encode-region break it later.
577 (goto-char (1+ (point-min)))
578 (while (and (not (bobp)) (not (eobp)))
579 (goto-char (min (point-max) (+ 56 bol)))
580 (search-backward "=" (- (point) 2) t)
581 (unless (or (bobp) (eobp))
583 (setq bol (point)))))))))
586 ;;; Functions for decoding RFC2047 messages
590 (defconst rfc2047-encoded-word-regexp
591 "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\
592 \\?\\([!->@-~ +]*\\)\\?="))
594 ;; Fixme: This should decode in place, not cons intermediate strings.
595 ;; Also check whether it needs to worry about delimiting fields like
598 ;; In fact it's reported that (invalid) encoding of mailboxes in
599 ;; addr-specs is in use, so delimiting fields might help. Probably
600 ;; not decoding a word which isn't properly delimited is good enough
601 ;; and worthwhile (is it more correct or not?), e.g. something like
602 ;; `=?iso-8859-1?q?foo?=@'.
604 (defun rfc2047-decode-region (start end)
605 "Decode MIME-encoded words in region between START and END."
607 (let ((case-fold-search t)
611 (narrow-to-region start end)
612 (goto-char (point-min))
613 ;; Remove whitespace between encoded words.
614 (while (re-search-forward
616 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
618 "\\(" rfc2047-encoded-word-regexp "\\)"))
620 (delete-region (goto-char (match-end 1)) (match-beginning 6)))
621 ;; Decode the encoded words.
622 (setq b (goto-char (point-min)))
623 (while (re-search-forward rfc2047-encoded-word-regexp nil t)
624 (setq e (match-beginning 0))
625 (insert (rfc2047-parse-and-decode
628 (delete-region (match-beginning 0) (match-end 0)))))
629 ;; Remove newlines between decoded words, though such things
630 ;; essentially must not be there.
632 (narrow-to-region e (point))
634 (while (re-search-forward "[\n\r]+" nil t)
636 (goto-char (point-max)))
637 (when (and (mm-multibyte-p)
639 (not (eq mail-parse-charset 'us-ascii))
640 (not (eq mail-parse-charset 'gnus-decoded)))
641 (mm-decode-coding-region b e mail-parse-charset))
643 (when (and (mm-multibyte-p)
645 (not (eq mail-parse-charset 'us-ascii))
646 (not (eq mail-parse-charset 'gnus-decoded)))
647 (mm-decode-coding-region b (point-max) mail-parse-charset))))))
649 (defun rfc2047-decode-string (string)
650 "Decode the quoted-printable-encoded STRING and return the results."
651 (let ((m (mm-multibyte-p)))
652 (if (string-match "=\\?" string)
654 ;; Fixme: This logic is wrong, but seems to be required by
655 ;; Gnus summary buffer generation. The value of `m' depends
656 ;; on the current buffer, not global multibyteness or that
657 ;; of the string. Also the string returned should always be
658 ;; multibyte in a multibyte session, i.e. the buffer should
659 ;; be multibyte before `buffer-string' is called.
661 (mm-enable-multibyte))
664 (rfc2047-decode-region (point-min) (point-max)))
666 ;; Fixme: As above, `m' here is inappropriate.
669 (not (eq mail-parse-charset 'us-ascii))
670 (not (eq mail-parse-charset 'gnus-decoded)))
671 ;; `decode-coding-string' in Emacs offers a third optional
672 ;; arg NOCOPY to avoid consing a new string if the decoding
673 ;; is "trivial". Unfortunately it currently doesn't
674 ;; consider anything else than a `nil' coding system
676 ;; `rfc2047-decode-string' is called multiple times for each
677 ;; article during summary buffer generation, and we really
678 ;; want to avoid unnecessary consing. So we bypass
679 ;; `decode-coding-string' if the string is purely ASCII.
680 (if (and (fboundp 'detect-coding-string)
681 ;; string is purely ASCII
682 (eq (detect-coding-string string t) 'undecided))
684 (mm-decode-coding-string string mail-parse-charset))
685 (mm-string-as-multibyte string)))))
687 (defun rfc2047-parse-and-decode (word)
688 "Decode WORD and return it if it is an encoded word.
689 Return WORD if it is not not an encoded word or if the charset isn't
691 (if (not (string-match rfc2047-encoded-word-regexp word))
696 (match-string 1 word)
697 (string-to-char (match-string 2 word))
698 (match-string 3 word))
700 word))) ; un-decodable
702 (defun rfc2047-pad-base64 (string)
703 "Pad STRING to quartets."
704 ;; Be more liberal to accept buggy base64 strings. If
705 ;; base64-decode-string accepts buggy strings, this function could
706 ;; be aliased to identity.
707 (case (mod (length string) 4)
709 (1 string) ;; Error, don't pad it.
710 (2 (concat string "=="))
711 (3 (concat string "="))))
713 (defun rfc2047-decode (charset encoding string)
714 "Decode STRING from the given MIME CHARSET in the given ENCODING.
715 Valid ENCODINGs are the characters \"B\" and \"Q\".
716 If your Emacs implementation can't decode CHARSET, return nil."
717 (if (stringp charset)
718 (setq charset (intern (downcase charset))))
719 (if (or (not charset)
720 (eq 'gnus-all mail-parse-ignored-charsets)
721 (memq 'gnus-all mail-parse-ignored-charsets)
722 (memq charset mail-parse-ignored-charsets))
723 (setq charset mail-parse-charset))
724 (let ((cs (mm-charset-to-coding-system charset)))
725 (if (and (not cs) charset
726 (listp mail-parse-ignored-charsets)
727 (memq 'gnus-unknown mail-parse-ignored-charsets))
728 (setq cs (mm-charset-to-coding-system mail-parse-charset)))
730 (when (and (eq cs 'ascii)
732 (setq cs mail-parse-charset))
733 (mm-decode-coding-string
735 ((char-equal ?B encoding)
736 (base64-decode-string
737 (rfc2047-pad-base64 string)))
738 ((char-equal ?Q encoding)
739 (quoted-printable-decode-string
740 (mm-subst-char-in-string ?_ ? string t)))
741 (t (error "Invalid encoding: %c" encoding)))
746 ;;; rfc2047.el ends here