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)
33 (unless (fboundp 'with-syntax-table) ; not in Emacs 20
34 (defmacro with-syntax-table (table &rest body)
35 "Evaluate BODY with syntax table of current buffer set to TABLE.
36 The syntax table of the current buffer is saved, BODY is evaluated, and the
37 saved table is restored, even in case of an abnormal exit.
38 Value is what BODY returns."
39 (let ((old-table (make-symbol "table"))
40 (old-buffer (make-symbol "buffer")))
41 `(let ((,old-table (syntax-table))
42 (,old-buffer (current-buffer)))
45 (set-syntax-table ,table)
48 (set-buffer ,old-buffer)
49 (set-syntax-table ,old-table))))))))
53 ;; Fixme: Avoid this (used for mail-parse-charset) mm dependence on gnus.
56 (autoload 'mm-body-7-or-8 "mm-bodies")
58 (defvar rfc2047-header-encoding-alist
59 '(("Newsgroups" . nil)
62 ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\
63 \\|Mail-Followup-To\\|Mail-Copies-To\\|Approved\\)" . address-mime)
65 "*Header/encoding method alist.
66 The list is traversed sequentially. The keys can either be
71 1) nil, in which case no encoding is done;
72 2) `mime', in which case the header will be encoded according to RFC2047;
73 3) `address-mime', like `mime', but takes account of the rules for address
74 fields (where quoted strings and comments must be treated separately);
75 4) a charset, in which case it will be encoded as that charset;
76 5) `default', in which case the field will be encoded as the rest
79 (defvar rfc2047-charset-encoding-alist
103 "Alist of MIME charsets to RFC2047 encodings.
104 Valid encodings are nil, `Q' and `B'. These indicate binary (no) encoding,
105 quoted-printable and base64 respectively.")
107 (defvar rfc2047-encoding-function-alist
108 '((Q . rfc2047-q-encode-region)
109 (B . rfc2047-b-encode-region)
111 "Alist of RFC2047 encodings to encoding functions.")
114 ;;; Functions for encoding RFC2047 messages
117 (defun rfc2047-narrow-to-field ()
118 "Narrow the buffer to the header on the current line."
124 (if (re-search-forward "^[^ \n\t]" nil t)
127 (goto-char (point-min)))
129 (defun rfc2047-field-value ()
130 "Return the value of the field at point."
133 (rfc2047-narrow-to-field)
134 (re-search-forward ":[ \t\n]*" nil t)
135 (buffer-substring (point) (point-max)))))
137 (defvar rfc2047-encoding-type 'address-mime
138 "The type of encoding done by `rfc2047-encode-region'.
139 This should be dynamically bound around calls to
140 `rfc2047-encode-region' to either `mime' or `address-mime'. See
141 `rfc2047-header-encoding-alist', for definitions.")
143 (defun rfc2047-encode-message-header ()
144 "Encode the message header according to `rfc2047-header-encoding-alist'.
145 Should be called narrowed to the head of the message."
148 (goto-char (point-min))
149 (let (alist elem method)
152 (rfc2047-narrow-to-field)
153 (if (not (rfc2047-encodable-p))
155 (if (and (eq (mm-body-7-or-8) '8bit)
158 (car message-posting-charset)))
159 ;; 8 bit must be decoded.
160 (mm-encode-coding-region
161 (point-min) (point-max)
162 (mm-charset-to-coding-system
163 (car message-posting-charset))))
164 ;; No encoding necessary, but folding is nice
167 (goto-char (point-min))
168 (skip-chars-forward "^:")
169 (when (looking-at ": ")
173 ;; We found something that may perhaps be encoded.
175 alist rfc2047-header-encoding-alist)
176 (while (setq elem (pop alist))
177 (when (or (and (stringp (car elem))
178 (looking-at (car elem)))
182 (goto-char (point-min))
183 (re-search-forward "^[^:]+: *" nil t)
185 ((eq method 'address-mime)
186 (rfc2047-encode-region (point) (point-max)))
188 (let ((rfc2047-encoding-type 'mime))
189 (rfc2047-encode-region (point) (point-max))))
190 ((eq method 'default)
191 (if (and (featurep 'mule)
192 (if (boundp 'default-enable-multibyte-characters)
193 default-enable-multibyte-characters)
195 (mm-encode-coding-region (point) (point-max)
196 mail-parse-charset)))
197 ;; We get this when CC'ing messsages to newsgroups with
198 ;; 8-bit names. The group name mail copy just got
199 ;; unconditionally encoded. Previously, it would ask
200 ;; whether to encode, which was quite confusing for the
201 ;; user. If the new behaviour is wrong, tell me. I have
202 ;; left the old code commented out below.
203 ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
204 ;; Modified by Dave Love, with the commented-out code changed
205 ;; in accordance with changes elsewhere.
207 (rfc2047-encode-region (point) (point-max)))
209 ;;; (if (or (message-options-get
210 ;;; 'rfc2047-encode-message-header-encode-any)
211 ;;; (message-options-set
212 ;;; 'rfc2047-encode-message-header-encode-any
214 ;;; "Some texts are not encoded. Encode anyway?")))
215 ;;; (rfc2047-encode-region (point-min) (point-max))
216 ;;; (error "Cannot send unencoded text")))
217 ((mm-coding-system-p method)
218 (if (and (featurep 'mule)
219 (if (boundp 'default-enable-multibyte-characters)
220 default-enable-multibyte-characters))
221 (mm-encode-coding-region (point) (point-max) method)))
224 (goto-char (point-max)))))))
226 ;; Fixme: This, and the require below may not be the Right Thing, but
227 ;; should be safe just before release. -- fx 2001-02-08
228 (eval-when-compile (defvar message-posting-charset))
230 (defun rfc2047-encodable-p ()
231 "Return non-nil if any characters in current buffer need encoding in headers.
232 The buffer may be narrowed."
233 (require 'message) ; for message-posting-charset
235 (mm-find-mime-charset-region (point-min) (point-max))))
237 (not (equal charsets (list (car message-posting-charset)))))))
239 ;; Use this syntax table when parsing into regions that may need
240 ;; encoding. Double quotes are string delimiters, backslash is
241 ;; character quoting, and all other RFC 2822 special characters are
242 ;; treated as punctuation so we can use forward-sexp/forward-word to
243 ;; skip to the end of regions appropriately. Nb. ietf-drums does
244 ;; things differently.
245 (defconst rfc2047-syntax-table
246 ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
247 (let ((table (make-syntax-table)))
248 ;; The following is done to work for setting all elements of the table
249 ;; in Emacs 21 and 22 and XEmacs; it appears to be the cleanest way.
250 ;; Play safe and don't assume the form of the word syntax entry --
252 (if (fboundp 'set-char-table-range) ; Emacs
253 (funcall (intern "set-char-table-range")
254 table t (aref (standard-syntax-table) ?a))
255 (if (fboundp 'put-char-table)
256 (if (fboundp 'get-char-table) ; warning avoidance
257 (put-char-table t (get-char-table ?a (standard-syntax-table))
259 (modify-syntax-entry ?\\ "\\" table)
260 (modify-syntax-entry ?\" "\"" 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)
273 (defun rfc2047-encode-region (b e)
274 "Encode words in region B to E that need encoding.
275 By default, the region is treated as containing RFC2822 addresses.
276 Dynamically bind `rfc2047-encoding-type' to change that."
278 (narrow-to-region b e)
279 (if (eq 'mime rfc2047-encoding-type)
280 ;; Simple case. Treat as single word after any initial ASCII
281 ;; part and before any tailing ASCII part. The leading ASCII
282 ;; is relevant for instance in Subject headers with `Re:' for
283 ;; interoperability with non-MIME clients, and we might as
284 ;; well avoid the tail too.
286 (goto-char (point-min))
287 ;; Does it need encoding?
288 (skip-chars-forward "\000-\177")
290 (skip-chars-backward "^ \n") ; beginning of space-delimited word
291 (rfc2047-encode (point) (progn
293 (skip-chars-backward "\000-\177")
294 (skip-chars-forward "^ \n")
295 ;; end of space-delimited word
297 ;; `address-mime' case -- take care of quoted words, comments.
298 (with-syntax-table rfc2047-syntax-table
299 (let ((start) ; start of current token
300 end ; end of current token
301 ;; Whether there's an encoded word before the current
302 ;; token, either immediately or separated by space.
304 (goto-char (point-min))
305 (condition-case nil ; in case of unbalanced quotes
306 ;; Look for rfc2822-style: sequences of atoms, quoted
307 ;; strings, specials, whitespace. (Specials mustn't be
312 (unless (= 0 (skip-chars-forward " \t\n"))
313 (setq start (point)))
315 ((not (char-after))) ; eob
317 ((eq ?\" (char-syntax (char-after)))
321 ;; Does it need encoding?
323 (skip-chars-forward "\000-\177" end)
325 (setq last-encoded nil)
326 ;; It needs encoding. Strip the quotes first,
327 ;; since encoded words can't occur in quotes.
329 (delete-backward-char 1)
333 ;; There was a preceding quoted word. We need
334 ;; to include any separating whitespace in this
335 ;; word to avoid it getting lost.
336 (skip-chars-backward " \t")
337 ;; A space is needed between the encoded words.
341 ;; Adjust the end position for the deleted quotes.
342 (rfc2047-encode start (- end 2))
343 (setq last-encoded t))) ; record that it was encoded
344 ((eq ?. (char-syntax (char-after)))
345 ;; Skip other delimiters, but record that they've
346 ;; potentially separated quoted words.
348 (setq last-encoded nil))
349 (t ; normal token/whitespace sequence
352 (skip-chars-backward " \t")
354 ;; Deal with encoding and leading space as for
357 (skip-chars-forward "\000-\177" end)
359 (setq last-encoded nil)
362 (skip-chars-backward " \t")
366 (rfc2047-encode start end)
367 (setq last-encoded t)))))
369 (error "Invalid data for rfc2047 encoding: %s"
370 (buffer-substring b e)))))))
371 (rfc2047-fold-region b (point))))
373 (defun rfc2047-encode-string (string)
374 "Encode words in STRING.
375 By default, the string is treated as containing addresses (see
376 `rfc2047-encoding-type')."
379 (rfc2047-encode-region (point-min) (point-max))
382 (defun rfc2047-encode (b e)
383 "Encode the word(s) in the region B to E.
384 By default, the region is treated as containing addresses (see
385 `rfc2047-encoding-type')."
386 (let* ((mime-charset (mm-find-mime-charset-region b e))
387 (cs (if (> (length mime-charset) 1)
388 ;; Fixme: Instead of this, try to break region into
389 ;; parts that can be encoded separately.
390 (error "Can't rfc2047-encode `%s'"
391 (buffer-substring b e))
392 (setq mime-charset (car mime-charset))
393 (mm-charset-to-coding-system mime-charset)))
394 ;; Fixme: Better, calculate the number of non-ASCII
395 ;; characters, at least for 8-bit charsets.
396 (encoding (or (cdr (assq mime-charset
397 rfc2047-charset-encoding-alist))
398 ;; For the charsets that don't have a preferred
399 ;; encoding, choose the one that's shorter.
401 (narrow-to-region b e)
402 (if (eq (mm-qp-or-base64) 'base64)
406 "=?" (downcase (symbol-name mime-charset)) "?"
407 (downcase (symbol-name encoding)) "?"))
408 (factor (case mime-charset
409 ((iso-8859-5 iso-8859-7 iso-8859-8 koi8-r) 1)
410 ((big5 gb2312 euc-kr) 2)
413 (pre (- b (save-restriction
416 ;; encoded-words must not be longer than 75 characters,
417 ;; including charset, encoding etc. This leaves us with
418 ;; 75 - (length start) - 2 - 2 characters. The last 2 is for
419 ;; possible base64 padding. In the worst case (iso-2022-*)
420 ;; each character expands to 8 bytes which is expanded by a
421 ;; factor of 4/3 by base64 encoding.
422 (length (floor (- 75 (length start) 4) (* factor (/ 4.0 3.0))))
423 ;; Limit line length to 76 characters.
424 (length1 (max 1 (floor (- 76 (length start) 4 pre)
425 (* factor (/ 4.0 3.0)))))
429 (narrow-to-region b e)
430 (when (eq encoding 'B)
431 ;; break into lines before encoding
432 (goto-char (point-min))
436 (goto-char (min (point-max) (+ length1 (point))))
438 (goto-char (min (point-max) (+ length (point)))))
442 (if (and (mm-multibyte-p)
443 (mm-coding-system-p cs))
444 (mm-encode-coding-region (point-min) (point-max) cs))
445 (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
446 (point-min) (point-max))
447 (goto-char (point-min))
455 (forward-line 1))))))
457 (defun rfc2047-fold-field ()
458 "Fold the current header field."
461 (rfc2047-narrow-to-field)
462 (rfc2047-fold-region (point-min) (point-max)))))
464 (defun rfc2047-fold-region (b e)
465 "Fold long lines in region B to E."
467 (narrow-to-region b e)
468 (goto-char (point-min))
472 (bol (save-restriction
476 (when (and (or break qword-break)
477 (> (- (point) bol) 76))
478 (goto-char (or break qword-break))
481 (if (looking-at "[ \t]")
484 (setq bol (1- (point)))
485 ;; Don't break before the first non-LWSP characters.
486 (skip-chars-forward " \t")
490 ((eq (char-after) ?\n)
495 (skip-chars-forward " \t")
496 (unless (or (eobp) (eq (char-after) ?\n))
498 ((eq (char-after) ?\r)
500 ((memq (char-after) '(? ?\t))
501 (skip-chars-forward " \t")
503 ;; Don't break just after the header name.
505 (setq break (1- (point)))))
507 (if (not (looking-at "=\\?[^=]"))
508 (if (eq (char-after) ?=)
510 (skip-chars-forward "^ \t\n\r="))
511 ;; Don't break at the start of the field.
512 (unless (= (point) b)
513 (setq qword-break (point)))
514 (skip-chars-forward "^ \t\n\r")))
516 (skip-chars-forward "^ \t\n\r"))))
517 (when (and (or break qword-break)
518 (> (- (point) bol) 76))
519 (goto-char (or break qword-break))
522 (if (looking-at "[ \t]")
525 (setq bol (1- (point)))
526 ;; Don't break before the first non-LWSP characters.
527 (skip-chars-forward " \t")
529 (forward-char 1))))))
531 (defun rfc2047-unfold-field ()
532 "Fold the current line."
535 (rfc2047-narrow-to-field)
536 (rfc2047-unfold-region (point-min) (point-max)))))
538 (defun rfc2047-unfold-region (b e)
539 "Unfold lines in region B to E."
541 (narrow-to-region b e)
542 (goto-char (point-min))
543 (let ((bol (save-restriction
546 (eol (point-at-eol)))
549 (if (and (looking-at "[ \t]")
550 (< (- (point-at-eol) bol) 76))
551 (delete-region eol (progn
553 (skip-chars-forward "\r\n")
555 (setq bol (point-at-bol)))
556 (setq eol (point-at-eol))
559 (defun rfc2047-b-encode-region (b e)
560 "Base64-encode the header contained in region B to E."
562 (narrow-to-region (goto-char b) e)
564 (base64-encode-region (point) (progn (end-of-line) (point)) t)
565 (if (and (bolp) (eolp))
566 (delete-backward-char 1))
569 (defun rfc2047-q-encode-region (b e)
570 "Quoted-printable-encode the header in region B to E."
573 (narrow-to-region (goto-char b) e)
574 (let ((bol (save-restriction
577 (quoted-printable-encode-region
579 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
580 ;; Avoid using 8bit characters.
581 ;; This list excludes `especials' (see the RFC2047 syntax),
582 ;; meaning that some characters in non-structured fields will
583 ;; get encoded when they con't need to be. The following is
584 ;; what it used to be.
585 ;;; ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
586 ;;; "\010\012\014\040-\074\076\100-\136\140-\177")
587 "-\b\n\f !#-'*+0-9A-Z\\^`-~\d")
588 (subst-char-in-region (point-min) (point-max) ? ?_)
589 ;; The size of QP encapsulation is about 20, so set limit to
591 (unless (< (- (point-max) (point-min)) 56)
592 ;; Don't break if it could fit in one line.
593 ;; Let rfc2047-encode-region break it later.
594 (goto-char (1+ (point-min)))
595 (while (and (not (bobp)) (not (eobp)))
596 (goto-char (min (point-max) (+ 56 bol)))
597 (search-backward "=" (- (point) 2) t)
598 (unless (or (bobp) (eobp))
600 (setq bol (point)))))))))
603 ;;; Functions for decoding RFC2047 messages
607 (defconst rfc2047-encoded-word-regexp
608 "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\
609 \\?\\([!->@-~ +]*\\)\\?="))
611 ;; Fixme: This should decode in place, not cons intermediate strings.
612 ;; Also check whether it needs to worry about delimiting fields like
615 ;; In fact it's reported that (invalid) encoding of mailboxes in
616 ;; addr-specs is in use, so delimiting fields might help. Probably
617 ;; not decoding a word which isn't properly delimited is good enough
618 ;; and worthwhile (is it more correct or not?), e.g. something like
619 ;; `=?iso-8859-1?q?foo?=@'.
621 (defun rfc2047-decode-region (start end)
622 "Decode MIME-encoded words in region between START and END."
624 (let ((case-fold-search t)
628 (narrow-to-region start end)
629 (goto-char (point-min))
630 ;; Remove whitespace between encoded words.
631 (while (re-search-forward
633 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
635 "\\(" rfc2047-encoded-word-regexp "\\)"))
637 (delete-region (goto-char (match-end 1)) (match-beginning 6)))
638 ;; Decode the encoded words.
639 (setq b (goto-char (point-min)))
640 (while (re-search-forward rfc2047-encoded-word-regexp nil t)
641 (setq e (match-beginning 0))
642 (insert (rfc2047-parse-and-decode
645 (delete-region (match-beginning 0) (match-end 0)))))
646 ;; Remove newlines between decoded words, though such things
647 ;; essentially must not be there.
649 (narrow-to-region e (point))
651 (while (re-search-forward "[\n\r]+" nil t)
653 (goto-char (point-max)))
654 (when (and (mm-multibyte-p)
656 (not (eq mail-parse-charset 'us-ascii))
657 (not (eq mail-parse-charset 'gnus-decoded)))
658 (mm-decode-coding-region b e mail-parse-charset))
660 (when (and (mm-multibyte-p)
662 (not (eq mail-parse-charset 'us-ascii))
663 (not (eq mail-parse-charset 'gnus-decoded)))
664 (mm-decode-coding-region b (point-max) mail-parse-charset))))))
666 (defun rfc2047-decode-string (string)
667 "Decode the quoted-printable-encoded STRING and return the results."
668 (let ((m (mm-multibyte-p)))
669 (if (string-match "=\\?" string)
671 ;; Fixme: This logic is wrong, but seems to be required by
672 ;; Gnus summary buffer generation. The value of `m' depends
673 ;; on the current buffer, not global multibyteness or that
674 ;; of the string. Also the string returned should always be
675 ;; multibyte in a multibyte session, i.e. the buffer should
676 ;; be multibyte before `buffer-string' is called.
678 (mm-enable-multibyte))
681 (rfc2047-decode-region (point-min) (point-max)))
683 ;; Fixme: As above, `m' here is inappropriate.
686 (not (eq mail-parse-charset 'us-ascii))
687 (not (eq mail-parse-charset 'gnus-decoded)))
688 (mm-decode-coding-string string mail-parse-charset)
689 (mm-string-as-multibyte string)))))
691 (defun rfc2047-parse-and-decode (word)
692 "Decode WORD and return it if it is an encoded word.
693 Return WORD if it is not not an encoded word or if the charset isn't
695 (if (not (string-match rfc2047-encoded-word-regexp word))
700 (match-string 1 word)
701 (upcase (match-string 2 word))
702 (match-string 3 word))
704 word))) ; un-decodable
706 (defun rfc2047-pad-base64 (string)
707 "Pad STRING to quartets."
708 ;; Be more liberal to accept buggy base64 strings. If
709 ;; base64-decode-string accepts buggy strings, this function could
710 ;; be aliased to identity.
711 (case (mod (length string) 4)
713 (1 string) ;; Error, don't pad it.
714 (2 (concat string "=="))
715 (3 (concat string "="))))
717 (defun rfc2047-decode (charset encoding string)
718 "Decode STRING from the given MIME CHARSET in the given ENCODING.
719 Valid ENCODINGs are \"B\" and \"Q\".
720 If your Emacs implementation can't decode CHARSET, return nil."
721 (if (stringp charset)
722 (setq charset (intern (downcase charset))))
723 (if (or (not charset)
724 (eq 'gnus-all mail-parse-ignored-charsets)
725 (memq 'gnus-all mail-parse-ignored-charsets)
726 (memq charset mail-parse-ignored-charsets))
727 (setq charset mail-parse-charset))
728 (let ((cs (mm-charset-to-coding-system charset)))
729 (if (and (not cs) charset
730 (listp mail-parse-ignored-charsets)
731 (memq 'gnus-unknown mail-parse-ignored-charsets))
732 (setq cs (mm-charset-to-coding-system mail-parse-charset)))
734 (when (and (eq cs 'ascii)
736 (setq cs mail-parse-charset))
737 (mm-decode-coding-string
739 ((equal "B" encoding)
740 (base64-decode-string
741 (rfc2047-pad-base64 string)))
742 ((equal "Q" encoding)
743 (quoted-printable-decode-string
744 (mm-replace-chars-in-string string ?_ ? )))
745 (t (error "Invalid encoding: %s" encoding)))
750 ;;; rfc2047.el ends here