Build courier-authlib 0.59.3-1hcoop1.
[hcoop/debian/courier-authlib.git] / authsaslplain.c
1 /* $Id: authsaslplain.c,v 1.3 2005/07/02 15:40:28 mrsam Exp $ */
2
3 /*
4 ** Copyright 2000-2005 Double Precision, Inc. See COPYING for
5 ** distribution information.
6 */
7
8 #include "courier_auth_config.h"
9 #include "auth.h"
10 #include "random128/random128.h"
11 #include "courierauthsasl.h"
12 #include <stdlib.h>
13 #include <string.h>
14 #if HAVE_UNISTD_H
15 #include <unistd.h>
16 #endif
17 #include <ctype.h>
18 #include <stdio.h>
19 #include <errno.h>
20
21 extern char *strdupdefdomain(const char *userid, const char *s1,
22 const char *s2, const char *s3);
23
24 int authsasl_plain(const char *method, const char *initresponse,
25 char *(*getresp)(const char *, void *),
26 void *callback_arg,
27 char **authtype,
28 char **authdata)
29 {
30 char *uid;
31 char *pw;
32 char *p;
33 int n;
34 int i;
35
36 if (initresponse)
37 {
38 p=malloc(strlen(initresponse)+1);
39 if (!p)
40 {
41 perror("malloc");
42 return (AUTHSASL_ERROR);
43 }
44 strcpy(p, initresponse);
45 }
46 else
47 {
48 p=authsasl_tobase64("", -1);
49 if (!p)
50 {
51 perror("malloc");
52 return (AUTHSASL_ERROR);
53 }
54 uid=getresp(p, callback_arg);
55 free(p);
56 p=uid;
57 if (!p)
58 {
59 perror("malloc");
60 return (AUTHSASL_ERROR);
61 }
62
63 if (*p == '*')
64 {
65 free(p);
66 return (AUTHSASL_ABORTED);
67 }
68 }
69
70 if ((n=authsasl_frombase64(p)) < 0)
71 {
72 free(p);
73 return (AUTHSASL_ABORTED);
74 }
75 p[n]=0;
76
77 uid=pw=0;
78
79 for (i=0; i<n; i++)
80 {
81 if (p[i] == 0)
82 {
83 ++i;
84 for (uid=p+i; i<n; i++)
85 if (p[i] == 0)
86 {
87 pw=p+i+1;
88 break;
89 }
90 }
91 }
92
93 if (pw == 0)
94 {
95 free(p);
96 return (AUTHSASL_ABORTED); /* Bad message */
97 }
98
99 if ( (*authtype=malloc(sizeof(AUTHTYPE_LOGIN))) == 0)
100 {
101 free(p);
102 perror("malloc");
103 return (AUTHSASL_ERROR);
104 }
105
106 strcpy( *authtype, AUTHTYPE_LOGIN);
107
108 if ( (*authdata=strdupdefdomain(uid, "\n", pw, "\n")) == 0)
109 {
110 free( *authtype );
111 free(p);
112 perror("malloc");
113 return (AUTHSASL_ERROR);
114 }
115
116 free(p);
117 return (AUTHSASL_OK);
118 }