*** empty log message ***
[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 (defvar base64-binary-coding-system 'binary)
77
78 (defun base64-run-command-on-region (start end output-buffer command
79                                            &rest arg-list)
80   (let ((tempfile nil) status errstring default-process-coding-system 
81         (coding-system-for-write base64-binary-coding-system)
82         (coding-system-for-read base64-binary-coding-system))
83     (unwind-protect
84         (progn
85           (setq tempfile (make-temp-name "base64"))
86           (setq status
87                 (apply 'call-process-region
88                        start end command nil
89                        (list output-buffer tempfile)
90                        nil arg-list))
91           (cond ((equal status 0) t)
92                 ((zerop (save-excursion
93                           (set-buffer (find-file-noselect tempfile))
94                           (buffer-size)))
95                  t)
96                 (t (save-excursion
97                      (set-buffer (find-file-noselect tempfile))
98                      (setq errstring (buffer-string))
99                      (kill-buffer nil)
100                      (cons status errstring)))))
101       (ignore-errors
102         (delete-file tempfile)))))
103
104 (if (string-match "XEmacs" emacs-version)
105     (defalias 'base64-insert-char 'insert-char)
106   (defun base64-insert-char (char &optional count ignored buffer)
107     (if (or (null buffer) (eq buffer (current-buffer)))
108         (insert-char char count)
109       (with-current-buffer buffer
110         (insert-char char count))))
111   (setq base64-binary-coding-system 'no-conversion))
112
113 (defun base64-decode-region (start end)
114   (interactive "r")
115   ;;(message "Decoding base64...")
116   (let ((work-buffer nil)
117         (done nil)
118         (counter 0)
119         (bits 0)
120         (lim 0) inputpos
121         (non-data-chars (concat "^=" base64-alphabet)))
122     (unwind-protect
123         (save-excursion
124           (setq work-buffer (generate-new-buffer " *base64-work*"))
125           (buffer-disable-undo work-buffer)
126           (if base64-decoder-program
127               (let* ((binary-process-output t) ; any text already has CRLFs
128                      (status (apply 'base64-run-command-on-region
129                                    start end work-buffer
130                                    base64-decoder-program
131                                    base64-decoder-switches)))
132                 (if (not (eq status t))
133                     (error "%s" (cdr status))))
134             (goto-char start)
135             (skip-chars-forward non-data-chars end)
136             (while (not done)
137               (setq inputpos (point))
138               (cond
139                ((> (skip-chars-forward base64-alphabet end) 0)
140                 (setq lim (point))
141                 (while (< inputpos lim)
142                   (setq bits (+ bits
143                                 (aref base64-alphabet-decoding-vector
144                                       (char-int (char-after inputpos)))))
145                   (setq counter (1+ counter)
146                         inputpos (1+ inputpos))
147                   (cond ((= counter 4)
148                          (base64-insert-char (lsh bits -16) 1 nil work-buffer)
149                          (base64-insert-char (logand (lsh bits -8) 255) 1 nil
150                                          work-buffer)
151                          (base64-insert-char (logand bits 255) 1 nil
152                                              work-buffer)
153                          (setq bits 0 counter 0))
154                         (t (setq bits (lsh bits 6)))))))
155               (cond
156                ((= (point) end)
157                 (if (not (zerop counter))
158                     (error "at least %d bits missing at end of base64 encoding"
159                            (* (- 4 counter) 6)))
160                 (setq done t))
161                ((eq (char-after (point)) ?=)
162                 (setq done t)
163                 (cond ((= counter 1)
164                        (error "at least 2 bits missing at end of base64 encoding"))
165                       ((= counter 2)
166                        (base64-insert-char (lsh bits -10) 1 nil work-buffer))
167                       ((= counter 3)
168                        (base64-insert-char (lsh bits -16) 1 nil work-buffer)
169                        (base64-insert-char (logand (lsh bits -8) 255)
170                                            1 nil work-buffer))
171                       ((= counter 0) t)))
172                (t (skip-chars-forward non-data-chars end)))))
173           (or (markerp end) (setq end (set-marker (make-marker) end)))
174           (goto-char start)
175           (insert-buffer-substring work-buffer)
176           (delete-region (point) end))
177       (and work-buffer (kill-buffer work-buffer))))
178   ;;(message "Decoding base64... done")
179   )
180
181 (defun base64-encode-region (start end &optional no-line-break)
182   (interactive "r")
183   (message "Encoding base64...")
184   (let ((work-buffer nil)
185         (counter 0)
186         (cols 0)
187         (bits 0)
188         (alphabet base64-alphabet)
189         inputpos)
190     (unwind-protect
191         (save-excursion
192           (setq work-buffer (generate-new-buffer " *base64-work*"))
193           (buffer-disable-undo work-buffer)
194           (if base64-encoder-program
195               (let ((status (apply 'base64-run-command-on-region
196                                    start end work-buffer
197                                    base64-encoder-program
198                                    base64-encoder-switches)))
199                 (if (not (eq status t))
200                     (error "%s" (cdr status))))
201             (setq inputpos start)
202             (while (< inputpos end)
203               (setq bits (+ bits (char-int (char-after inputpos))))
204               (setq counter (1+ counter))
205               (cond ((= counter 3)
206                      (base64-insert-char (aref alphabet (lsh bits -18)) 1 nil
207                                          work-buffer)
208                      (base64-insert-char
209                       (aref alphabet (logand (lsh bits -12) 63))
210                       1 nil work-buffer)
211                      (base64-insert-char
212                       (aref alphabet (logand (lsh bits -6) 63))
213                       1 nil work-buffer)
214                      (base64-insert-char
215                       (aref alphabet (logand bits 63))
216                       1 nil work-buffer)
217                      (setq cols (+ cols 4))
218                      (cond ((and (= cols 72)
219                                  (not no-line-break))
220                             (base64-insert-char ?\n 1 nil work-buffer)
221                             (setq cols 0)))
222                      (setq bits 0 counter 0))
223                     (t (setq bits (lsh bits 8))))
224               (setq inputpos (1+ inputpos)))
225             ;; write out any remaining bits with appropriate padding
226             (if (= counter 0)
227                 nil
228               (setq bits (lsh bits (- 16 (* 8 counter))))
229               (base64-insert-char (aref alphabet (lsh bits -18)) 1 nil
230                                   work-buffer)
231               (base64-insert-char (aref alphabet (logand (lsh bits -12) 63))
232                                   1 nil work-buffer)
233               (if (= counter 1)
234                   (base64-insert-char ?= 2 nil work-buffer)
235                 (base64-insert-char (aref alphabet (logand (lsh bits -6) 63))
236                                     1 nil work-buffer)
237                 (base64-insert-char ?= 1 nil work-buffer)))
238             (if (and (> cols 0)
239                      (not no-line-break))
240                 (base64-insert-char ?\n 1 nil work-buffer)))
241           (or (markerp end) (setq end (set-marker (make-marker) end)))
242           (goto-char start)
243           (insert-buffer-substring work-buffer)
244           (delete-region (point) end))
245       (and work-buffer (kill-buffer work-buffer))))
246   (message "Encoding base64... done"))
247
248 (defun base64-encode (string)
249   (save-excursion
250     (set-buffer (get-buffer-create " *base64-encode*"))
251     (erase-buffer)
252     (insert string)
253     (base64-encode-region (point-min) (point-max))
254     (skip-chars-backward " \t\r\n")
255     (delete-region (point-max) (point))
256     (prog1
257         (buffer-string)
258       (kill-buffer (current-buffer)))))
259
260 (defun base64-decode (string)
261   (save-excursion
262     (set-buffer (get-buffer-create " *base64-decode*"))
263     (erase-buffer)
264     (insert string)
265     (base64-decode-region (point-min) (point-max))
266     (goto-char (point-max))
267     (skip-chars-backward " \t\r\n")
268     (delete-region (point-max) (point))
269     (prog1
270         (buffer-string)
271       (kill-buffer (current-buffer)))))
272
273 (fset 'base64-decode-string 'base64-decode)
274
275 (provide 'base64)