* All OS-level includes are now included from webcit.h instead of from
[citadel.git] / webcit / cookie_conversion.c
1 /*
2  * $Id$
3  *
4  * Utility functions which convert the HTTP cookie format we use to and
5  * from user/password/room strings.
6  *
7  */
8
9 #include "webcit.h"
10
11 #define TRUE  1
12 #define FALSE 0
13
14 typedef unsigned char byte;           /* Byte type */
15
16 /*
17  * Pack all session info into one easy-to-digest cookie. Healthy and delicious!
18  */
19 void stuff_to_cookie(char *cookie, int session,
20                 char *user, char *pass, char *room)
21 {
22         char buf[SIZ];
23         int i;
24
25         sprintf(buf, "%d|%s|%s|%s|", session, user, pass, room);
26         strcpy(cookie, "");
27         for (i=0; i<strlen(buf); ++i) {
28                 sprintf(&cookie[i*2], "%02X", buf[i]);
29         }
30 }
31
32 int xtoi(char *in, size_t len)
33 {
34     int val = 0;
35     while (isxdigit((byte) *in) && (len-- > 0)) {
36         char c = *in++;
37         val <<= 4;
38         val += isdigit((unsigned char)c)
39             ? (c - '0')
40             : (tolower((unsigned char)c) - 'a' + 10);
41     }
42     return val;
43 }
44
45 /*
46  * Extract all that fun stuff out of the cookie.
47  */
48 void cookie_to_stuff(char *cookie, int *session,
49                 char *user, size_t user_len,
50                 char *pass, size_t pass_len,
51                 char *room, size_t room_len)
52 {
53         char buf[SIZ];
54         int i, len;
55
56         strcpy(buf, "");
57         len = strlen(cookie) * 2 ;
58         for (i=0; i<len; ++i) {
59                 buf[i] = xtoi(&cookie[i*2], 2);
60                 buf[i+1] = 0;
61         }
62
63         if (session != NULL)
64                 *session = extract_int(buf, 0);
65         if (user != NULL)
66                 extract_token(user, buf, 1, '|', user_len);
67         if (pass != NULL)
68                 extract_token(pass, buf, 2, '|', pass_len);
69         if (room != NULL)
70                 extract_token(room, buf, 3, '|', room_len);
71 }