2000-12-20 09: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 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           (insert "\n ")
327           (setq bol (1- (point)))
328           ;; Don't break before the first non-LWSP characters.
329           (skip-chars-forward " \t")
330           (forward-char 1))
331         (cond
332          ((eq (char-after) ?\n)
333           (forward-char 1)
334           (setq bol (point)
335                 break nil
336                 qword-break nil)
337           (skip-chars-forward " \t")
338           (unless (or (eobp) (eq (char-after) ?\n))
339             (forward-char 1)))
340          ((eq (char-after) ?\r)
341           (forward-char 1))
342          ((memq (char-after) '(?  ?\t))
343           (skip-chars-forward " \t")
344           (setq break (1- (point))))
345          ((not break)
346           (if (not (looking-at "=\\?[^=]"))
347               (if (eq (char-after) ?=)
348                   (forward-char 1)
349                 (skip-chars-forward "^ \t\n\r="))
350             (setq qword-break (point))
351             (skip-chars-forward "^ \t\n\r")))
352          (t
353           (skip-chars-forward "^ \t\n\r"))))
354       (when (and (or break qword-break) (> (- (point) bol) 76))
355         (goto-char (or break qword-break))
356         (setq break nil
357               qword-break nil)
358         (insert "\n ")
359         (setq bol (1- (point)))
360         ;; Don't break before the first non-LWSP characters.
361         (skip-chars-forward " \t")
362         (forward-char 1)))))
363
364 (defun rfc2047-unfold-region (b e)
365   "Unfold lines in the region."
366   (save-restriction
367     (narrow-to-region b e)
368     (goto-char (point-min))
369     (let ((bol (save-restriction
370                  (widen)
371                  (gnus-point-at-bol)))
372           (eol (gnus-point-at-eol))
373           leading)
374       (forward-line 1)
375       (while (not (eobp))
376         (looking-at "[ \t]*")
377         (setq leading (- (match-end 0) (match-beginning 0)))
378         (if (< (- (gnus-point-at-eol) bol leading) 76)
379             (progn
380               (goto-char eol)
381               (delete-region eol (progn
382                                    (skip-chars-forward "[ \t\n\r]+")
383                                    (1- (point)))))
384           (setq bol (gnus-point-at-bol)))
385         (setq eol (gnus-point-at-eol))
386         (forward-line 1)))))
387
388 (defun rfc2047-b-encode-region (b e)
389   "Base64-encode the header contained in region B to E."
390   (save-restriction
391     (narrow-to-region (goto-char b) e)
392     (while (not (eobp))
393       (base64-encode-region (point) (progn (end-of-line) (point)) t)
394       (if (and (bolp) (eolp))
395           (delete-backward-char 1))
396       (forward-line))))
397
398 (defun rfc2047-q-encode-region (b e)
399   "Quoted-printable-encode the header in region B to E."
400   (save-excursion
401     (save-restriction
402       (narrow-to-region (goto-char b) e)
403       (let ((alist rfc2047-q-encoding-alist)
404             (bol (save-restriction
405                    (widen)
406                    (gnus-point-at-bol))))
407         (while alist
408           (when (looking-at (caar alist))
409             (quoted-printable-encode-region b e nil (cdar alist))
410             (subst-char-in-region (point-min) (point-max) ?  ?_)
411             (setq alist nil))
412           (pop alist))
413         ;; The size of QP encapsulation is about 20, so set limit to
414         ;; 56=76-20.
415         (unless (< (- (point-max) (point-min)) 56)
416           ;; Don't break if it could fit in one line.
417           ;; Let rfc2047-encode-region break it later.
418           (goto-char (1+ (point-min)))
419           (while (and (not (bobp)) (not (eobp)))
420             (goto-char (min (point-max) (+ 56 bol)))
421             (search-backward "=" (- (point) 2) t)
422             (unless (or (bobp) (eobp))
423               (insert "\n")
424               (setq bol (point)))))))))
425
426 ;;;
427 ;;; Functions for decoding RFC2047 messages
428 ;;;
429
430 (defvar rfc2047-encoded-word-regexp
431   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]*\\)\\?=")
432
433 (defun rfc2047-decode-region (start end)
434   "Decode MIME-encoded words in region between START and END."
435   (interactive "r")
436   (let ((case-fold-search t)
437         b e)
438     (save-excursion
439       (save-restriction
440         (narrow-to-region start end)
441         (goto-char (point-min))
442         ;; Remove whitespace between encoded words.
443         (while (re-search-forward
444                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
445                         "\\(\n?[ \t]\\)+"
446                         "\\(" rfc2047-encoded-word-regexp "\\)")
447                 nil t)
448           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
449         ;; Decode the encoded words.
450         (setq b (goto-char (point-min)))
451         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
452           (setq e (match-beginning 0))
453           (insert (rfc2047-parse-and-decode
454                    (prog1
455                        (match-string 0)
456                      (delete-region (match-beginning 0) (match-end 0)))))
457           (when (and (mm-multibyte-p)
458                      mail-parse-charset
459                      (not (eq mail-parse-charset 'gnus-decoded)))
460             (mm-decode-coding-region b e mail-parse-charset))
461           (setq b (point)))
462         (when (and (mm-multibyte-p)
463                    mail-parse-charset
464                    (not (eq mail-parse-charset 'us-ascii))
465                    (not (eq mail-parse-charset 'gnus-decoded)))
466           (mm-decode-coding-region b (point-max) mail-parse-charset))
467         (rfc2047-unfold-region (point-min) (point-max))))))
468
469 (defun rfc2047-decode-string (string)
470   "Decode the quoted-printable-encoded STRING and return the results."
471   (let ((m (mm-multibyte-p)))
472     (with-temp-buffer
473       (when m
474         (mm-enable-multibyte))
475       (insert string)
476       (inline
477         (rfc2047-decode-region (point-min) (point-max)))
478       (buffer-string))))
479
480 (defun rfc2047-parse-and-decode (word)
481   "Decode WORD and return it if it is an encoded word.
482 Return WORD if not."
483   (if (not (string-match rfc2047-encoded-word-regexp word))
484       word
485     (or
486      (condition-case nil
487          (rfc2047-decode
488           (match-string 1 word)
489           (upcase (match-string 2 word))
490           (match-string 3 word))
491        (error word))
492      word)))
493
494 (defun rfc2047-pad-base64 (string)
495   "Pad STRING to quartets."
496   ;; Be more liberal to accept buggy base64 strings. If
497   ;; base64-decode-string accepts buggy strings, this function could
498   ;; be aliased to identity.
499   (case (mod (length string) 4)
500     (0 string)
501     (1 string) ;; Error, don't pad it.
502     (2 (concat string "=="))
503     (3 (concat string "="))))
504
505 (defun rfc2047-decode (charset encoding string)
506   "Decode STRING from the given MIME CHARSET in the given ENCODING.
507 Valid ENCODINGs are \"B\" and \"Q\".
508 If your Emacs implementation can't decode CHARSET, return nil."
509   (if (stringp charset)
510       (setq charset (intern (downcase charset))))
511   (if (or (not charset)
512           (eq 'gnus-all mail-parse-ignored-charsets)
513           (memq 'gnus-all mail-parse-ignored-charsets)
514           (memq charset mail-parse-ignored-charsets))
515       (setq charset mail-parse-charset))
516   (let ((cs (mm-charset-to-coding-system charset)))
517     (if (and (not cs) charset
518              (listp mail-parse-ignored-charsets)
519              (memq 'gnus-unknown mail-parse-ignored-charsets))
520         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
521     (when cs
522       (when (and (eq cs 'ascii)
523                  mail-parse-charset)
524         (setq cs mail-parse-charset))
525       (mm-with-unibyte-current-buffer-mule4
526         ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
527         (mm-decode-coding-string
528          (cond
529           ((equal "B" encoding)
530            (base64-decode-string 
531             (rfc2047-pad-base64 string)))
532           ((equal "Q" encoding)
533            (quoted-printable-decode-string
534             (mm-replace-chars-in-string string ?_ ? )))
535           (t (error "Invalid encoding: %s" encoding)))
536          cs)))))
537
538 (provide 'rfc2047)
539
540 ;;; rfc2047.el ends here