move more CB selection logic to libsasl
[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 /* select a mechanism for a connection
394  *  mechlist      -- mechanisms server has available (punctuation ignored)
395  *  secret        -- optional secret from previous session
396  * output:
397  *  prompt_need   -- on SASL_INTERACT, list of prompts needed to continue
398  *  clientout     -- the initial client response to send to the server
399  *  mech          -- set to mechanism name
400  *
401  * Returns:
402  *  SASL_OK       -- success
403  *  SASL_NOMEM    -- not enough memory
404  *  SASL_NOMECH   -- no mechanism meets requested properties
405  *  SASL_INTERACT -- user interaction needed to fill in prompt_need list
406  */
407
408 /* xxx confirm this with rfc 2222
409  * SASL mechanism allowable characters are "AZaz-_"
410  * seperators can be any other characters and of any length
411  * even variable lengths between
412  *
413  * Apps should be encouraged to simply use space or comma space
414  * though
415  */
416 int sasl_client_start(sasl_conn_t *conn,
417                       const char *mechlist,
418                       sasl_interact_t **prompt_need,
419                       const char **clientout,
420                       unsigned *clientoutlen,
421                       const char **mech)
422 {
423     sasl_client_conn_t *c_conn= (sasl_client_conn_t *) conn;
424     char name[SASL_MECHNAMEMAX + 1];
425     cmechanism_t *m=NULL,*bestm=NULL;
426     size_t pos=0,place;
427     size_t list_len;
428     sasl_ssf_t bestssf = 0, minssf = 0;
429     int result;
430
431     if(_sasl_client_active==0) return SASL_NOTINIT;
432
433     if (!conn) return SASL_BADPARAM;
434
435     /* verify parameters */
436     if (mechlist == NULL)
437         PARAMERROR(conn);
438
439     /* if prompt_need != NULL we've already been here
440        and just need to do the continue step again */
441
442     /* do a step */
443     /* FIXME: Hopefully they only give us our own prompt_need back */
444     if (prompt_need && *prompt_need != NULL) {
445         goto dostep;
446     }
447
448     if(conn->props.min_ssf < conn->external.ssf) {
449         minssf = 0;
450     } else {
451         minssf = conn->props.min_ssf - conn->external.ssf;
452     }
453
454     c_conn->cparams->chanbindingflag = SASL_CB_FLAG_NONE;
455
456     /* parse mechlist */
457     list_len = strlen(mechlist);
458
459     while (pos<list_len)
460     {
461         place=0;
462         while ((pos<list_len) && (isalnum((unsigned char)mechlist[pos])
463                                   || mechlist[pos] == '_'
464                                   || mechlist[pos] == '-')) {
465             name[place]=mechlist[pos];
466             pos++;
467             place++;
468             if (SASL_MECHNAMEMAX < place) {
469                 place--;
470                 while(pos<list_len && (isalnum((unsigned char)mechlist[pos])
471                                        || mechlist[pos] == '_'
472                                        || mechlist[pos] == '-'))
473                     pos++;
474             }
475         }
476         pos++;
477         name[place]=0;
478
479         if (! place) continue;
480
481         /* foreach in client list */
482         for (m = cmechlist->mech_list; m != NULL; m = m->next) {
483             int myflags, plus;
484
485             if (!_sasl_is_equal_mech(name, m->m.plug->mech_name, &plus))
486                 continue;
487
488             /* Do we have the prompts for it? */
489             if (!have_prompts(conn, m->m.plug))
490                 break;
491
492             /* Is it strong enough? */
493             if (minssf > m->m.plug->max_ssf)
494                 break;
495
496             /* Does it meet our security properties? */
497             myflags = conn->props.security_flags;
498             
499             /* if there's an external layer this is no longer plaintext */
500             if ((conn->props.min_ssf <= conn->external.ssf) && 
501                 (conn->external.ssf > 1)) {
502                 myflags &= ~SASL_SEC_NOPLAINTEXT;
503             }
504
505             if (((myflags ^ m->m.plug->security_flags) & myflags) != 0) {
506                 break;
507             }
508
509             /* Can we meet it's features? */
510             if ((m->m.plug->features & SASL_FEAT_NEEDSERVERFQDN)
511                 && !conn->serverFQDN) {
512                 break;
513             }
514
515             /* Can it meet our features? */
516             if ((conn->flags & SASL_NEED_PROXY) &&
517                 !(m->m.plug->features & SASL_FEAT_ALLOWS_PROXY)) {
518                 break;
519             }
520
521 #ifdef PREFER_MECH
522             if (strcasecmp(m->m.plug->mech_name, PREFER_MECH) &&
523                 bestm && m->m.plug->max_ssf <= bestssf) {
524                 /* this mechanism isn't our favorite, and it's no better
525                    than what we already have! */
526                 break;
527             }
528 #else
529             if (bestm && m->m.plug->max_ssf <= bestssf) {
530                 /* this mechanism is no better than what we already have! */
531                 break;
532             }
533 #endif
534
535             /* compare security flags, only take new mechanism if it has
536              * all the security flags of the previous one.
537              *
538              * From the mechanisms we ship with, this yields the order:
539              *
540              * SRP
541              * GSSAPI + KERBEROS_V4
542              * DIGEST + OTP
543              * CRAM + EXTERNAL
544              * PLAIN + LOGIN + ANONYMOUS
545              *
546              * This might be improved on by comparing the numeric value of
547              * the bitwise-or'd security flags, which splits DIGEST/OTP,
548              * CRAM/EXTERNAL, and PLAIN/LOGIN from ANONYMOUS, but then we
549              * are depending on the numeric values of the flags (which may
550              * change, and their ordering could be considered dumb luck.
551              */
552
553             if (bestm &&
554                 ((m->m.plug->security_flags ^ bestm->m.plug->security_flags) &
555                  bestm->m.plug->security_flags)) {
556                 break;
557             }
558
559             if (SASL_CB_PRESENT(c_conn->cparams)) {
560                 if (plus)
561                     c_conn->cparams->chanbindingflag = SASL_CB_FLAG_USED;
562                 else
563                     c_conn->cparams->chanbindingflag = SASL_CB_FLAG_WANT;
564             }
565
566             if (mech) {
567                 *mech = m->m.plug->mech_name;
568             }
569             bestssf = m->m.plug->max_ssf;
570             bestm = m;
571             break;
572         }
573     }
574
575     if (bestm == NULL) {
576         sasl_seterror(conn, 0, "No worthy mechs found");
577         result = SASL_NOMECH;
578         goto done;
579     }
580
581     /* make (the rest of) cparams */
582     c_conn->cparams->service = conn->service;
583     c_conn->cparams->servicelen = (unsigned) strlen(conn->service);
584     
585     if (conn->serverFQDN) {
586         c_conn->cparams->serverFQDN = conn->serverFQDN; 
587         c_conn->cparams->slen = (unsigned) strlen(conn->serverFQDN);
588     }
589
590     c_conn->cparams->clientFQDN = c_conn->clientFQDN; 
591     c_conn->cparams->clen = (unsigned) strlen(c_conn->clientFQDN);
592
593     c_conn->cparams->external_ssf = conn->external.ssf;
594     c_conn->cparams->props = conn->props;
595     c_conn->mech = bestm;
596
597     /* init that plugin */
598     result = c_conn->mech->m.plug->mech_new(c_conn->mech->m.plug->glob_context,
599                                           c_conn->cparams,
600                                           &(conn->context));
601     if(result != SASL_OK) goto done;
602
603     /* do a step -- but only if we can do a client-send-first */
604  dostep:
605     if(clientout) {
606         if(c_conn->mech->m.plug->features & SASL_FEAT_SERVER_FIRST) {
607             *clientout = NULL;
608             *clientoutlen = 0;
609             result = SASL_CONTINUE;
610         } else {
611             result = sasl_client_step(conn, NULL, 0, prompt_need,
612                                       clientout, clientoutlen);
613         }
614     }
615     else
616         result = SASL_CONTINUE;
617
618  done:
619     RETURN(conn, result);
620 }
621
622 /* do a single authentication step.
623  *  serverin    -- the server message received by the client, MUST have a NUL
624  *                 sentinel, not counted by serverinlen
625  * output:
626  *  prompt_need -- on SASL_INTERACT, list of prompts needed to continue
627  *  clientout   -- the client response to send to the server
628  *
629  * returns:
630  *  SASL_OK        -- success
631  *  SASL_INTERACT  -- user interaction needed to fill in prompt_need list
632  *  SASL_BADPROT   -- server protocol incorrect/cancelled
633  *  SASL_BADSERV   -- server failed mutual auth
634  */
635
636 int sasl_client_step(sasl_conn_t *conn,
637                      const char *serverin,
638                      unsigned serverinlen,
639                      sasl_interact_t **prompt_need,
640                      const char **clientout,
641                      unsigned *clientoutlen)
642 {
643   sasl_client_conn_t *c_conn= (sasl_client_conn_t *) conn;
644   int result;
645
646   if(_sasl_client_active==0) return SASL_NOTINIT;
647   if(!conn) return SASL_BADPARAM;
648
649   /* check parameters */
650   if ((serverin==NULL) && (serverinlen>0))
651       PARAMERROR(conn);
652
653   /* Don't do another step if the plugin told us that we're done */
654   if (conn->oparams.doneflag) {
655       _sasl_log(conn, SASL_LOG_ERR, "attempting client step after doneflag");
656       return SASL_FAIL;
657   }
658
659   if(clientout) *clientout = NULL;
660   if(clientoutlen) *clientoutlen = 0;
661
662   /* do a step */
663   result = c_conn->mech->m.plug->mech_step(conn->context,
664                                          c_conn->cparams,
665                                          serverin,
666                                          serverinlen,
667                                          prompt_need,
668                                          clientout, clientoutlen,
669                                          &conn->oparams);
670
671   if (result == SASL_OK) {
672       /* So we're done on this end, but if both
673        * 1. the mech does server-send-last
674        * 2. the protocol does not
675        * we need to return no data */
676       if(!*clientout && !(conn->flags & SASL_SUCCESS_DATA)) {
677           *clientout = "";
678           *clientoutlen = 0;
679       }
680       
681       if(!conn->oparams.maxoutbuf) {
682           conn->oparams.maxoutbuf = conn->props.maxbufsize;
683       }
684
685       if(conn->oparams.user == NULL || conn->oparams.authid == NULL) {
686           sasl_seterror(conn, 0,
687                         "mech did not call canon_user for both authzid and authid");
688           result = SASL_BADPROT;
689       }
690   }  
691
692   RETURN(conn,result);
693 }
694
695 /* returns the length of all the mechanisms
696  * added up 
697  */
698
699 static unsigned mech_names_len()
700 {
701   cmechanism_t *listptr;
702   unsigned result = 0;
703
704   for (listptr = cmechlist->mech_list;
705        listptr;
706        listptr = listptr->next)
707     result += (unsigned) strlen(listptr->m.plug->mech_name);
708
709   return result;
710 }
711
712
713 int _sasl_client_listmech(sasl_conn_t *conn,
714                           const char *prefix,
715                           const char *sep,
716                           const char *suffix,
717                           const char **result,
718                           unsigned *plen,
719                           int *pcount)
720 {
721     cmechanism_t *m=NULL;
722     sasl_ssf_t minssf = 0;
723     int ret;
724     size_t resultlen;
725     int flag;
726     const char *mysep;
727
728     if(_sasl_client_active == 0) return SASL_NOTINIT;
729     if (!conn) return SASL_BADPARAM;
730     if(conn->type != SASL_CONN_CLIENT) PARAMERROR(conn);
731     
732     if (! result)
733         PARAMERROR(conn);
734     
735     if (plen != NULL)
736         *plen = 0;
737     if (pcount != NULL)
738         *pcount = 0;
739
740     if (sep) {
741         mysep = sep;
742     } else {
743         mysep = " ";
744     }
745
746     if(conn->props.min_ssf < conn->external.ssf) {
747         minssf = 0;
748     } else {
749         minssf = conn->props.min_ssf - conn->external.ssf;
750     }
751
752     if (! cmechlist || cmechlist->mech_length <= 0)
753         INTERROR(conn, SASL_NOMECH);
754
755     resultlen = (prefix ? strlen(prefix) : 0)
756         + (strlen(mysep) * (cmechlist->mech_length - 1))
757         + mech_names_len()
758         + (suffix ? strlen(suffix) : 0)
759         + 1;
760     ret = _buf_alloc(&conn->mechlist_buf,
761                      &conn->mechlist_buf_len, resultlen);
762     if(ret != SASL_OK) MEMERROR(conn);
763
764     if (prefix)
765         strcpy (conn->mechlist_buf,prefix);
766     else
767         *(conn->mechlist_buf) = '\0';
768
769     flag = 0;
770     for (m = cmechlist->mech_list; m != NULL; m = m->next) {
771             /* do we have the prompts for it? */
772             if (!have_prompts(conn, m->m.plug))
773                 continue;
774
775             /* is it strong enough? */
776             if (minssf > m->m.plug->max_ssf)
777                 continue;
778
779             /* does it meet our security properties? */
780             if (((conn->props.security_flags ^ m->m.plug->security_flags)
781                  & conn->props.security_flags) != 0) {
782                 continue;
783             }
784
785             /* Can we meet it's features? */
786             if ((m->m.plug->features & SASL_FEAT_NEEDSERVERFQDN)
787                 && !conn->serverFQDN) {
788                 continue;
789             }
790
791             /* Can it meet our features? */
792             if ((conn->flags & SASL_NEED_PROXY) &&
793                 !(m->m.plug->features & SASL_FEAT_ALLOWS_PROXY)) {
794                 continue;
795             }
796
797             /* Okay, we like it, add it to the list! */
798
799             if (pcount != NULL)
800                 (*pcount)++;
801
802             /* print seperator */
803             if (flag) {
804                 strcat(conn->mechlist_buf, mysep);
805             } else {
806                 flag = 1;
807             }
808             
809             /* now print the mechanism name */
810             strcat(conn->mechlist_buf, m->m.plug->mech_name);
811     }
812     
813   if (suffix)
814       strcat(conn->mechlist_buf,suffix);
815
816   if (plen!=NULL)
817       *plen = (unsigned) strlen(conn->mechlist_buf);
818
819   *result = conn->mechlist_buf;
820
821   return SASL_OK;
822 }
823
824 sasl_string_list_t *_sasl_client_mechs(void) 
825 {
826   cmechanism_t *listptr;
827   sasl_string_list_t *retval = NULL, *next=NULL;
828
829   if(!_sasl_client_active) return NULL;
830
831   /* make list */
832   for (listptr = cmechlist->mech_list; listptr; listptr = listptr->next) {
833       next = sasl_ALLOC(sizeof(sasl_string_list_t));
834
835       if(!next && !retval) return NULL;
836       else if(!next) {
837           next = retval->next;
838           do {
839               sasl_FREE(retval);
840               retval = next;
841               next = retval->next;
842           } while(next);
843           return NULL;
844       }
845       
846       next->d = listptr->m.plug->mech_name;
847
848       if(!retval) {
849           next->next = NULL;
850           retval = next;
851       } else {
852           next->next = retval;
853           retval = next;
854       }
855   }
856
857   return retval;
858 }
859
860
861
862
863 /* It would be nice if we can show other information like Author, Company, Year, plugin version */
864 static void
865 _sasl_print_mechanism (
866   client_sasl_mechanism_t *m,
867   sasl_info_callback_stage_t stage,
868   void *rock
869 )
870 {
871     char delimiter;
872
873     if (stage == SASL_INFO_LIST_START) {
874         printf ("List of client plugins follows\n");
875         return;
876     } else if (stage == SASL_INFO_LIST_END) {
877         return;
878     }
879
880     /* Process the mechanism */
881     printf ("Plugin \"%s\" ", m->plugname);
882
883     /* There is no delay loading for client side plugins */
884     printf ("[loaded]");
885
886     printf (", \tAPI version: %d\n", m->version);
887
888     if (m->plug != NULL) {
889         printf ("\tSASL mechanism: %s, best SSF: %d\n",
890                 m->plug->mech_name,
891                 m->plug->max_ssf);
892
893         printf ("\tsecurity flags:");
894         
895         delimiter = ' ';
896         if (m->plug->security_flags & SASL_SEC_NOANONYMOUS) {
897             printf ("%cNO_ANONYMOUS", delimiter);
898             delimiter = '|';
899         }
900
901         if (m->plug->security_flags & SASL_SEC_NOPLAINTEXT) {
902             printf ("%cNO_PLAINTEXT", delimiter);
903             delimiter = '|';
904         }
905         
906         if (m->plug->security_flags & SASL_SEC_NOACTIVE) {
907             printf ("%cNO_ACTIVE", delimiter);
908             delimiter = '|';
909         }
910
911         if (m->plug->security_flags & SASL_SEC_NODICTIONARY) {
912             printf ("%cNO_DICTIONARY", delimiter);
913             delimiter = '|';
914         }
915
916         if (m->plug->security_flags & SASL_SEC_FORWARD_SECRECY) {
917             printf ("%cFORWARD_SECRECY", delimiter);
918             delimiter = '|';
919         }
920
921         if (m->plug->security_flags & SASL_SEC_PASS_CREDENTIALS) {
922             printf ("%cPASS_CREDENTIALS", delimiter);
923             delimiter = '|';
924         }
925
926         if (m->plug->security_flags & SASL_SEC_MUTUAL_AUTH) {
927             printf ("%cMUTUAL_AUTH", delimiter);
928             delimiter = '|';
929         }
930
931
932
933         printf ("\n\tfeatures:");
934         
935         delimiter = ' ';
936         if (m->plug->features & SASL_FEAT_WANT_CLIENT_FIRST) {
937             printf ("%cWANT_CLIENT_FIRST", delimiter);
938             delimiter = '|';
939         }
940
941         if (m->plug->features & SASL_FEAT_SERVER_FIRST) {
942             printf ("%cSERVER_FIRST", delimiter);
943             delimiter = '|';
944         }
945
946         if (m->plug->features & SASL_FEAT_ALLOWS_PROXY) {
947             printf ("%cPROXY_AUTHENTICATION", delimiter);
948             delimiter = '|';
949         }
950
951         if (m->plug->features & SASL_FEAT_NEEDSERVERFQDN) {
952             printf ("%cNEED_SERVER_FQDN", delimiter);
953             delimiter = '|';
954         }
955
956         if (m->plug->features & SASL_FEAT_GSS_FRAMING) {
957             printf ("%cGSS_FRAMING", delimiter);
958             delimiter = '|';
959         }
960
961         if (m->plug->features & SASL_FEAT_CHANNEL_BINDING) {
962             printf ("%cCHANNEL_BINDING", delimiter);
963             delimiter = '|';
964         }
965     }
966
967 /* Delay loading is not supported for the client side plugins:
968     if (m->f) {
969         printf ("\n\twill be loaded from \"%s\"", m->f);
970     }
971  */
972
973     printf ("\n");
974 }
975
976
977 /* Dump information about available client plugins */
978 int sasl_client_plugin_info (
979   const char *c_mech_list,              /* space separated mechanism list or NULL for ALL */
980   sasl_client_info_callback_t *info_cb,
981   void *info_cb_rock
982 )
983 {
984     cmechanism_t *m;
985     client_sasl_mechanism_t plug_data;
986     char * cur_mech;
987     char * mech_list = NULL;
988     char * p;
989
990     if (info_cb == NULL) {
991         info_cb = _sasl_print_mechanism;
992     }
993
994     if (cmechlist != NULL) {
995         info_cb (NULL, SASL_INFO_LIST_START, info_cb_rock);
996
997         if (c_mech_list == NULL) {
998             m = cmechlist->mech_list; /* m point to beginning of the list */
999
1000             while (m != NULL) {
1001                 memcpy (&plug_data, &m->m, sizeof(plug_data));
1002
1003                 info_cb (&plug_data, SASL_INFO_LIST_MECH, info_cb_rock);
1004             
1005                 m = m->next;
1006             }
1007         } else {
1008             mech_list = strdup (c_mech_list);
1009
1010             cur_mech = mech_list;
1011
1012             while (cur_mech != NULL) {
1013                 p = strchr (cur_mech, ' ');
1014                 if (p != NULL) {
1015                     *p = '\0';
1016                     p++;
1017                 }
1018
1019                 m = cmechlist->mech_list; /* m point to beginning of the list */
1020
1021                 while (m != NULL) {
1022                     if (strcasecmp (cur_mech, m->m.plug->mech_name) == 0) {
1023                         memcpy (&plug_data, &m->m, sizeof(plug_data));
1024
1025                         info_cb (&plug_data, SASL_INFO_LIST_MECH, info_cb_rock);
1026                     }
1027             
1028                     m = m->next;
1029                 }
1030
1031                 cur_mech = p;
1032             }
1033
1034             free (mech_list);
1035         }
1036
1037         info_cb (NULL, SASL_INFO_LIST_END, info_cb_rock);
1038
1039         return (SASL_OK);
1040     }
1041
1042     return (SASL_NOTINIT);
1043 }