2001-01-21 00:00:00 ShengHuo ZHU <zsh@cs.rochester.edu>
[gnus] / lisp / rfc2047.el
1 ;;; rfc2047.el --- Functions for encoding and decoding rfc2047 messages
2 ;; Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; This file is part of GNU Emacs.
7
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)
11 ;; any later version.
12
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.
17
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.
22
23 ;;; Commentary:
24
25 ;; RFC 2047 is "MIME (Multipurpose Internet Mail Extensions) Part
26 ;; Three:  Message Header Extensions for Non-ASCII Text".
27
28 ;;; Code:
29
30 (eval-when-compile (require 'cl))
31
32 (require 'qp)
33 (require 'mm-util)
34 (require 'ietf-drums)
35 (require 'mail-prsvr)
36 (require 'base64)
37 ;; Fixme: Avoid this (for gnus-point-at-...) mm dependence on gnus.
38 (require 'gnus-util)
39 (autoload 'mm-body-7-or-8 "mm-bodies")
40
41 (defvar rfc2047-header-encoding-alist
42   '(("Newsgroups" . nil)
43     ("Message-ID" . nil)
44     ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\)" .
45      "-A-Za-z0-9!*+/=_")
46     (t . mime))
47   "*Header/encoding method alist.
48 The list is traversed sequentially.  The keys can either be
49 header regexps or t.
50
51 The values can be:
52
53 1) nil, in which case no encoding is done;
54 2) `mime', in which case the header will be encoded according to RFC2047;
55 3) a charset, in which case it will be encoded as that charset;
56 4) `default', in which case the field will be encoded as the rest
57    of the article.
58 5) a string, like `mime', expect for using it as word-chars.")
59
60 (defvar rfc2047-charset-encoding-alist
61   '((us-ascii . nil)
62     (iso-8859-1 . Q)
63     (iso-8859-2 . Q)
64     (iso-8859-3 . Q)
65     (iso-8859-4 . Q)
66     (iso-8859-5 . B)
67     (koi8-r . B)
68     (iso-8859-7 . Q)
69     (iso-8859-8 . Q)
70     (iso-8859-9 . Q)
71     (iso-8859-14 . Q)
72     (iso-8859-15 . Q)
73     (iso-2022-jp . B)
74     (iso-2022-kr . B)
75     (gb2312 . B)
76     (cn-gb . B)
77     (cn-gb-2312 . B)
78     (euc-kr . B)
79     (iso-2022-jp-2 . B)
80     (iso-2022-int-1 . B))
81   "Alist of MIME charsets to RFC2047 encodings.
82 Valid encodings are nil, `Q' and `B'.")
83
84 (defvar rfc2047-encoding-function-alist
85   '((Q . rfc2047-q-encode-region)
86     (B . rfc2047-b-encode-region)
87     (nil . ignore))
88   "Alist of RFC2047 encodings to encoding functions.")
89
90 (defvar rfc2047-q-encoding-alist
91   '(("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\):"
92      . "-A-Za-z0-9!*+/" )
93     ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
94     ;; Avoid using 8bit characters. Some versions of Emacs has bug!
95     ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
96     ("." . "\010\012\014\040-\074\076\100-\136\140-\177"))
97   "Alist of header regexps and valid Q characters.")
98
99 ;;;
100 ;;; Functions for encoding RFC2047 messages
101 ;;;
102
103 (defun rfc2047-narrow-to-field ()
104   "Narrow the buffer to the header on the current line."
105   (beginning-of-line)
106   (narrow-to-region
107    (point)
108    (progn
109      (forward-line 1)
110      (if (re-search-forward "^[^ \n\t]" nil t)
111          (progn
112            (beginning-of-line)
113            (point))
114        (point-max))))
115   (goto-char (point-min)))
116
117 (defun rfc2047-encode-message-header ()
118   "Encode the message header according to `rfc2047-header-encoding-alist'.
119 Should be called narrowed to the head of the message."
120   (interactive "*")
121   (save-excursion
122     (goto-char (point-min))
123     (let (alist elem method)
124       (while (not (eobp))
125         (save-restriction
126           (rfc2047-narrow-to-field)
127           (if (not (rfc2047-encodable-p))
128               (if (and (eq (mm-body-7-or-8) '8bit)
129                        (mm-multibyte-p)
130                        (mm-coding-system-p
131                         (car message-posting-charset)))
132                        ;; 8 bit must be decoded.
133                        ;; Is message-posting-charset a coding system?
134                        (mm-encode-coding-region
135                         (point-min) (point-max)
136                         (car message-posting-charset)))
137             ;; We found something that may perhaps be encoded.
138             (setq method nil
139                   alist rfc2047-header-encoding-alist)
140             (while (setq elem (pop alist))
141               (when (or (and (stringp (car elem))
142                              (looking-at (car elem)))
143                         (eq (car elem) t))
144                 (setq alist nil
145                       method (cdr elem))))
146             (cond
147              ((stringp method)
148               (rfc2047-encode-region (point-min) (point-max) method))
149              ((eq method 'mime)
150               (rfc2047-encode-region (point-min) (point-max)))
151              ((eq method 'default)
152               (if (and (featurep 'mule)
153                        (if (boundp 'default-enable-multibyte-characters)
154                            default-enable-multibyte-characters)
155                        mail-parse-charset)
156                   (mm-encode-coding-region (point-min) (point-max)
157                                            mail-parse-charset)))
158              ((null method)
159               (and (delq 'ascii
160                          (mm-find-charset-region (point-min)
161                                                  (point-max)))
162                    (if (or (message-options-get
163                             'rfc2047-encode-message-header-encode-any)
164                            (message-options-set
165                             'rfc2047-encode-message-header-encode-any
166                             (y-or-n-p
167                              "Some texts are not encoded. Encode anyway?")))
168                        (rfc2047-encode-region (point-min) (point-max))
169                      (error "Cannot send unencoded text."))))
170              ((mm-coding-system-p method)
171               (if (and (featurep 'mule)
172                        (if (boundp 'default-enable-multibyte-characters)
173                            default-enable-multibyte-characters))
174                   (mm-encode-coding-region (point-min) (point-max) method)))
175              ;; Hm.
176              (t)))
177           (goto-char (point-max)))))))
178
179 (defun rfc2047-encodable-p ()
180   "Return non-nil if any characters in current buffer need encoding in headers.
181 The buffer may be narrowed."
182   (let ((charsets
183          (mapcar
184           'mm-mime-charset
185           (mm-find-charset-region (point-min) (point-max))))
186         (cs (list 'us-ascii (car message-posting-charset)))
187         found)
188     (while charsets
189       (unless (memq (pop charsets) cs)
190         (setq found t)))
191     found))
192
193 (defun rfc2047-dissect-region (b e &optional word-chars)
194   "Dissect the region between B and E into words."
195   (unless word-chars
196     ;; Anything except most CTLs, WSP
197     (setq word-chars "\010\012\014\041-\177"))
198   (let (mail-parse-mule-charset
199         words point current
200         result word)
201     (save-restriction
202       (narrow-to-region b e)
203       (goto-char (point-min))
204       (skip-chars-forward "\000-\177")
205       (while (not (eobp))
206         (setq point (point))
207         (skip-chars-backward word-chars b)
208         (unless (eq b (point))
209           (push (cons (buffer-substring b (point)) nil) words))
210         (setq b (point))
211         (goto-char point)
212         (setq current (mm-charset-after))
213         (forward-char 1)
214         (skip-chars-forward word-chars)
215         (while (and (not (eobp))
216                     (eq (mm-charset-after) current))
217           (forward-char 1)
218           (skip-chars-forward word-chars))
219         (unless (eq b (point))
220           (push (cons (buffer-substring b (point)) current) words))
221         (setq b (point))
222         (skip-chars-forward "\000-\177"))
223       (unless (eq b (point))
224         (push (cons (buffer-substring b (point)) nil) words)))
225     ;; merge adjacent words
226     (setq word (pop words))
227     (while word
228       (if (and (cdr word)
229                (caar words)
230                (not (cdar words))
231                (not (string-match "[^ \t]" (caar words))))
232           (if (eq (cdr (nth 1 words)) (cdr word))
233               (progn
234                 (setq word (cons (concat
235                                   (car (nth 1 words)) (caar words)
236                                   (car word))
237                                  (cdr word)))
238                 (pop words)
239                 (pop words))
240             (push (cons (concat (caar words) (car word)) (cdr word))
241                   result)
242             (pop words)
243             (setq word (pop words)))
244         (push word result)
245         (setq word (pop words))))
246     result))
247
248 (defun rfc2047-encode-region (b e &optional word-chars)
249   "Encode all encodable words in region."
250   (let ((words (rfc2047-dissect-region b e word-chars)) word)
251     (save-restriction
252       (narrow-to-region b e)
253       (delete-region (point-min) (point-max))
254       (while (setq word (pop words))
255         (if (not (cdr word))
256             (insert (car word))
257           (rfc2047-fold-region (gnus-point-at-bol) (point))
258           (goto-char (point-max))
259           (if (> (- (point) (save-restriction
260                               (widen)
261                               (gnus-point-at-bol))) 76)
262               (insert "\n "))
263           ;; Insert blank between encoded words
264           (if (eq (char-before) ?=) (insert " "))
265           (rfc2047-encode (point)
266                           (progn (insert (car word)) (point))
267                           (cdr word))))
268       (rfc2047-fold-region (point-min) (point-max)))))
269
270 (defun rfc2047-encode-string (string &optional word-chars)
271   "Encode words in STRING."
272   (with-temp-buffer
273     (insert string)
274     (rfc2047-encode-region (point-min) (point-max) word-chars)
275     (buffer-string)))
276
277 (defun rfc2047-encode (b e charset)
278   "Encode the word in the region B to E with CHARSET."
279   (let* ((mime-charset (mm-mime-charset charset))
280          (encoding (or (cdr (assq mime-charset
281                                   rfc2047-charset-encoding-alist))
282                        'B))
283          (start (concat
284                  "=?" (downcase (symbol-name mime-charset)) "?"
285                  (downcase (symbol-name encoding)) "?"))
286          (first t))
287     (save-restriction
288       (narrow-to-region b e)
289       (when (eq encoding 'B)
290         ;; break into lines before encoding
291         (goto-char (point-min))
292         (while (not (eobp))
293           (goto-char (min (point-max) (+ 15 (point))))
294           (unless (eobp)
295             (insert "\n"))))
296       (if (and (mm-multibyte-p)
297                (mm-coding-system-p mime-charset))
298           (mm-encode-coding-region (point-min) (point-max) mime-charset))
299       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
300                (point-min) (point-max))
301       (goto-char (point-min))
302       (while (not (eobp))
303         (unless first
304           (insert " "))
305         (setq first nil)
306         (insert start)
307         (end-of-line)
308         (insert "?=")
309         (forward-line 1)))))
310
311 (defun rfc2047-fold-region (b e)
312   "Fold long lines in the region."
313   (save-restriction
314     (narrow-to-region b e)
315     (goto-char (point-min))
316     (let ((break nil)
317           (qword-break nil)
318           (bol (save-restriction
319                  (widen)
320                  (gnus-point-at-bol))))
321       (while (not (eobp))
322         (when (and (or break qword-break) (> (- (point) bol) 76))
323           (goto-char (or break qword-break))
324           (setq break nil
325                 qword-break nil)
326           (if (looking-at " \t")
327               (insert "\n")
328             (insert "\n "))
329           (setq bol (1- (point)))
330           ;; Don't break before the first non-LWSP characters.
331           (skip-chars-forward " \t")
332           (forward-char 1))
333         (cond
334          ((eq (char-after) ?\n)
335           (forward-char 1)
336           (setq bol (point)
337                 break nil
338                 qword-break nil)
339           (skip-chars-forward " \t")
340           (unless (or (eobp) (eq (char-after) ?\n))
341             (forward-char 1)))
342          ((eq (char-after) ?\r)
343           (forward-char 1))
344          ((memq (char-after) '(?  ?\t))
345           (skip-chars-forward " \t")
346           (setq break (1- (point))))
347          ((not break)
348           (if (not (looking-at "=\\?[^=]"))
349               (if (eq (char-after) ?=)
350                   (forward-char 1)
351                 (skip-chars-forward "^ \t\n\r="))
352             (setq qword-break (point))
353             (skip-chars-forward "^ \t\n\r")))
354          (t
355           (skip-chars-forward "^ \t\n\r"))))
356       (when (and (or break qword-break) (> (- (point) bol) 76))
357         (goto-char (or break qword-break))
358         (setq break nil
359               qword-break nil)
360           (if (looking-at " \t")
361               (insert "\n")
362             (insert "\n "))
363         (setq bol (1- (point)))
364         ;; Don't break before the first non-LWSP characters.
365         (skip-chars-forward " \t")
366         (forward-char 1)))))
367
368 (defun rfc2047-unfold-region (b e)
369   "Unfold lines in the region."
370   (save-restriction
371     (narrow-to-region b e)
372     (goto-char (point-min))
373     (let ((bol (save-restriction
374                  (widen)
375                  (gnus-point-at-bol)))
376           (eol (gnus-point-at-eol))
377           leading)
378       (forward-line 1)
379       (while (not (eobp))
380         (looking-at "[ \t]*")
381         (setq leading (- (match-end 0) (match-beginning 0)))
382         (if (< (- (gnus-point-at-eol) bol leading) 76)
383             (progn
384               (goto-char eol)
385               (delete-region eol (progn
386                                    (skip-chars-forward "[ \t\n\r]+")
387                                    (1- (point)))))
388           (setq bol (gnus-point-at-bol)))
389         (setq eol (gnus-point-at-eol))
390         (forward-line 1)))))
391
392 (defun rfc2047-b-encode-region (b e)
393   "Base64-encode the header contained in region B to E."
394   (save-restriction
395     (narrow-to-region (goto-char b) e)
396     (while (not (eobp))
397       (base64-encode-region (point) (progn (end-of-line) (point)) t)
398       (if (and (bolp) (eolp))
399           (delete-backward-char 1))
400       (forward-line))))
401
402 (defun rfc2047-q-encode-region (b e)
403   "Quoted-printable-encode the header in region B to E."
404   (save-excursion
405     (save-restriction
406       (narrow-to-region (goto-char b) e)
407       (let ((alist rfc2047-q-encoding-alist)
408             (bol (save-restriction
409                    (widen)
410                    (gnus-point-at-bol))))
411         (while alist
412           (when (looking-at (caar alist))
413             (quoted-printable-encode-region b e nil (cdar alist))
414             (subst-char-in-region (point-min) (point-max) ?  ?_)
415             (setq alist nil))
416           (pop alist))
417         ;; The size of QP encapsulation is about 20, so set limit to
418         ;; 56=76-20.
419         (unless (< (- (point-max) (point-min)) 56)
420           ;; Don't break if it could fit in one line.
421           ;; Let rfc2047-encode-region break it later.
422           (goto-char (1+ (point-min)))
423           (while (and (not (bobp)) (not (eobp)))
424             (goto-char (min (point-max) (+ 56 bol)))
425             (search-backward "=" (- (point) 2) t)
426             (unless (or (bobp) (eobp))
427               (insert "\n")
428               (setq bol (point)))))))))
429
430 ;;;
431 ;;; Functions for decoding RFC2047 messages
432 ;;;
433
434 (defvar rfc2047-encoded-word-regexp
435   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]*\\)\\?=")
436
437 (defun rfc2047-decode-region (start end)
438   "Decode MIME-encoded words in region between START and END."
439   (interactive "r")
440   (let ((case-fold-search t)
441         b e)
442     (save-excursion
443       (save-restriction
444         (narrow-to-region start end)
445         (goto-char (point-min))
446         ;; Remove whitespace between encoded words.
447         (while (re-search-forward
448                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
449                         "\\(\n?[ \t]\\)+"
450                         "\\(" rfc2047-encoded-word-regexp "\\)")
451                 nil t)
452           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
453         ;; Decode the encoded words.
454         (setq b (goto-char (point-min)))
455         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
456           (setq e (match-beginning 0))
457           (insert (rfc2047-parse-and-decode
458                    (prog1
459                        (match-string 0)
460                      (delete-region (match-beginning 0) (match-end 0)))))
461           (when (and (mm-multibyte-p)
462                      mail-parse-charset
463                      (not (eq mail-parse-charset 'gnus-decoded)))
464             (mm-decode-coding-region b e mail-parse-charset))
465           (setq b (point)))
466         (when (and (mm-multibyte-p)
467                    mail-parse-charset
468                    (not (eq mail-parse-charset 'us-ascii))
469                    (not (eq mail-parse-charset 'gnus-decoded)))
470           (mm-decode-coding-region b (point-max) mail-parse-charset))
471         (rfc2047-unfold-region (point-min) (point-max))))))
472
473 (defun rfc2047-decode-string (string)
474   "Decode the quoted-printable-encoded STRING and return the results."
475   (let ((m (mm-multibyte-p)))
476     (with-temp-buffer
477       (when m
478         (mm-enable-multibyte))
479       (insert string)
480       (inline
481         (rfc2047-decode-region (point-min) (point-max)))
482       (buffer-string))))
483
484 (defun rfc2047-parse-and-decode (word)
485   "Decode WORD and return it if it is an encoded word.
486 Return WORD if not."
487   (if (not (string-match rfc2047-encoded-word-regexp word))
488       word
489     (or
490      (condition-case nil
491          (rfc2047-decode
492           (match-string 1 word)
493           (upcase (match-string 2 word))
494           (match-string 3 word))
495        (error word))
496      word)))
497
498 (defun rfc2047-pad-base64 (string)
499   "Pad STRING to quartets."
500   ;; Be more liberal to accept buggy base64 strings. If
501   ;; base64-decode-string accepts buggy strings, this function could
502   ;; be aliased to identity.
503   (case (mod (length string) 4)
504     (0 string)
505     (1 string) ;; Error, don't pad it.
506     (2 (concat string "=="))
507     (3 (concat string "="))))
508
509 (defun rfc2047-decode (charset encoding string)
510   "Decode STRING from the given MIME CHARSET in the given ENCODING.
511 Valid ENCODINGs are \"B\" and \"Q\".
512 If your Emacs implementation can't decode CHARSET, return nil."
513   (if (stringp charset)
514       (setq charset (intern (downcase charset))))
515   (if (or (not charset)
516           (eq 'gnus-all mail-parse-ignored-charsets)
517           (memq 'gnus-all mail-parse-ignored-charsets)
518           (memq charset mail-parse-ignored-charsets))
519       (setq charset mail-parse-charset))
520   (let ((cs (mm-charset-to-coding-system charset)))
521     (if (and (not cs) charset
522              (listp mail-parse-ignored-charsets)
523              (memq 'gnus-unknown mail-parse-ignored-charsets))
524         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
525     (when cs
526       (when (and (eq cs 'ascii)
527                  mail-parse-charset)
528         (setq cs mail-parse-charset))
529       (mm-with-unibyte-current-buffer-mule4
530         ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
531         (mm-decode-coding-string
532          (cond
533           ((equal "B" encoding)
534            (base64-decode-string
535             (rfc2047-pad-base64 string)))
536           ((equal "Q" encoding)
537            (quoted-printable-decode-string
538             (mm-replace-chars-in-string string ?_ ? )))
539           (t (error "Invalid encoding: %s" encoding)))
540          cs)))))
541
542 (provide 'rfc2047)
543
544 ;;; rfc2047.el ends here