* migrate more of the upload handling to strbuf
[citadel.git] / webcit / cookie_conversion.c
1 /*
2  * $Id$
3  */
4
5 #include "webcit.h"
6
7 typedef unsigned char byte;           /* Byte type used by cookie_to_stuff() */
8
9 /*
10  * Pack all session info into one easy-to-digest cookie. Healthy and delicious!
11  */
12 void stuff_to_cookie(char *cookie, size_t clen, int session,
13                 StrBuf *user, StrBuf *pass, StrBuf *room, const char *language)
14 {
15         char buf[SIZ];
16         int i;
17         int len;
18
19         len = snprintf(buf, SIZ, "%d|%s|%s|%s|%s|", 
20                 session, 
21                 ChrPtr(user), 
22                 ChrPtr(pass), 
23                 ChrPtr(room),
24                 language
25         );
26
27         strcpy(cookie, "");
28         for (i=0; (i < len) && (i * 2 < clen); ++i) {
29                 snprintf(&cookie[i*2], clen - i * 2, "%02X", buf[i]);
30         }
31 }
32
33 /*
34  * Convert unpacked hex string to an integer
35  */
36 int xtoi(const char *in, size_t len)
37 {
38         int val = 0;
39         char c = 0;
40         while (!IsEmptyStr(in) && isxdigit((byte) *in) && (len-- > 0))
41         {
42                 c = *in++;
43                 val <<= 4;
44                 if (!isdigit((unsigned char)c)) {
45                         c = tolower((unsigned char) c);
46                         if ((c < 'a') || (c > 'f'))
47                                 return 0;
48                         val += c  - 'a' + 10 ;
49                 }
50                 else
51                         val += c - '0';
52         }
53         return val;
54 }
55
56 /*
57  * Extract all that fun stuff out of the cookie.
58  */
59 void cookie_to_stuff(StrBuf *cookie,
60                         int *session,
61                         StrBuf *user,
62                         StrBuf *pass,
63                         StrBuf *room,
64                         StrBuf *language)
65 {
66         if (session != NULL) {
67                 *session = StrBufExtract_int(cookie, 0, '|');
68         }
69         if (user != NULL) {
70                 StrBufExtract_token(user, cookie, 1, '|');
71         }
72         if (pass != NULL) {
73                 StrBufExtract_token(pass, cookie, 2, '|');
74         }
75         if (room != NULL) {
76                 StrBufExtract_token(room, cookie, 3, '|');
77         }
78         if (language != NULL) {
79                 StrBufExtract_token(language, cookie, 4, '|');
80         }
81 }