644dbfc32a3b84259d9c71f7818a689b072346ac
[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 <ctype.h>
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <stdio.h>
13 #include <fcntl.h>
14 #include <signal.h>
15 #include <sys/types.h>
16 #include <sys/wait.h>
17 #include <sys/socket.h>
18 #include <sys/time.h>
19 #include <limits.h>
20 #include <netinet/in.h>
21 #include <netdb.h>
22 #include <string.h>
23 #include <pwd.h>
24 #include <errno.h>
25 #include <stdarg.h>
26 #include <pthread.h>
27 #include <signal.h>
28 #include "webcit.h"
29
30 #define TRUE  1
31 #define FALSE 0
32
33 typedef unsigned char byte;           /* Byte type */
34
35 /*
36  * Pack all session info into one easy-to-digest cookie. Healthy and delicious!
37  */
38 void stuff_to_cookie(char *cookie, int session,
39                 char *user, char *pass, char *room)
40 {
41         char buf[SIZ];
42         int i;
43
44         sprintf(buf, "%d|%s|%s|%s|", session, user, pass, room);
45         strcpy(cookie, "");
46         for (i=0; i<strlen(buf); ++i) {
47                 sprintf(&cookie[i*2], "%02X", buf[i]);
48         }
49 }
50
51 int xtoi(char *in, size_t len)
52 {
53     int val = 0;
54     while (isxdigit((byte) *in) && (len-- > 0)) {
55         char c = *in++;
56         val <<= 4;
57         val += isdigit((unsigned char)c)
58             ? (c - '0')
59             : (tolower((unsigned char)c) - 'a' + 10);
60     }
61     return val;
62 }
63
64 /*
65  * Extract all that fun stuff out of the cookie.
66  */
67 void cookie_to_stuff(char *cookie, int *session, char *user, char *pass, char *room)
68 {
69         char buf[SIZ];
70         int i, len;
71
72         strcpy(buf, "");
73         len = strlen(cookie) * 2 ;
74         for (i=0; i<len; ++i) {
75                 buf[i] = xtoi(&cookie[i*2], 2);
76                 buf[i+1] = 0;
77         }
78
79         if (session != NULL)
80                 *session = extract_int(buf, 0);
81         if (user != NULL)
82                 extract(user, buf, 1);
83         if (pass != NULL)
84                 extract(pass, buf, 2);
85         if (room != NULL)
86                 extract(room, buf, 3);
87 }