6cf78e07824e2467aa559e5225a643257d7e2d47
[gnus] / lisp / base64.el
1 ;;; base64.el,v --- Base64 encoding functions
2 ;; Author: Kyle E. Jones
3 ;; Created: 1997/03/12 14:37:09
4 ;; Version: 1.6
5 ;; Keywords: extensions
6
7 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
8 ;;; Copyright (C) 1997 Kyle E. Jones
9 ;;;
10 ;;; This file is not part of GNU Emacs, but the same permissions apply.
11 ;;;
12 ;;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 2, or (at your option)
15 ;;; any later version.
16 ;;;
17 ;;; GNU Emacs is distributed in the hope that it will be useful,
18 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;;; GNU General Public License for more details.
21 ;;;
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;;; Boston, MA 02111-1307, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27
28 ;; For non-MULE
29 (if (not (fboundp 'char-int))
30     (fset 'char-int 'identity))
31
32 (defvar base64-alphabet
33   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
34
35 (defvar base64-decoder-program nil
36   "*Non-nil value should be a string that names a MIME base64 decoder.
37 The program should expect to read base64 data on its standard
38 input and write the converted data to its standard output.")
39
40 (defvar base64-decoder-switches nil
41   "*List of command line flags passed to the command named by
42 base64-decoder-program.")
43
44 (defvar base64-encoder-program nil
45   "*Non-nil value should be a string that names a MIME base64 encoder.
46 The program should expect arbitrary data on its standard
47 input and write base64 data to its standard output.")
48
49 (defvar base64-encoder-switches nil
50   "*List of command line flags passed to the command named by
51 base64-encoder-program.")
52
53 (defconst base64-alphabet-decoding-alist
54   '(
55     ( ?A . 00) ( ?B . 01) ( ?C . 02) ( ?D . 03) ( ?E . 04) ( ?F . 05)
56     ( ?G . 06) ( ?H . 07) ( ?I . 08) ( ?J . 09) ( ?K . 10) ( ?L . 11)
57     ( ?M . 12) ( ?N . 13) ( ?O . 14) ( ?P . 15) ( ?Q . 16) ( ?R . 17)
58     ( ?S . 18) ( ?T . 19) ( ?U . 20) ( ?V . 21) ( ?W . 22) ( ?X . 23)
59     ( ?Y . 24) ( ?Z . 25) ( ?a . 26) ( ?b . 27) ( ?c . 28) ( ?d . 29)
60     ( ?e . 30) ( ?f . 31) ( ?g . 32) ( ?h . 33) ( ?i . 34) ( ?j . 35)
61     ( ?k . 36) ( ?l . 37) ( ?m . 38) ( ?n . 39) ( ?o . 40) ( ?p . 41)
62     ( ?q . 42) ( ?r . 43) ( ?s . 44) ( ?t . 45) ( ?u . 46) ( ?v . 47)
63     ( ?w . 48) ( ?x . 49) ( ?y . 50) ( ?z . 51) ( ?0 . 52) ( ?1 . 53)
64     ( ?2 . 54) ( ?3 . 55) ( ?4 . 56) ( ?5 . 57) ( ?6 . 58) ( ?7 . 59)
65     ( ?8 . 60) ( ?9 . 61) ( ?+ . 62) ( ?/ . 63)
66    ))
67
68 (defvar base64-alphabet-decoding-vector
69   (let ((v (make-vector 123 nil))
70         (p base64-alphabet-decoding-alist))
71     (while p
72       (aset v (car (car p)) (cdr (car p)))
73       (setq p (cdr p)))
74     v))
75
76 (defun base64-run-command-on-region (start end output-buffer command
77                                            &rest arg-list)
78   (let ((tempfile nil) status errstring default-process-coding-system)
79     (unwind-protect
80         (progn
81           (setq tempfile (make-temp-name "base64"))
82           (setq status
83                 (apply 'call-process-region
84                        start end command nil
85                        (list output-buffer tempfile)
86                        nil arg-list))
87           (cond ((equal status 0) t)
88                 ((zerop (save-excursion
89                           (set-buffer (find-file-noselect tempfile))
90                           (buffer-size)))
91                  t)
92                 (t (save-excursion
93                      (set-buffer (find-file-noselect tempfile))
94                      (setq errstring (buffer-string))
95                      (kill-buffer nil)
96                      (cons status errstring)))))
97       (condition-case ()
98           (delete-file tempfile)
99         (error nil)))))
100
101 (if (string-match "XEmacs" emacs-version)
102     (defalias 'base64-insert-char 'insert-char)
103   (defun base64-insert-char (char &optional count ignored buffer)
104     (if (or (null buffer) (eq buffer (current-buffer)))
105         (insert-char char count)
106       (with-current-buffer buffer
107         (insert-char char count)))))
108
109 (defun base64-decode-region (start end)
110   (interactive "r")
111   ;;(message "Decoding base64...")
112   (let ((work-buffer nil)
113         (done nil)
114         (counter 0)
115         (bits 0)
116         (lim 0) inputpos
117         (non-data-chars (concat "^=" base64-alphabet)))
118     (unwind-protect
119         (save-excursion
120           (setq work-buffer (generate-new-buffer " *base64-work*"))
121           (buffer-disable-undo work-buffer)
122           (if base64-decoder-program
123               (let* ((binary-process-output t) ; any text already has CRLFs
124                      (status (apply 'base64-run-command-on-region
125                                    start end work-buffer
126                                    base64-decoder-program
127                                    base64-decoder-switches)))
128                 (if (not (eq status t))
129                     (error "%s" (cdr status))))
130             (goto-char start)
131             (skip-chars-forward non-data-chars end)
132             (while (not done)
133               (setq inputpos (point))
134               (cond
135                ((> (skip-chars-forward base64-alphabet end) 0)
136                 (setq lim (point))
137                 (while (< inputpos lim)
138                   (setq bits (+ bits
139                                 (aref base64-alphabet-decoding-vector
140                                       (char-int (char-after inputpos)))))
141                   (setq counter (1+ counter)
142                         inputpos (1+ inputpos))
143                   (cond ((= counter 4)
144                          (base64-insert-char (lsh bits -16) 1 nil work-buffer)
145                          (base64-insert-char (logand (lsh bits -8) 255) 1 nil
146                                          work-buffer)
147                          (base64-insert-char (logand bits 255) 1 nil
148                                              work-buffer)
149                          (setq bits 0 counter 0))
150                         (t (setq bits (lsh bits 6)))))))
151               (cond
152                ((= (point) end)
153                 (if (not (zerop counter))
154                     (error "at least %d bits missing at end of base64 encoding"
155                            (* (- 4 counter) 6)))
156                 (setq done t))
157                ((eq (char-after (point)) ?=)
158                 (setq done t)
159                 (cond ((= counter 1)
160                        (error "at least 2 bits missing at end of base64 encoding"))
161                       ((= counter 2)
162                        (base64-insert-char (lsh bits -10) 1 nil work-buffer))
163                       ((= counter 3)
164                        (base64-insert-char (lsh bits -16) 1 nil work-buffer)
165                        (base64-insert-char (logand (lsh bits -8) 255)
166                                            1 nil work-buffer))
167                       ((= counter 0) t)))
168                (t (skip-chars-forward non-data-chars end)))))
169           (or (markerp end) (setq end (set-marker (make-marker) end)))
170           (goto-char start)
171           (insert-buffer-substring work-buffer)
172           (delete-region (point) end))
173       (and work-buffer (kill-buffer work-buffer))))
174   ;;(message "Decoding base64... done")
175   )
176
177 (defun base64-encode-region (start end &optional no-line-break)
178   (interactive "r")
179   (message "Encoding base64...")
180   (let ((work-buffer nil)
181         (counter 0)
182         (cols 0)
183         (bits 0)
184         (alphabet base64-alphabet)
185         inputpos)
186     (unwind-protect
187         (save-excursion
188           (setq work-buffer (generate-new-buffer " *base64-work*"))
189           (buffer-disable-undo work-buffer)
190           (if base64-encoder-program
191               (let ((status (apply 'base64-run-command-on-region
192                                    start end work-buffer
193                                    base64-encoder-program
194                                    base64-encoder-switches)))
195                 (if (not (eq status t))
196                     (error "%s" (cdr status))))
197             (setq inputpos start)
198             (while (< inputpos end)
199               (setq bits (+ bits (char-int (char-after inputpos))))
200               (setq counter (1+ counter))
201               (cond ((= counter 3)
202                      (base64-insert-char (aref alphabet (lsh bits -18)) 1 nil
203                                          work-buffer)
204                      (base64-insert-char
205                       (aref alphabet (logand (lsh bits -12) 63))
206                       1 nil work-buffer)
207                      (base64-insert-char
208                       (aref alphabet (logand (lsh bits -6) 63))
209                       1 nil work-buffer)
210                      (base64-insert-char
211                       (aref alphabet (logand bits 63))
212                       1 nil work-buffer)
213                      (setq cols (+ cols 4))
214                      (cond ((and (= cols 72)
215                                  (not no-line-break))
216                             (base64-insert-char ?\n 1 nil work-buffer)
217                             (setq cols 0)))
218                      (setq bits 0 counter 0))
219                     (t (setq bits (lsh bits 8))))
220               (setq inputpos (1+ inputpos)))
221             ;; write out any remaining bits with appropriate padding
222             (if (= counter 0)
223                 nil
224               (setq bits (lsh bits (- 16 (* 8 counter))))
225               (base64-insert-char (aref alphabet (lsh bits -18)) 1 nil
226                                   work-buffer)
227               (base64-insert-char (aref alphabet (logand (lsh bits -12) 63))
228                                   1 nil work-buffer)
229               (if (= counter 1)
230                   (base64-insert-char ?= 2 nil work-buffer)
231                 (base64-insert-char (aref alphabet (logand (lsh bits -6) 63))
232                                     1 nil work-buffer)
233                 (base64-insert-char ?= 1 nil work-buffer)))
234             (if (and (> cols 0)
235                      (not no-line-break))
236                 (base64-insert-char ?\n 1 nil work-buffer)))
237           (or (markerp end) (setq end (set-marker (make-marker) end)))
238           (goto-char start)
239           (insert-buffer-substring work-buffer)
240           (delete-region (point) end))
241       (and work-buffer (kill-buffer work-buffer))))
242   (message "Encoding base64... done"))
243
244 (defun base64-encode (string)
245   (save-excursion
246     (set-buffer (get-buffer-create " *base64-encode*"))
247     (erase-buffer)
248     (insert string)
249     (base64-encode-region (point-min) (point-max))
250     (skip-chars-backward " \t\r\n")
251     (delete-region (point-max) (point))
252     (prog1
253         (buffer-string)
254       (kill-buffer (current-buffer)))))
255
256 (defun base64-decode (string)
257   (save-excursion
258     (set-buffer (get-buffer-create " *base64-decode*"))
259     (erase-buffer)
260     (insert string)
261     (base64-decode-region (point-min) (point-max))
262     (goto-char (point-max))
263     (skip-chars-backward " \t\r\n")
264     (delete-region (point-max) (point))
265     (prog1
266         (buffer-string)
267       (kill-buffer (current-buffer)))))
268
269 (fset 'base64-decode-string 'base64-decode)
270
271 (provide 'base64)