complete moving logic to server
[cyrus-sasl.git] / lib / client.c
1 /* SASL client API implementation
2  * Rob Siemborski
3  * Tim Martin
4  * $Id: client.c,v 1.67 2006/04/26 15:33:41 mel Exp $
5  */
6 /* 
7  * Copyright (c) 1998-2003 Carnegie Mellon University.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer. 
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. The name "Carnegie Mellon University" must not be used to
22  *    endorse or promote products derived from this software without
23  *    prior written permission. For permission or any other legal
24  *    details, please contact  
25  *      Office of Technology Transfer
26  *      Carnegie Mellon University
27  *      5000 Forbes Avenue
28  *      Pittsburgh, PA  15213-3890
29  *      (412) 268-4387, fax: (412) 268-7395
30  *      tech-transfer@andrew.cmu.edu
31  *
32  * 4. Redistributions of any form whatsoever must retain the following
33  *    acknowledgment:
34  *    "This product includes software developed by Computing Services
35  *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
36  *
37  * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
38  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
39  * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
40  * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
41  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
42  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
43  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
44  */
45
46 #include <config.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <limits.h>
50 #include <ctype.h>
51 #include <string.h>
52 #ifdef HAVE_UNISTD_H
53 #include <unistd.h>
54 #endif
55
56 /* SASL Headers */
57 #include "sasl.h"
58 #include "saslplug.h"
59 #include "saslutil.h"
60 #include "saslint.h"
61
62 static cmech_list_t *cmechlist; /* global var which holds the list */
63 sasl_global_callbacks_t global_callbacks_client; 
64 static int _sasl_client_active = 0;
65
66 static int init_mechlist()
67 {
68   cmechlist->mutex = sasl_MUTEX_ALLOC();
69   if(!cmechlist->mutex) return SASL_FAIL;
70   
71   cmechlist->utils=_sasl_alloc_utils(NULL, &global_callbacks_client);
72   if (cmechlist->utils==NULL)
73     return SASL_NOMEM;
74
75   cmechlist->mech_list=NULL;
76   cmechlist->mech_length=0;
77
78   return SASL_OK;
79 }
80
81 static int client_done(void) {
82   cmechanism_t *cm;
83   cmechanism_t *cprevm;
84
85   if(!_sasl_client_active)
86       return SASL_NOTINIT;
87   else
88       _sasl_client_active--;
89   
90   if(_sasl_client_active) {
91       /* Don't de-init yet! Our refcount is nonzero. */
92       return SASL_CONTINUE;
93   }
94   
95   cm=cmechlist->mech_list; /* m point to begging of the list */
96   while (cm!=NULL)
97   {
98     cprevm=cm;
99     cm=cm->next;
100
101     if (cprevm->m.plug->mech_free) {
102         cprevm->m.plug->mech_free(cprevm->m.plug->glob_context,
103                                 cmechlist->utils);
104     }
105
106     sasl_FREE(cprevm->m.plugname);
107     sasl_FREE(cprevm);    
108   }
109   sasl_MUTEX_FREE(cmechlist->mutex);
110   _sasl_free_utils(&cmechlist->utils);
111   sasl_FREE(cmechlist);
112
113   cmechlist = NULL;
114
115   return SASL_OK;
116 }
117
118 int sasl_client_add_plugin(const char *plugname,
119                            sasl_client_plug_init_t *entry_point)
120 {
121   int plugcount;
122   sasl_client_plug_t *pluglist;
123   cmechanism_t *mech;
124   int result;
125   int version;
126   int lupe;
127
128   if(!plugname || !entry_point) return SASL_BADPARAM;
129   
130   result = entry_point(cmechlist->utils, SASL_CLIENT_PLUG_VERSION, &version,
131                        &pluglist, &plugcount);
132
133   if (result != SASL_OK)
134   {
135     _sasl_log(NULL, SASL_LOG_WARN,
136               "entry_point failed in sasl_client_add_plugin for %s",
137               plugname);
138     return result;
139   }
140
141   if (version != SASL_CLIENT_PLUG_VERSION)
142   {
143     _sasl_log(NULL, SASL_LOG_WARN,
144               "version conflict in sasl_client_add_plugin for %s", plugname);
145     return SASL_BADVERS;
146   }
147
148   for (lupe=0;lupe< plugcount ;lupe++)
149     {
150       mech = sasl_ALLOC(sizeof(cmechanism_t));
151       if (! mech) return SASL_NOMEM;
152
153       mech->m.plug=pluglist++;
154       if(_sasl_strdup(plugname, &mech->m.plugname, NULL) != SASL_OK) {
155         sasl_FREE(mech);
156         return SASL_NOMEM;
157       }
158       mech->m.version = version;
159       mech->next = cmechlist->mech_list;
160       cmechlist->mech_list = mech;
161       cmechlist->mech_length++;
162     }
163
164   return SASL_OK;
165 }
166
167 static int
168 client_idle(sasl_conn_t *conn)
169 {
170   cmechanism_t *m;
171   if (! cmechlist)
172     return 0;
173
174   for (m = cmechlist->mech_list;
175        m;
176        m = m->next)
177     if (m->m.plug->idle
178         &&  m->m.plug->idle(m->m.plug->glob_context,
179                           conn,
180                           conn ? ((sasl_client_conn_t *)conn)->cparams : NULL))
181       return 1;
182   return 0;
183 }
184
185 /* initialize the SASL client drivers
186  *  callbacks      -- base callbacks for all client connections
187  * returns:
188  *  SASL_OK        -- Success
189  *  SASL_NOMEM     -- Not enough memory
190  *  SASL_BADVERS   -- Mechanism version mismatch
191  *  SASL_BADPARAM  -- error in config file
192  *  SASL_NOMECH    -- No mechanisms available
193  *  ...
194  */
195
196 int sasl_client_init(const sasl_callback_t *callbacks)
197 {
198   int ret;
199   const add_plugin_list_t ep_list[] = {
200       { "sasl_client_plug_init", (add_plugin_t *)sasl_client_add_plugin },
201       { "sasl_canonuser_init", (add_plugin_t *)sasl_canonuser_add_plugin },
202       { NULL, NULL }
203   };
204
205   if(_sasl_client_active) {
206       /* We're already active, just increase our refcount */
207       /* xxx do something with the callback structure? */
208       _sasl_client_active++;
209       return SASL_OK;
210   }
211
212   global_callbacks_client.callbacks = callbacks;
213   global_callbacks_client.appname = NULL;
214
215   cmechlist=sasl_ALLOC(sizeof(cmech_list_t));
216   if (cmechlist==NULL) return SASL_NOMEM;
217
218   /* We need to call client_done if we fail now */
219   _sasl_client_active = 1;
220
221   /* load plugins */
222   ret=init_mechlist();  
223   if (ret!=SASL_OK) {
224       client_done();
225       return ret;
226   }
227
228   sasl_client_add_plugin("EXTERNAL", &external_client_plug_init);
229
230   ret = _sasl_common_init(&global_callbacks_client);
231
232   if (ret == SASL_OK)
233       ret = _sasl_load_plugins(ep_list,
234                                _sasl_find_getpath_callback(callbacks),
235                                _sasl_find_verifyfile_callback(callbacks));
236   
237   if (ret == SASL_OK) {
238       _sasl_client_cleanup_hook = &client_done;
239       _sasl_client_idle_hook = &client_idle;
240
241       ret = _sasl_build_mechlist();
242   } else {
243       client_done();
244   }
245       
246   return ret;
247 }
248
249 static void client_dispose(sasl_conn_t *pconn)
250 {
251   sasl_client_conn_t *c_conn=(sasl_client_conn_t *) pconn;
252
253   if (c_conn->mech && c_conn->mech->m.plug->mech_dispose) {
254     c_conn->mech->m.plug->mech_dispose(pconn->context,
255                                      c_conn->cparams->utils);
256   }
257
258   pconn->context = NULL;
259
260   if (c_conn->clientFQDN)
261       sasl_FREE(c_conn->clientFQDN);
262
263   if (c_conn->cparams) {
264       _sasl_free_utils(&(c_conn->cparams->utils));
265       sasl_FREE(c_conn->cparams);
266   }
267
268   _sasl_conn_dispose(pconn);
269 }
270
271 /* initialize a client exchange based on the specified mechanism
272  *  service       -- registered name of the service using SASL (e.g. "imap")
273  *  serverFQDN    -- the fully qualified domain name of the server
274  *  iplocalport   -- client IPv4/IPv6 domain literal string with port
275  *                    (if NULL, then mechanisms requiring IPaddr are disabled)
276  *  ipremoteport  -- server IPv4/IPv6 domain literal string with port
277  *                    (if NULL, then mechanisms requiring IPaddr are disabled)
278  *  prompt_supp   -- list of client interactions supported
279  *                   may also include sasl_getopt_t context & call
280  *                   NULL prompt_supp = user/pass via SASL_INTERACT only
281  *                   NULL proc = interaction supported via SASL_INTERACT
282  *  secflags      -- security flags (see above)
283  * in/out:
284  *  pconn         -- connection negotiation structure
285  *                   pointer to NULL => allocate new
286  *                   non-NULL => recycle storage and go for next available mech
287  *
288  * Returns:
289  *  SASL_OK       -- success
290  *  SASL_NOMECH   -- no mechanism meets requested properties
291  *  SASL_NOMEM    -- not enough memory
292  */
293 int sasl_client_new(const char *service,
294                     const char *serverFQDN,
295                     const char *iplocalport,
296                     const char *ipremoteport,
297                     const sasl_callback_t *prompt_supp,
298                     unsigned flags,
299                     sasl_conn_t **pconn)
300 {
301   int result;
302   char name[MAXHOSTNAMELEN];
303   sasl_client_conn_t *conn;
304   sasl_utils_t *utils;
305
306   if(_sasl_client_active==0) return SASL_NOTINIT;
307   
308   /* Remember, serverFQDN, iplocalport and ipremoteport can be NULL and be valid! */
309   if (!pconn || !service)
310     return SASL_BADPARAM;
311
312   *pconn=sasl_ALLOC(sizeof(sasl_client_conn_t));
313   if (*pconn==NULL) {
314       _sasl_log(NULL, SASL_LOG_ERR,
315                 "Out of memory allocating connection context");
316       return SASL_NOMEM;
317   }
318   memset(*pconn, 0, sizeof(sasl_client_conn_t));
319
320   (*pconn)->destroy_conn = &client_dispose;
321
322   conn = (sasl_client_conn_t *)*pconn;
323   
324   conn->mech = NULL;
325
326   conn->cparams=sasl_ALLOC(sizeof(sasl_client_params_t));
327   if (conn->cparams==NULL) 
328       MEMERROR(*pconn);
329   memset(conn->cparams,0,sizeof(sasl_client_params_t));
330
331   result = _sasl_conn_init(*pconn, service, flags, SASL_CONN_CLIENT,
332                            &client_idle, serverFQDN,
333                            iplocalport, ipremoteport,
334                            prompt_supp, &global_callbacks_client);
335   if (result != SASL_OK) RETURN(*pconn, result);
336   
337   utils=_sasl_alloc_utils(*pconn, &global_callbacks_client);
338   if (utils==NULL)
339       MEMERROR(*pconn);
340   
341   utils->conn= *pconn;
342
343   /* Setup the non-lazy parts of cparams, the rest is done in
344    * sasl_client_start */
345   conn->cparams->utils = utils;
346   conn->cparams->canon_user = &_sasl_canon_user;
347   conn->cparams->flags = flags;
348   conn->cparams->prompt_supp = (*pconn)->callbacks;
349   
350   /* get the clientFQDN (serverFQDN was set in _sasl_conn_init) */
351   memset(name, 0, sizeof(name));
352   gethostname(name, MAXHOSTNAMELEN);
353
354   result = _sasl_strdup(name, &conn->clientFQDN, NULL);
355
356   if(result == SASL_OK) return SASL_OK;
357
358   /* result isn't SASL_OK */
359   _sasl_conn_dispose(*pconn);
360   sasl_FREE(*pconn);
361   *pconn = NULL;
362   _sasl_log(NULL, SASL_LOG_ERR, "Out of memory in sasl_client_new");
363   return result;
364 }
365
366 static int have_prompts(sasl_conn_t *conn,
367                         const sasl_client_plug_t *mech)
368 {
369   static const unsigned long default_prompts[] = {
370     SASL_CB_AUTHNAME,
371     SASL_CB_PASS,
372     SASL_CB_LIST_END
373   };
374
375   const unsigned long *prompt;
376   int (*pproc)();
377   void *pcontext;
378   int result;
379
380   for (prompt = (mech->required_prompts
381                  ? mech->required_prompts :
382                  default_prompts);
383        *prompt != SASL_CB_LIST_END;
384        prompt++) {
385     result = _sasl_getcallback(conn, *prompt, &pproc, &pcontext);
386     if (result != SASL_OK && result != SASL_INTERACT)
387       return 0;                 /* we don't have this required prompt */
388   }
389
390   return 1; /* we have all the prompts */
391 }
392
393 static int
394 _mech_plus_p(const char *mech, size_t len)
395 {
396     return (len > 5 && strncasecmp(&mech[len - 5], "-PLUS", 5) == 0);
397 }
398
399 /*
400  * Order PLUS mechanisms first. Returns NUL separated list of
401  * *count items.
402  */
403 static int
404 _sasl_client_order_mechs(const sasl_utils_t *utils,
405                          const char *mechs,
406                          int has_cb_data,
407                          char **ordered_mechs,
408                          size_t *count,
409                          int *server_can_cb)
410 {
411     char *list, *listp;
412     size_t i;
413     const char *p, *start  = NULL;
414
415     *count = 0;
416     *server_can_cb = 0;
417
418     listp = list = utils->malloc(strlen(mechs) + 1);
419     if (list == NULL)
420         return SASL_NOMEM;
421
422     if (has_cb_data) {
423         for (start = p = mechs, i = 0; *p != '\0'; p++) {
424             if (isspace(*p) || p[1] == '\0') {
425                 size_t len = p - start + 1;
426
427                 if (_mech_plus_p(start, len)) {
428                     memcpy(listp, start, len);
429                     listp[len] = '\0';
430                     listp += len + 1;
431                     (*count)++;
432                     *server_can_cb = 1;
433                 }
434                 start = p + 1;
435             }
436         }
437     }
438
439     for (start = p = mechs, i = 0; *p != '\0'; p++) {
440         if (isspace(*p) || p[1] == '\0') {
441             size_t len = p - start + 1;
442
443             if (!_mech_plus_p(start, len)) {
444                 memcpy(listp, start, len);
445                 listp[len] = '\0';
446                 listp += len + 1;
447                 (*count)++;
448             }
449             start = p + 1;
450         }
451     }
452
453     *listp = '\0';
454     *ordered_mechs = list;
455
456     return SASL_OK;
457 }
458
459 /* select a mechanism for a connection
460  *  mechlist      -- mechanisms server has available (punctuation ignored)
461  *  secret        -- optional secret from previous session
462  * output:
463  *  prompt_need   -- on SASL_INTERACT, list of prompts needed to continue
464  *  clientout     -- the initial client response to send to the server
465  *  mech          -- set to mechanism name
466  *
467  * Returns:
468  *  SASL_OK       -- success
469  *  SASL_NOMEM    -- not enough memory
470  *  SASL_NOMECH   -- no mechanism meets requested properties
471  *  SASL_INTERACT -- user interaction needed to fill in prompt_need list
472  */
473
474 /* xxx confirm this with rfc 2222
475  * SASL mechanism allowable characters are "AZaz-_"
476  * seperators can be any other characters and of any length
477  * even variable lengths between
478  *
479  * Apps should be encouraged to simply use space or comma space
480  * though
481  */
482 int sasl_client_start(sasl_conn_t *conn,
483                       const char *mechlist,
484                       sasl_interact_t **prompt_need,
485                       const char **clientout,
486                       unsigned *clientoutlen,
487                       const char **mech)
488 {
489     sasl_client_conn_t *c_conn= (sasl_client_conn_t *) conn;
490     char *ordered_mechs = NULL, *name;
491     cmechanism_t *m=NULL,*bestm=NULL;
492     size_t i, list_len;
493     sasl_ssf_t bestssf = 0, minssf = 0;
494     int result, server_can_cb = 0;
495
496     if(_sasl_client_active==0) return SASL_NOTINIT;
497
498     if (!conn) return SASL_BADPARAM;
499
500     /* verify parameters */
501     if (mechlist == NULL)
502         PARAMERROR(conn);
503
504     /* if prompt_need != NULL we've already been here
505        and just need to do the continue step again */
506
507     /* do a step */
508     /* FIXME: Hopefully they only give us our own prompt_need back */
509     if (prompt_need && *prompt_need != NULL) {
510         goto dostep;
511     }
512
513     if(conn->props.min_ssf < conn->external.ssf) {
514         minssf = 0;
515     } else {
516         minssf = conn->props.min_ssf - conn->external.ssf;
517     }
518
519     result = _sasl_client_order_mechs(c_conn->cparams->utils,
520                                       mechlist,
521                                       SASL_CB_PRESENT(c_conn->cparams),
522                                       &ordered_mechs,
523                                       &list_len,
524                                       &server_can_cb);
525     if (result != 0)
526         return result;
527
528     /* If we have CB and the server supports it, we should use it */
529     if (SASL_CB_PRESENT(c_conn->cparams) && server_can_cb)
530         c_conn->cparams->chanbindingflag = SASL_CB_FLAG_WANT;
531     else
532         c_conn->cparams->chanbindingflag = SASL_CB_FLAG_NONE;
533
534     for (i = 0, name = ordered_mechs; i < list_len; i++) {
535         /* foreach in client list */
536         for (m = cmechlist->mech_list; m != NULL; m = m->next) {
537             int myflags, plus;
538
539             if (!_sasl_is_equal_mech(name, m->m.plug->mech_name, &plus))
540                 continue;
541
542             /* Do we have the prompts for it? */
543             if (!have_prompts(conn, m->m.plug))
544                 break;
545
546             /* Is it strong enough? */
547             if (minssf > m->m.plug->max_ssf)
548                 break;
549
550             /* Does it meet our security properties? */
551             myflags = conn->props.security_flags;
552             
553             /* if there's an external layer this is no longer plaintext */
554             if ((conn->props.min_ssf <= conn->external.ssf) && 
555                 (conn->external.ssf > 1)) {
556                 myflags &= ~SASL_SEC_NOPLAINTEXT;
557             }
558
559             if (((myflags ^ m->m.plug->security_flags) & myflags) != 0) {
560                 break;
561             }
562
563             /* Can we meet it's features? */
564             if ((m->m.plug->features & SASL_FEAT_NEEDSERVERFQDN)
565                 && !conn->serverFQDN) {
566                 break;
567             }
568
569             /* Can it meet our features? */
570             if ((conn->flags & SASL_NEED_PROXY) &&
571                 !(m->m.plug->features & SASL_FEAT_ALLOWS_PROXY)) {
572                 break;
573             }
574
575 #ifdef PREFER_MECH
576             if (strcasecmp(m->m.plug->mech_name, PREFER_MECH) &&
577                 bestm && m->m.plug->max_ssf <= bestssf) {
578                 /* this mechanism isn't our favorite, and it's no better
579                    than what we already have! */
580                 break;
581             }
582 #else
583             if (bestm && m->m.plug->max_ssf <= bestssf) {
584                 /* this mechanism is no better than what we already have! */
585                 break;
586             }
587 #endif
588
589             /* compare security flags, only take new mechanism if it has
590              * all the security flags of the previous one.
591              *
592              * From the mechanisms we ship with, this yields the order:
593              *
594              * SRP
595              * GSSAPI + KERBEROS_V4
596              * DIGEST + OTP
597              * CRAM + EXTERNAL
598              * PLAIN + LOGIN + ANONYMOUS
599              *
600              * This might be improved on by comparing the numeric value of
601              * the bitwise-or'd security flags, which splits DIGEST/OTP,
602              * CRAM/EXTERNAL, and PLAIN/LOGIN from ANONYMOUS, but then we
603              * are depending on the numeric values of the flags (which may
604              * change, and their ordering could be considered dumb luck.
605              */
606
607             if (bestm &&
608                 ((m->m.plug->security_flags ^ bestm->m.plug->security_flags) &
609                  bestm->m.plug->security_flags)) {
610                 break;
611             }
612
613             /* Prefer server advertised CB mechanisms */
614             if (SASL_CB_PRESENT(c_conn->cparams) && plus)
615                 c_conn->cparams->chanbindingflag = SASL_CB_FLAG_USED;
616
617             if (mech) {
618                 *mech = m->m.plug->mech_name;
619             }
620             bestssf = m->m.plug->max_ssf;
621             bestm = m;
622             break;
623         }
624         name += strlen(name) + 1;
625     }
626
627     if (bestm == NULL) {
628         sasl_seterror(conn, 0, "No worthy mechs found");
629         result = SASL_NOMECH;
630         goto done;
631     }
632
633     /* make (the rest of) cparams */
634     c_conn->cparams->service = conn->service;
635     c_conn->cparams->servicelen = (unsigned) strlen(conn->service);
636     
637     if (conn->serverFQDN) {
638         c_conn->cparams->serverFQDN = conn->serverFQDN; 
639         c_conn->cparams->slen = (unsigned) strlen(conn->serverFQDN);
640     }
641
642     c_conn->cparams->clientFQDN = c_conn->clientFQDN; 
643     c_conn->cparams->clen = (unsigned) strlen(c_conn->clientFQDN);
644
645     c_conn->cparams->external_ssf = conn->external.ssf;
646     c_conn->cparams->props = conn->props;
647     c_conn->mech = bestm;
648
649     /* init that plugin */
650     result = c_conn->mech->m.plug->mech_new(c_conn->mech->m.plug->glob_context,
651                                           c_conn->cparams,
652                                           &(conn->context));
653     if(result != SASL_OK) goto done;
654
655     /* do a step -- but only if we can do a client-send-first */
656  dostep:
657     if(clientout) {
658         if(c_conn->mech->m.plug->features & SASL_FEAT_SERVER_FIRST) {
659             *clientout = NULL;
660             *clientoutlen = 0;
661             result = SASL_CONTINUE;
662         } else {
663             result = sasl_client_step(conn, NULL, 0, prompt_need,
664                                       clientout, clientoutlen);
665         }
666     }
667     else
668         result = SASL_CONTINUE;
669
670  done:
671     if (ordered_mechs != NULL)
672         c_conn->cparams->utils->free(ordered_mechs);
673     RETURN(conn, result);
674 }
675
676 /* do a single authentication step.
677  *  serverin    -- the server message received by the client, MUST have a NUL
678  *                 sentinel, not counted by serverinlen
679  * output:
680  *  prompt_need -- on SASL_INTERACT, list of prompts needed to continue
681  *  clientout   -- the client response to send to the server
682  *
683  * returns:
684  *  SASL_OK        -- success
685  *  SASL_INTERACT  -- user interaction needed to fill in prompt_need list
686  *  SASL_BADPROT   -- server protocol incorrect/cancelled
687  *  SASL_BADSERV   -- server failed mutual auth
688  */
689
690 int sasl_client_step(sasl_conn_t *conn,
691                      const char *serverin,
692                      unsigned serverinlen,
693                      sasl_interact_t **prompt_need,
694                      const char **clientout,
695                      unsigned *clientoutlen)
696 {
697   sasl_client_conn_t *c_conn= (sasl_client_conn_t *) conn;
698   int result;
699
700   if(_sasl_client_active==0) return SASL_NOTINIT;
701   if(!conn) return SASL_BADPARAM;
702
703   /* check parameters */
704   if ((serverin==NULL) && (serverinlen>0))
705       PARAMERROR(conn);
706
707   /* Don't do another step if the plugin told us that we're done */
708   if (conn->oparams.doneflag) {
709       _sasl_log(conn, SASL_LOG_ERR, "attempting client step after doneflag");
710       return SASL_FAIL;
711   }
712
713   if(clientout) *clientout = NULL;
714   if(clientoutlen) *clientoutlen = 0;
715
716   /* do a step */
717   result = c_conn->mech->m.plug->mech_step(conn->context,
718                                          c_conn->cparams,
719                                          serverin,
720                                          serverinlen,
721                                          prompt_need,
722                                          clientout, clientoutlen,
723                                          &conn->oparams);
724
725   if (result == SASL_OK) {
726       /* So we're done on this end, but if both
727        * 1. the mech does server-send-last
728        * 2. the protocol does not
729        * we need to return no data */
730       if(!*clientout && !(conn->flags & SASL_SUCCESS_DATA)) {
731           *clientout = "";
732           *clientoutlen = 0;
733       }
734       
735       if(!conn->oparams.maxoutbuf) {
736           conn->oparams.maxoutbuf = conn->props.maxbufsize;
737       }
738
739       if(conn->oparams.user == NULL || conn->oparams.authid == NULL) {
740           sasl_seterror(conn, 0,
741                         "mech did not call canon_user for both authzid and authid");
742           result = SASL_BADPROT;
743       }
744   }  
745
746   RETURN(conn,result);
747 }
748
749 /* returns the length of all the mechanisms
750  * added up 
751  */
752
753 static unsigned mech_names_len()
754 {
755   cmechanism_t *listptr;
756   unsigned result = 0;
757
758   for (listptr = cmechlist->mech_list;
759        listptr;
760        listptr = listptr->next)
761     result += (unsigned) strlen(listptr->m.plug->mech_name);
762
763   return result;
764 }
765
766
767 int _sasl_client_listmech(sasl_conn_t *conn,
768                           const char *prefix,
769                           const char *sep,
770                           const char *suffix,
771                           const char **result,
772                           unsigned *plen,
773                           int *pcount)
774 {
775     cmechanism_t *m=NULL;
776     sasl_ssf_t minssf = 0;
777     int ret;
778     size_t resultlen;
779     int flag;
780     const char *mysep;
781
782     if(_sasl_client_active == 0) return SASL_NOTINIT;
783     if (!conn) return SASL_BADPARAM;
784     if(conn->type != SASL_CONN_CLIENT) PARAMERROR(conn);
785     
786     if (! result)
787         PARAMERROR(conn);
788     
789     if (plen != NULL)
790         *plen = 0;
791     if (pcount != NULL)
792         *pcount = 0;
793
794     if (sep) {
795         mysep = sep;
796     } else {
797         mysep = " ";
798     }
799
800     if(conn->props.min_ssf < conn->external.ssf) {
801         minssf = 0;
802     } else {
803         minssf = conn->props.min_ssf - conn->external.ssf;
804     }
805
806     if (! cmechlist || cmechlist->mech_length <= 0)
807         INTERROR(conn, SASL_NOMECH);
808
809     resultlen = (prefix ? strlen(prefix) : 0)
810         + (strlen(mysep) * (cmechlist->mech_length - 1))
811         + mech_names_len()
812         + (suffix ? strlen(suffix) : 0)
813         + 1;
814     ret = _buf_alloc(&conn->mechlist_buf,
815                      &conn->mechlist_buf_len, resultlen);
816     if(ret != SASL_OK) MEMERROR(conn);
817
818     if (prefix)
819         strcpy (conn->mechlist_buf,prefix);
820     else
821         *(conn->mechlist_buf) = '\0';
822
823     flag = 0;
824     for (m = cmechlist->mech_list; m != NULL; m = m->next) {
825             /* do we have the prompts for it? */
826             if (!have_prompts(conn, m->m.plug))
827                 continue;
828
829             /* is it strong enough? */
830             if (minssf > m->m.plug->max_ssf)
831                 continue;
832
833             /* does it meet our security properties? */
834             if (((conn->props.security_flags ^ m->m.plug->security_flags)
835                  & conn->props.security_flags) != 0) {
836                 continue;
837             }
838
839             /* Can we meet it's features? */
840             if ((m->m.plug->features & SASL_FEAT_NEEDSERVERFQDN)
841                 && !conn->serverFQDN) {
842                 continue;
843             }
844
845             /* Can it meet our features? */
846             if ((conn->flags & SASL_NEED_PROXY) &&
847                 !(m->m.plug->features & SASL_FEAT_ALLOWS_PROXY)) {
848                 continue;
849             }
850
851             /* Okay, we like it, add it to the list! */
852
853             if (pcount != NULL)
854                 (*pcount)++;
855
856             /* print seperator */
857             if (flag) {
858                 strcat(conn->mechlist_buf, mysep);
859             } else {
860                 flag = 1;
861             }
862             
863             /* now print the mechanism name */
864             strcat(conn->mechlist_buf, m->m.plug->mech_name);
865     }
866     
867   if (suffix)
868       strcat(conn->mechlist_buf,suffix);
869
870   if (plen!=NULL)
871       *plen = (unsigned) strlen(conn->mechlist_buf);
872
873   *result = conn->mechlist_buf;
874
875   return SASL_OK;
876 }
877
878 sasl_string_list_t *_sasl_client_mechs(void) 
879 {
880   cmechanism_t *listptr;
881   sasl_string_list_t *retval = NULL, *next=NULL;
882
883   if(!_sasl_client_active) return NULL;
884
885   /* make list */
886   for (listptr = cmechlist->mech_list; listptr; listptr = listptr->next) {
887       next = sasl_ALLOC(sizeof(sasl_string_list_t));
888
889       if(!next && !retval) return NULL;
890       else if(!next) {
891           next = retval->next;
892           do {
893               sasl_FREE(retval);
894               retval = next;
895               next = retval->next;
896           } while(next);
897           return NULL;
898       }
899       
900       next->d = listptr->m.plug->mech_name;
901
902       if(!retval) {
903           next->next = NULL;
904           retval = next;
905       } else {
906           next->next = retval;
907           retval = next;
908       }
909   }
910
911   return retval;
912 }
913
914
915
916
917 /* It would be nice if we can show other information like Author, Company, Year, plugin version */
918 static void
919 _sasl_print_mechanism (
920   client_sasl_mechanism_t *m,
921   sasl_info_callback_stage_t stage,
922   void *rock
923 )
924 {
925     char delimiter;
926
927     if (stage == SASL_INFO_LIST_START) {
928         printf ("List of client plugins follows\n");
929         return;
930     } else if (stage == SASL_INFO_LIST_END) {
931         return;
932     }
933
934     /* Process the mechanism */
935     printf ("Plugin \"%s\" ", m->plugname);
936
937     /* There is no delay loading for client side plugins */
938     printf ("[loaded]");
939
940     printf (", \tAPI version: %d\n", m->version);
941
942     if (m->plug != NULL) {
943         printf ("\tSASL mechanism: %s, best SSF: %d\n",
944                 m->plug->mech_name,
945                 m->plug->max_ssf);
946
947         printf ("\tsecurity flags:");
948         
949         delimiter = ' ';
950         if (m->plug->security_flags & SASL_SEC_NOANONYMOUS) {
951             printf ("%cNO_ANONYMOUS", delimiter);
952             delimiter = '|';
953         }
954
955         if (m->plug->security_flags & SASL_SEC_NOPLAINTEXT) {
956             printf ("%cNO_PLAINTEXT", delimiter);
957             delimiter = '|';
958         }
959         
960         if (m->plug->security_flags & SASL_SEC_NOACTIVE) {
961             printf ("%cNO_ACTIVE", delimiter);
962             delimiter = '|';
963         }
964
965         if (m->plug->security_flags & SASL_SEC_NODICTIONARY) {
966             printf ("%cNO_DICTIONARY", delimiter);
967             delimiter = '|';
968         }
969
970         if (m->plug->security_flags & SASL_SEC_FORWARD_SECRECY) {
971             printf ("%cFORWARD_SECRECY", delimiter);
972             delimiter = '|';
973         }
974
975         if (m->plug->security_flags & SASL_SEC_PASS_CREDENTIALS) {
976             printf ("%cPASS_CREDENTIALS", delimiter);
977             delimiter = '|';
978         }
979
980         if (m->plug->security_flags & SASL_SEC_MUTUAL_AUTH) {
981             printf ("%cMUTUAL_AUTH", delimiter);
982             delimiter = '|';
983         }
984
985
986
987         printf ("\n\tfeatures:");
988         
989         delimiter = ' ';
990         if (m->plug->features & SASL_FEAT_WANT_CLIENT_FIRST) {
991             printf ("%cWANT_CLIENT_FIRST", delimiter);
992             delimiter = '|';
993         }
994
995         if (m->plug->features & SASL_FEAT_SERVER_FIRST) {
996             printf ("%cSERVER_FIRST", delimiter);
997             delimiter = '|';
998         }
999
1000         if (m->plug->features & SASL_FEAT_ALLOWS_PROXY) {
1001             printf ("%cPROXY_AUTHENTICATION", delimiter);
1002             delimiter = '|';
1003         }
1004
1005         if (m->plug->features & SASL_FEAT_NEEDSERVERFQDN) {
1006             printf ("%cNEED_SERVER_FQDN", delimiter);
1007             delimiter = '|';
1008         }
1009
1010         if (m->plug->features & SASL_FEAT_GSS_FRAMING) {
1011             printf ("%cGSS_FRAMING", delimiter);
1012             delimiter = '|';
1013         }
1014
1015         if (m->plug->features & SASL_FEAT_CHANNEL_BINDING) {
1016             printf ("%cCHANNEL_BINDING", delimiter);
1017             delimiter = '|';
1018         }
1019     }
1020
1021 /* Delay loading is not supported for the client side plugins:
1022     if (m->f) {
1023         printf ("\n\twill be loaded from \"%s\"", m->f);
1024     }
1025  */
1026
1027     printf ("\n");
1028 }
1029
1030
1031 /* Dump information about available client plugins */
1032 int sasl_client_plugin_info (
1033   const char *c_mech_list,              /* space separated mechanism list or NULL for ALL */
1034   sasl_client_info_callback_t *info_cb,
1035   void *info_cb_rock
1036 )
1037 {
1038     cmechanism_t *m;
1039     client_sasl_mechanism_t plug_data;
1040     char * cur_mech;
1041     char * mech_list = NULL;
1042     char * p;
1043
1044     if (info_cb == NULL) {
1045         info_cb = _sasl_print_mechanism;
1046     }
1047
1048     if (cmechlist != NULL) {
1049         info_cb (NULL, SASL_INFO_LIST_START, info_cb_rock);
1050
1051         if (c_mech_list == NULL) {
1052             m = cmechlist->mech_list; /* m point to beginning of the list */
1053
1054             while (m != NULL) {
1055                 memcpy (&plug_data, &m->m, sizeof(plug_data));
1056
1057                 info_cb (&plug_data, SASL_INFO_LIST_MECH, info_cb_rock);
1058             
1059                 m = m->next;
1060             }
1061         } else {
1062             mech_list = strdup (c_mech_list);
1063
1064             cur_mech = mech_list;
1065
1066             while (cur_mech != NULL) {
1067                 p = strchr (cur_mech, ' ');
1068                 if (p != NULL) {
1069                     *p = '\0';
1070                     p++;
1071                 }
1072
1073                 m = cmechlist->mech_list; /* m point to beginning of the list */
1074
1075                 while (m != NULL) {
1076                     if (strcasecmp (cur_mech, m->m.plug->mech_name) == 0) {
1077                         memcpy (&plug_data, &m->m, sizeof(plug_data));
1078
1079                         info_cb (&plug_data, SASL_INFO_LIST_MECH, info_cb_rock);
1080                     }
1081             
1082                     m = m->next;
1083                 }
1084
1085                 cur_mech = p;
1086             }
1087
1088             free (mech_list);
1089         }
1090
1091         info_cb (NULL, SASL_INFO_LIST_END, info_cb_rock);
1092
1093         return (SASL_OK);
1094     }
1095
1096     return (SASL_NOTINIT);
1097 }