chiark / gitweb /
Take advantage of the new dynamic string macros.
[mLib] / base64.c
1 /* -*-c-*-
2  *
3  * $Id: base64.c,v 1.3 1999/05/21 22:14:30 mdw Exp $
4  *
5  * Base64 encoding and decoding.
6  *
7  * (c) 1997 Straylight/Edgeware
8  */
9
10 /*----- Licensing notice --------------------------------------------------* 
11  *
12  * This file is part of the mLib utilities library.
13  *
14  * mLib is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU Library General Public License as
16  * published by the Free Software Foundation; either version 2 of the
17  * License, or (at your option) any later version.
18  * 
19  * mLib is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU Library General Public License for more details.
23  * 
24  * You should have received a copy of the GNU Library General Public
25  * License along with mLib; if not, write to the Free
26  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27  * MA 02111-1307, USA.
28  */
29
30 /*----- Revision history --------------------------------------------------*
31  *
32  * $Log: base64.c,v $
33  * Revision 1.3  1999/05/21 22:14:30  mdw
34  * Take advantage of the new dynamic string macros.
35  *
36  * Revision 1.2  1999/05/18 21:45:27  mdw
37  * Allow Base64 encode and decode of arbitrary rubbish.
38  *
39  * Revision 1.1  1999/05/17 20:35:00  mdw
40  * Base64 encoding and decoding support.
41  *
42  */
43
44 /*----- Header files ------------------------------------------------------*/
45
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49
50 #include "base64.h"
51 #include "dstr.h"
52
53 /*----- Important tables --------------------------------------------------*/
54
55 static const char base64_encodeMap[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
56                                          "abcdefghijklmnopqrstuvwxyz" 
57                                          "0123456789+/" };
58
59 static const signed char base64_decodeMap[] = {
60   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  /* 0x */
61   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  /* 1x */
62   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,  /* 2x */
63   52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,  /* 3x */
64   -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,  /* 4x */
65   15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,  /* 5x */
66   -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36 ,37, 38, 39, 40,  /* 6x */
67   41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1   /* 7x */
68 };  
69
70 /*----- Main code ---------------------------------------------------------*/
71
72 /* --- @base64_encode@ --- *
73  *
74  * Arguments:   @base64_ctx *ctx@ = pointer to a context block
75  *              @const void *p@ = pointer to a source buffer
76  *              @size_t sz@ = size of the source buffer
77  *              @dstr *d@ = pointer to destination string
78  *
79  * Returns:     ---
80  *
81  * Use:         Encodes a binary string in base64.  To flush out the final
82  *              few characters (if necessary), pass a null source pointer.
83  */
84
85 void base64_encode(base64_ctx *ctx,
86                    const void *p, size_t sz,
87                    dstr *d)
88 {
89   if (p) {
90     unsigned long acc = ctx->acc;
91     unsigned qsz = ctx->qsz;
92     const unsigned char *src = p;
93
94     while (sz) {
95       acc = (acc << 8) | *src++;
96       qsz++;
97       sz--;
98       if (qsz == 3) {
99         DPUTC(d, base64_encodeMap[(acc >> 18) & 0x3f]);
100         DPUTC(d, base64_encodeMap[(acc >> 12) & 0x3f]);
101         DPUTC(d, base64_encodeMap[(acc >>  6) & 0x3f]);
102         DPUTC(d, base64_encodeMap[(acc >>  0) & 0x3f]);
103         ctx->lnlen += 4;
104         if (ctx->maxline && ctx->lnlen >= ctx->maxline) {
105           dstr_puts(d, ctx->indent);
106           ctx->lnlen = 0;
107         }
108         qsz = 0;
109         acc = 0;
110       }
111     }
112
113     ctx->acc = acc;
114     ctx->qsz = qsz;
115   } else {
116     unsigned long acc = ctx->acc;
117     unsigned qsz = ctx->qsz;
118
119     switch (qsz) {
120       case 0:
121         break;
122       case 1:
123         acc <<= 16;
124         DPUTC(d, base64_encodeMap[(acc >> 18) & 0x3f]);
125         DPUTC(d, base64_encodeMap[(acc >> 12) & 0x3f]);
126         DPUTC(d, '=');
127         DPUTC(d, '=');
128         ctx->lnlen += 4;
129         break;
130       case 2:
131         acc <<= 8;
132         DPUTC(d, base64_encodeMap[(acc >> 18) & 0x3f]);
133         DPUTC(d, base64_encodeMap[(acc >> 12) & 0x3f]);
134         DPUTC(d, base64_encodeMap[(acc >>  6) & 0x3f]);
135         DPUTC(d, '=');
136         ctx->lnlen += 4;
137         break;
138     }
139     ctx->qsz = 0;
140     ctx->acc = 0;
141   }
142 }
143
144 /* --- @base64_decode@ --- *
145  *
146  * Arguments:   @base64_ctx *ctx@ = pointer to a context block
147  *              @const void *p@ = pointer to a source buffer
148  *              @size_t sz@ = size of the source buffer
149  *              @dstr *d@ = pointer to destination string
150  *
151  * Returns:     ---
152  *
153  * Use:         Decodes a binary string in base64.  To flush out the final
154  *              few characters (if necessary), pass a null source pointer.
155  */
156
157 void base64_decode(base64_ctx *ctx,
158                    const void *p, size_t sz,
159                    dstr *d)
160 {
161   if (p) {
162     unsigned long acc = ctx->acc;
163     unsigned qsz = ctx->qsz;
164     const char *src = p;
165     int ch;
166
167     while (sz) {
168
169       /* --- Get the next character and convert it --- */
170
171       ch = *src++;
172       if (ch >= 128 || ch < 0)
173         ch = -1;
174       else
175         ch = base64_decodeMap[ch];
176       sz--;
177       if (ch == -1)
178         continue;
179
180       /* --- Bung it in the accumulator --- */
181
182       acc = (acc << 6) | ch;
183       qsz++;
184
185       /* --- Maybe write out a completed triplet --- */
186
187       if (qsz == 4) {
188         DPUTC(d, (acc >> 16) & 0xff);
189         DPUTC(d, (acc >>  8) & 0xff);
190         DPUTC(d, (acc >>  0) & 0xff);
191         acc = 0;
192         qsz = 0;
193       }
194     }
195
196     ctx->acc = acc;
197     ctx->qsz = qsz;
198   } else {
199
200     /* --- Notes about the tail-end bits --- *
201      *
202      * Ending Base64 decoding is messy.  The reference I'm using to define
203      * the encoding, RFC1521 section 5.2, is a little hazy on exactly what to
204      * do at the end.  It explains that I'm meant to ignore spurious `='
205      * characters, and points out that I'm not guaranteed to see anything
206      * interesting at the end.  I'll play safe here, and ignore all `='
207      * characters, relying on my client to work out when to stop feeding me
208      * data.  I'll use the queue size to work out how many tail-end bytes
209      * I ought to write.
210      */
211
212     unsigned long acc = ctx->acc;
213     unsigned qsz = ctx->qsz;
214
215     /* --- Now fiddle with everything else --- */
216
217     acc <<= 6 * (4 - qsz);
218     qsz *= 6;
219     while (qsz > 8) {
220       DPUTC(d, (acc >> 16) & 0xff);
221       acc <<= 8;
222       qsz -= 8;
223     }
224
225     /* --- That seems to be good enough --- */
226
227     ctx->qsz = 0;
228     ctx->acc = 0;
229   }
230 }
231
232 /* --- @base64_init@ --- *
233  *
234  * Arguments:   @base64_ctx *ctx@ = pointer to context block to initialize
235  *
236  * Returns:     ---
237  *
238  * Use:         Initializes a base64 context properly.
239  */
240
241 void base64_init(base64_ctx *ctx)
242 {
243   ctx->acc = 0;
244   ctx->qsz = 0;
245   ctx->lnlen = 0;
246   ctx->indent = "\n";
247   ctx->maxline = 72;
248 }
249
250 /*----- Test driver code --------------------------------------------------*/
251
252 #ifdef TEST_RIG
253
254 int main(int argc, char *argv[])
255 {
256   unsigned char buf[BUFSIZ];
257   dstr d = DSTR_INIT;
258   base64_ctx ctx;
259   void (*proc)(base64_ctx *, const unsigned char *, size_t, dstr *);
260   size_t sz;
261
262   base64_init(&ctx);
263
264   if (argc > 1 && strcmp(argv[1], "-d") == 0)
265     proc = base64_decode;
266   else {
267     proc = base64_encode;
268     putchar('\t');
269     ctx.indent = "\n\t";
270     ctx.maxline = 64;
271   }
272
273   do {
274     sz = fread(buf, 1, sizeof(buf), stdin);
275     if (sz) {
276       proc(&ctx, buf, sz, &d);
277       dstr_write(&d, stdout);
278       dstr_destroy(&d);
279     }
280   } while (sz == sizeof(buf));
281
282   proc(&ctx, 0, 0, &d);
283   dstr_write(&d, stdout);
284
285   if (proc == base64_encode)
286     putchar('\n');
287
288   return (0);
289 }
290
291 #endif
292
293 /*----- That's all, folks -------------------------------------------------*/