comparison f-demime/base64.c @ 0:7e0d08176f32

f-demime starting code
author Mychaela Falconia <falcon@freecalypso.org>
date Sat, 06 May 2023 06:14:03 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:7e0d08176f32
1 /*
2 * This module implements base64 decoding.
3 */
4
5 #include <ctype.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <strings.h>
10 #include "defs.h"
11
12 extern void (*dec_outf)();
13
14 static unsigned b64_accum, b64_eq_flag;
15 static int b64_state, last_partial;
16 int b64_err_flag, b64_nonempty;
17
18 void
19 base64_dec_init()
20 {
21 b64_accum = 0;
22 b64_eq_flag = 0;
23 b64_state = 0;
24 b64_err_flag = 0;
25 b64_nonempty = 0;
26 last_partial = 0;
27 }
28
29 static void
30 process_unit()
31 {
32 if (last_partial)
33 b64_err_flag = 1;
34 switch (b64_eq_flag) {
35 case 0:
36 dec_outf(b64_accum >> 16);
37 dec_outf((b64_accum >> 8) & 0xFF);
38 dec_outf(b64_accum & 0xFF);
39 last_partial = 0;
40 break;
41 case 1:
42 dec_outf(b64_accum >> 16);
43 dec_outf((b64_accum >> 8) & 0xFF);
44 last_partial = 1;
45 break;
46 case 3:
47 dec_outf(b64_accum >> 16);
48 last_partial = 1;
49 break;
50 default:
51 b64_err_flag = 1;
52 }
53 b64_accum = 0;
54 b64_eq_flag = 0;
55 b64_state = 0;
56 }
57
58 static void
59 base64_input_char(ch)
60 {
61 int code;
62
63 b64_nonempty = 1;
64 if (ch >= 'A' && ch <= 'Z')
65 code = ch - 'A';
66 else if (ch >= 'a' && ch <= 'z')
67 code = ch - 'a' + 26;
68 else if (ch >= '0' && ch <= '9')
69 code = ch - '0' + 52;
70 else switch (ch) {
71 case '+':
72 code = 62;
73 break;
74 case '/':
75 code = 63;
76 break;
77 case '=':
78 code = 64;
79 break;
80 default:
81 b64_err_flag = 1;
82 return;
83 }
84 b64_accum <<= 6;
85 b64_accum |= (code & 63);
86 b64_eq_flag <<= 1;
87 b64_eq_flag |= (code >> 6);
88 b64_state++;
89 if (b64_state >= 4)
90 process_unit();
91 }
92
93 void
94 base64_input_line(line)
95 char *line;
96 {
97 char *cp;
98 int c;
99
100 for (cp = line; *cp; ) {
101 c = *cp++;
102 if (!isspace(c))
103 base64_input_char(c);
104 }
105 }
106
107 void
108 base64_dec_finish()
109 {
110 if (b64_state)
111 b64_err_flag = 1;
112 }