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