10 #include <sys/socket.h>
13 #include <netinet/in.h>
26 typedef unsigned char byte; /* Byte type */
27 static byte dtable[SIZ]; /* base64 encode / decode table */
30 * decode_base64() and encode_base64() are adaptations of code by
31 * John Walker, found in full in the file "base64.c" included with the Citadel
32 * server. The difference between those functions and these is that
33 * these are intended to encode/decode small string buffers, and those are
34 * intended to encode/decode entire MIME parts.
37 void encode_base64(char *dest, char *source)
39 int i, hiteof = FALSE;
43 /* Fill dtable with character encodings. */
45 for (i = 0; i < 26; i++) {
47 dtable[26 + i] = 'a' + i;
49 for (i = 0; i < 10; i++) {
50 dtable[52 + i] = '0' + i;
56 byte igroup[3], ogroup[4];
59 igroup[0] = igroup[1] = igroup[2] = 0;
60 for (n = 0; n < 3; n++) {
69 ogroup[0] = dtable[igroup[0] >> 2];
70 ogroup[1] = dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
71 ogroup[2] = dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
72 ogroup[3] = dtable[igroup[2] & 0x3F];
74 /* Replace characters in output stream with "=" pad
75 characters if fewer than three characters were
76 read from the end of the input stream. */
84 for (i = 0; i < 4; i++) {
85 dest[dpos++] = ogroup[i];
94 * Convert base64-encoded to binary. Returns the length of the decoded data.
95 * It will stop after reading 'length' bytes.
97 int decode_base64(char *dest, char *source, size_t length)
103 for (i = 0; i < 255; i++) {
106 for (i = 'A'; i <= 'Z'; i++) {
107 dtable[i] = 0 + (i - 'A');
109 for (i = 'a'; i <= 'z'; i++) {
110 dtable[i] = 26 + (i - 'a');
112 for (i = '0'; i <= '9'; i++) {
113 dtable[i] = 52 + (i - '0');
119 /*CONSTANTCONDITION*/
121 byte a[4], b[4], o[3];
123 for (i = 0; i < 4; i++) {
124 if (spos >= length) {
135 if (dtable[c] & 0x80) {
136 /* Ignoring errors: discard invalid character. */
141 b[i] = (byte) dtable[c];
143 o[0] = (b[0] << 2) | (b[1] >> 4);
144 o[1] = (b[1] << 4) | (b[2] >> 2);
145 o[2] = (b[2] << 6) | b[3];
146 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
147 if (i>=1) dest[dpos++] = o[0];
148 if (i>=2) dest[dpos++] = o[1];
149 if (i>=3) dest[dpos++] = o[2];
160 * Pack all session info into one easy-to-digest cookie. Healthy and delicious!
162 void stuff_to_cookie(char *cookie, int session, char *user, char *pass, char *room)
166 sprintf(buf, "%d|%s|%s|%s", session, user, pass, room);
167 encode_base64(cookie, buf);
172 * Extract all that fun stuff out of the cookie.
174 void cookie_to_stuff(char *cookie, int *session, char *user, char *pass, char *room)
178 decode_base64(buf, cookie, strlen(cookie));
181 *session = extract_int(buf, 0);
183 extract(user, buf, 1);
185 extract(pass, buf, 2);
187 extract(room, buf, 3);