import cyrus-sasl-2.1.23
[cyrus-sasl.git] / lib / common.c
1 /* common.c - Functions that are common to server and clinet
2  * Rob Siemborski
3  * Tim Martin
4  * $Id: common.c,v 1.114 2006/04/19 18:39:59 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 <string.h>
49 #include <stdlib.h>
50 #include <limits.h>
51 #ifdef HAVE_SYSLOG
52 #include <syslog.h>
53 #endif
54 #include <stdarg.h>
55 #include <ctype.h>
56 #include <assert.h>
57
58 #include <sasl.h>
59 #include <saslutil.h>
60 #include <saslplug.h>
61 #include "saslint.h"
62
63 #ifdef HAVE_UNISTD_H
64 #include <unistd.h>
65 #endif
66
67 static const char *implementation_string = "Cyrus SASL";
68
69 #define VSTR0(maj, min, step)   #maj "." #min "." #step
70 #define VSTR(maj, min, step)    VSTR0(maj, min, step)
71 #define SASL_VERSION_STRING     VSTR(SASL_VERSION_MAJOR, SASL_VERSION_MINOR, \
72                                 SASL_VERSION_STEP)
73
74 static int _sasl_getpath(void *context __attribute__((unused)), const char **path);
75 static int _sasl_getpath_simple(void *context __attribute__((unused)), const char **path);
76 static int _sasl_getconfpath(void *context __attribute__((unused)), char ** path);
77 static int _sasl_getconfpath_simple(void *context __attribute__((unused)), const char **path);
78
79 #if !defined(WIN32)
80 static char * _sasl_get_default_unix_path(void *context __attribute__((unused)),
81                             char * env_var_name, char * default_value);
82 #else
83 /* NB: Always returned allocated value */
84 static char * _sasl_get_default_win_path(void *context __attribute__((unused)),
85                             char * reg_attr_name, char * default_value);
86 #endif
87
88
89 static const char build_ident[] = "$Build: libsasl " PACKAGE "-" VERSION " $";
90
91 /* It turns out to be convenient to have a shared sasl_utils_t */
92 LIBSASL_VAR const sasl_utils_t *sasl_global_utils = NULL;
93
94 /* Should be a null-terminated array that lists the available mechanisms */
95 static char **global_mech_list = NULL;
96
97 void *free_mutex = NULL;
98
99 int (*_sasl_client_cleanup_hook)(void) = NULL;
100 int (*_sasl_server_cleanup_hook)(void) = NULL;
101 int (*_sasl_client_idle_hook)(sasl_conn_t *conn) = NULL;
102 int (*_sasl_server_idle_hook)(sasl_conn_t *conn) = NULL;
103
104 sasl_allocation_utils_t _sasl_allocation_utils={
105   (sasl_malloc_t *)  &malloc,
106   (sasl_calloc_t *)  &calloc,
107   (sasl_realloc_t *) &realloc,
108   (sasl_free_t *) &free
109 };
110
111 #define SASL_ENCODEV_EXTRA  4096
112
113 /* Default getpath/getconfpath callbacks. These can be edited by sasl_set_path(). */
114 static sasl_callback_t default_getpath_cb = {
115     SASL_CB_GETPATH, &_sasl_getpath, NULL
116 };
117 static sasl_callback_t default_getconfpath_cb = {
118     SASL_CB_GETCONFPATH, &_sasl_getconfpath, NULL
119 };
120
121 static char * default_plugin_path = NULL;
122 static char * default_conf_path = NULL;
123
124 /* Intenal mutex functions do as little as possible (no thread protection) */
125 static void *sasl_mutex_alloc(void)
126 {
127   return (void *)0x1;
128 }
129
130 static int sasl_mutex_lock(void *mutex __attribute__((unused)))
131 {
132     return SASL_OK;
133 }
134
135 static int sasl_mutex_unlock(void *mutex __attribute__((unused)))
136 {
137     return SASL_OK;
138 }
139
140 static void sasl_mutex_free(void *mutex __attribute__((unused)))
141 {
142     return;
143 }
144
145 sasl_mutex_utils_t _sasl_mutex_utils={
146   &sasl_mutex_alloc,
147   &sasl_mutex_lock,
148   &sasl_mutex_unlock,
149   &sasl_mutex_free
150 };
151
152 void sasl_set_mutex(sasl_mutex_alloc_t *n, sasl_mutex_lock_t *l,
153                     sasl_mutex_unlock_t *u, sasl_mutex_free_t *d)
154 {
155   _sasl_mutex_utils.alloc=n;
156   _sasl_mutex_utils.lock=l;
157   _sasl_mutex_utils.unlock=u;
158   _sasl_mutex_utils.free=d;
159 }
160
161 /* copy a string to malloced memory */
162 int _sasl_strdup(const char *in, char **out, size_t *outlen)
163 {
164   size_t len = strlen(in);
165   if (outlen) *outlen = len;
166   *out=sasl_ALLOC((unsigned) len + 1);
167   if (! *out) return SASL_NOMEM;
168   strcpy((char *) *out, in);
169   return SASL_OK;
170 }
171
172 /* adds a string to the buffer; reallocing if need be */
173 int _sasl_add_string(char **out, size_t *alloclen,
174                      size_t *outlen, const char *add)
175 {
176   size_t addlen;
177
178   if (add==NULL) add = "(null)";
179
180   addlen=strlen(add); /* only compute once */
181   if (_buf_alloc(out, alloclen, (*outlen)+addlen)!=SASL_OK)
182     return SASL_NOMEM;
183
184   strncpy(*out + *outlen, add, addlen);
185   *outlen += addlen;
186
187   return SASL_OK;
188 }
189
190 /* a simpler way to set plugin path or configuration file path
191  * without the need to set sasl_getpath_t callback.
192  *
193  * This function can be called before sasl_server_init/sasl_client_init.
194  *
195  * Don't call this function without locking in a multithreaded application.
196  */  
197 int sasl_set_path (int path_type, char * path)
198 {
199     int result;
200
201     if (path == NULL) {
202         return (SASL_FAIL);
203     }
204
205     switch (path_type) {
206         case SASL_PATH_TYPE_PLUGIN:
207             if (default_plugin_path != NULL) {
208                 sasl_FREE (default_plugin_path);
209                 default_plugin_path = NULL;
210             }
211             result = _sasl_strdup (path, &default_plugin_path, NULL);
212             if (result != SASL_OK) {
213                 return (result);
214             }
215
216             /* Update the default getpath_t callback */
217             default_getpath_cb.proc = (int (*)()) &_sasl_getpath_simple;
218             break;
219
220         case SASL_PATH_TYPE_CONFIG:
221             if (default_conf_path != NULL) {
222                 sasl_FREE (default_conf_path);
223                 default_conf_path = NULL;
224             }
225             result = _sasl_strdup (path, &default_conf_path, NULL);
226             if (result != SASL_OK) {
227                 return (result);
228             }
229
230             /* Update the default getpath_t callback */
231             default_getconfpath_cb.proc = (int (*)()) &_sasl_getconfpath_simple;
232             break;
233
234         default:
235             return (SASL_FAIL);
236     }
237
238     return (SASL_OK);
239 }
240
241 /* return the version of the cyrus sasl library as compiled,
242  * using 32 bits: high byte is major version, second byte is minor version,
243  * low 16 bits are step # */
244 void sasl_version(const char **implementation, int *version) 
245 {
246     if(implementation) *implementation = implementation_string;
247     /* NB: the format is not the same as in SASL_VERSION_FULL */
248     if(version) *version = (SASL_VERSION_MAJOR << 24) | 
249                            (SASL_VERSION_MINOR << 16) |
250                            (SASL_VERSION_STEP);
251 }
252
253 /* Extended version of sasl_version above */
254 void sasl_version_info (const char **implementation, const char **version_string,
255                     int *version_major, int *version_minor, int *version_step,
256                     int *version_patch)
257 {
258     if (implementation) *implementation = implementation_string;
259     if (version_string) *version_string = SASL_VERSION_STRING;
260     if (version_major) *version_major = SASL_VERSION_MAJOR;
261     if (version_minor) *version_minor = SASL_VERSION_MINOR;
262     if (version_step) *version_step = SASL_VERSION_STEP;
263     /* Version patch is always 0 for CMU SASL */
264     if (version_patch) *version_patch = 0;
265 }
266
267 /* security-encode a regular string.  Mostly a wrapper for sasl_encodev */
268 /* output is only valid until next call to sasl_encode or sasl_encodev */
269 int sasl_encode(sasl_conn_t *conn, const char *input,
270                 unsigned inputlen,
271                 const char **output, unsigned *outputlen)
272 {
273     int result;
274     struct iovec tmp;
275
276     if(!conn) return SASL_BADPARAM;
277     if(!input || !inputlen || !output || !outputlen)
278         PARAMERROR(conn);
279     
280     /* maxoutbuf checking is done in sasl_encodev */
281
282     /* Note: We are casting a const pointer here, but it's okay
283      * because we believe people downstream of us are well-behaved, and the
284      * alternative is an absolute mess, performance-wise. */
285     tmp.iov_base = (void *)input;
286     tmp.iov_len = inputlen;
287     
288     result = sasl_encodev(conn, &tmp, 1, output, outputlen);
289
290     RETURN(conn, result);
291 }
292
293 /* Internal function that doesn't do any verification */
294 static int
295 _sasl_encodev (sasl_conn_t *conn,
296                const struct iovec *invec,
297                unsigned numiov,
298                int * p_num_packets,     /* number of packets generated so far */
299                const char **output,     /* previous output, if *p_num_packets > 0 */
300                unsigned *outputlen)
301 {
302     int result;
303     char * new_buf;
304
305     assert (conn->oparams.encode != NULL);
306
307     if (*p_num_packets == 1) {
308         /* This is the second call to this function,
309            so we need to allocate a new output buffer
310            and copy existing data there. */
311         conn->multipacket_encoded_data.curlen = *outputlen;
312         if (conn->multipacket_encoded_data.data == NULL) {
313             conn->multipacket_encoded_data.reallen = 
314                  conn->multipacket_encoded_data.curlen + SASL_ENCODEV_EXTRA;
315             conn->multipacket_encoded_data.data =
316                  sasl_ALLOC(conn->multipacket_encoded_data.reallen + 1);
317
318             if (conn->multipacket_encoded_data.data == NULL) {
319                 MEMERROR(conn);
320             }
321         } else {
322             /* A buffer left from a previous sasl_encodev call.
323                Make sure it is big enough. */
324             if (conn->multipacket_encoded_data.curlen >
325                 conn->multipacket_encoded_data.reallen) {
326                 conn->multipacket_encoded_data.reallen = 
327                     conn->multipacket_encoded_data.curlen + SASL_ENCODEV_EXTRA;
328
329                 new_buf = sasl_REALLOC(conn->multipacket_encoded_data.data,
330                             conn->multipacket_encoded_data.reallen + 1);
331                 if (new_buf == NULL) {
332                     MEMERROR(conn);
333                 }
334                 conn->multipacket_encoded_data.data = new_buf;
335             }
336         }
337
338         memcpy (conn->multipacket_encoded_data.data,
339                 *output,
340                 *outputlen);
341     }
342
343     result = conn->oparams.encode(conn->context,
344                                   invec,
345                                   numiov,
346                                   output,
347                                   outputlen);
348
349     if (*p_num_packets > 0 && result == SASL_OK) {
350         /* Is the allocated buffer big enough? If not, grow it. */
351         if ((conn->multipacket_encoded_data.curlen + *outputlen) >
352              conn->multipacket_encoded_data.reallen) {
353             conn->multipacket_encoded_data.reallen =
354                 conn->multipacket_encoded_data.curlen + *outputlen;
355             new_buf = sasl_REALLOC(conn->multipacket_encoded_data.data,
356                         conn->multipacket_encoded_data.reallen + 1);
357             if (new_buf == NULL) {
358                 MEMERROR(conn);
359             }
360             conn->multipacket_encoded_data.data = new_buf;
361         }
362
363         /* Append new data to the end of the buffer */
364         memcpy (conn->multipacket_encoded_data.data +
365                 conn->multipacket_encoded_data.curlen,
366                 *output,
367                 *outputlen);
368         conn->multipacket_encoded_data.curlen += *outputlen;
369
370         *output = conn->multipacket_encoded_data.data;
371         *outputlen = conn->multipacket_encoded_data.curlen;
372     }
373
374     (*p_num_packets)++;
375
376     RETURN(conn, result);
377 }
378
379 /* security-encode an iovec */
380 /* output is only valid until the next call to sasl_encode or sasl_encodev */
381 int sasl_encodev(sasl_conn_t *conn,
382                  const struct iovec *invec,
383                  unsigned numiov,
384                  const char **output,
385                  unsigned *outputlen)
386 {
387     int result;
388     unsigned i;
389     unsigned j;
390     size_t total_size = 0;
391     struct iovec *cur_invec = NULL;
392     struct iovec last_invec;
393     unsigned cur_numiov;
394     char * next_buf = NULL;
395     unsigned remainder_len;
396     unsigned index_offset;
397     unsigned allocated = 0;
398     /* Number of generated SASL packets */
399     int num_packets = 0;
400
401     if (!conn) return SASL_BADPARAM;
402     if (! invec || ! output || ! outputlen || numiov < 1) {
403         PARAMERROR(conn);
404     }
405
406     if (!conn->props.maxbufsize) {
407         sasl_seterror(conn, 0,
408                       "called sasl_encode[v] with application that does not support security layers");
409         return SASL_TOOWEAK;
410     }
411
412     /* If oparams.encode is NULL, this means there is no SASL security
413        layer in effect, so no SASL framing is needed. */
414     if (conn->oparams.encode == NULL)  {
415         result = _iovec_to_buf(invec, numiov, &conn->encode_buf);
416         if (result != SASL_OK) INTERROR(conn, result);
417        
418         *output = conn->encode_buf->data;
419         *outputlen = (unsigned) conn->encode_buf->curlen;
420
421         RETURN(conn, result);
422     }
423
424     /* This might be better to check on a per-plugin basis, but I think
425      * it's cleaner and more effective here.  It also encourages plugins
426      * to be honest about what they accept */
427
428     last_invec.iov_base = NULL;
429     remainder_len = 0;
430     next_buf = NULL;
431     i = 0;
432     while (i < numiov) {
433         if ((total_size + invec[i].iov_len) > conn->oparams.maxoutbuf) {
434
435             /* CLAIM: total_size < conn->oparams.maxoutbuf */
436             
437             /* Fit as many bytes in last_invec, so that we have conn->oparams.maxoutbuf
438                bytes in total. */
439             last_invec.iov_len = conn->oparams.maxoutbuf - total_size;
440             /* Point to the first byte of the current record. */
441             last_invec.iov_base = invec[i].iov_base;
442
443             /* Note that total_size < conn->oparams.maxoutbuf */
444             /* The total size of the iov is bigger then the other end can accept.
445                So we allocate a new iov that contains just enough. */
446
447             /* +1 --- for the tail record */
448             cur_numiov = i + 1;
449
450             /* +1 --- just in case we need the head record */
451             if ((cur_numiov + 1) > allocated) {
452                 struct iovec *new_invec;
453
454                 allocated = cur_numiov + 1;
455                 new_invec = sasl_REALLOC (cur_invec, sizeof(struct iovec) * allocated);
456                 if (new_invec == NULL) {
457                     if (cur_invec != NULL) {
458                         sasl_FREE(cur_invec);
459                     }
460                     MEMERROR(conn);
461                 }
462                 cur_invec = new_invec;
463             }
464
465             if (next_buf != NULL) {
466                 cur_invec[0].iov_base = next_buf;
467                 cur_invec[0].iov_len = remainder_len;
468                 cur_numiov++;
469                 index_offset = 1;
470             } else {
471                 index_offset = 0;
472             }
473
474             if (i > 0) {
475                 /* Copy all previous chunks */
476                 /* NOTE - The starting index in invec is always 0 */
477                 for (j = 0; j < i; j++) {
478                     cur_invec[j + index_offset] = invec[j];
479                 }
480             }
481
482             /* Initialize the last record */
483             cur_invec[i + index_offset] = last_invec;
484
485             result = _sasl_encodev (conn,
486                                     cur_invec,
487                                     cur_numiov,
488                                     &num_packets,
489                                     output,
490                                     outputlen);
491
492             if (result != SASL_OK) {
493                 goto cleanup;
494             }
495
496             /* Point to the first byte that wouldn't fit into
497                the conn->oparams.maxoutbuf buffer. */
498             /* Note, if next_buf points to the very end of the IOV record,
499                it will be reset to NULL below */
500             next_buf = last_invec.iov_base + last_invec.iov_len;
501             /* Note - remainder_len is how many bytes left to be encoded in
502                the current IOV slot. */
503             remainder_len = (total_size + invec[i].iov_len) - conn->oparams.maxoutbuf;
504
505             /* Skip all consumed IOV records */
506             invec += i + 1;
507             numiov = numiov - (i + 1);
508             i = 0;
509
510             while (remainder_len > conn->oparams.maxoutbuf) {
511                 last_invec.iov_base = next_buf;
512                 last_invec.iov_len = conn->oparams.maxoutbuf;
513
514                 /* Note, if next_buf points to the very end of the IOV record,
515                    it will be reset to NULL below */
516                 next_buf = last_invec.iov_base + last_invec.iov_len;
517                 remainder_len = remainder_len - conn->oparams.maxoutbuf;
518
519                 result = _sasl_encodev (conn,
520                                         &last_invec,
521                                         1,
522                                         &num_packets,
523                                         output,
524                                         outputlen);
525                 if (result != SASL_OK) {
526                     goto cleanup;
527                 }
528             }
529
530             total_size = remainder_len;
531
532             if (remainder_len == 0) {
533                 /* Just clear next_buf */
534                 next_buf = NULL;
535             }
536         } else {
537             total_size += invec[i].iov_len;
538             i++;
539         }
540     }
541
542     /* CLAIM - The remaining data is shorter then conn->oparams.maxoutbuf. */
543
544     /* Force encoding of any partial buffer. Might not be optimal on the wire. */
545     if (next_buf != NULL) {
546         last_invec.iov_base = next_buf;
547         last_invec.iov_len = remainder_len;
548
549         result = _sasl_encodev (conn,
550                                 &last_invec,
551                                 1,
552                                 &num_packets,
553                                 output,
554                                 outputlen);
555
556         if (result != SASL_OK) {
557             goto cleanup;
558         }
559     }
560
561     if (numiov > 0) {
562         result = _sasl_encodev (conn,
563                                 invec,
564                                 numiov,
565                                 &num_packets,
566                                 output,
567                                 outputlen);
568     }
569
570 cleanup:
571     if (cur_invec != NULL) {
572         sasl_FREE(cur_invec);
573     }
574
575     RETURN(conn, result);
576 }
577  
578 /* output is only valid until next call to sasl_decode */
579 int sasl_decode(sasl_conn_t *conn,
580                 const char *input, unsigned inputlen,
581                 const char **output, unsigned *outputlen)
582 {
583     int result;
584
585     if(!conn) return SASL_BADPARAM;
586     if(!input || !output || !outputlen)
587         PARAMERROR(conn);
588
589     if(!conn->props.maxbufsize) {
590         sasl_seterror(conn, 0,
591                       "called sasl_decode with application that does not support security layers");
592         RETURN(conn, SASL_TOOWEAK);
593     }
594
595     if(conn->oparams.decode == NULL)
596     {
597         /* Since we know how long the output is maximally, we can
598          * just allocate it to begin with, and never need another
599          * allocation! */
600
601         /* However, if they pass us more than they actually can take,
602          * we cannot help them... */
603         if(inputlen > conn->props.maxbufsize) {
604             sasl_seterror(conn, 0,
605                           "input too large for default sasl_decode");
606             RETURN(conn,SASL_BUFOVER);
607         }
608
609         if(!conn->decode_buf)
610             conn->decode_buf = sasl_ALLOC(conn->props.maxbufsize + 1);
611         if(!conn->decode_buf)   
612             MEMERROR(conn);
613         
614         memcpy(conn->decode_buf, input, inputlen);
615         conn->decode_buf[inputlen] = '\0';
616         *output = conn->decode_buf;
617         *outputlen = inputlen;
618         
619         return SASL_OK;
620     } else {
621         result = conn->oparams.decode(conn->context, input, inputlen,
622                                       output, outputlen);
623
624         /* NULL an empty buffer (for misbehaved applications) */
625         if (*outputlen == 0) *output = NULL;
626
627         RETURN(conn, result);
628     }
629
630     INTERROR(conn, SASL_FAIL);
631 }
632
633
634 void
635 sasl_set_alloc(sasl_malloc_t *m,
636                sasl_calloc_t *c,
637                sasl_realloc_t *r,
638                sasl_free_t *f)
639 {
640   _sasl_allocation_utils.malloc=m;
641   _sasl_allocation_utils.calloc=c;
642   _sasl_allocation_utils.realloc=r;
643   _sasl_allocation_utils.free=f;
644 }
645
646 void sasl_done(void)
647 {
648     if (_sasl_server_cleanup_hook && _sasl_server_cleanup_hook() == SASL_OK) {
649         _sasl_server_idle_hook = NULL;
650         _sasl_server_cleanup_hook = NULL;
651     }
652     
653     if (_sasl_client_cleanup_hook && _sasl_client_cleanup_hook() == SASL_OK) {
654         _sasl_client_idle_hook = NULL;  
655         _sasl_client_cleanup_hook = NULL;
656     }
657     
658     if (_sasl_server_cleanup_hook || _sasl_client_cleanup_hook) {
659         return;
660     }
661
662     /* NOTE - the caller will need to reinitialize the values,
663        if it is going to call sasl_client_init/sasl_server_init again. */
664     if (default_plugin_path != NULL) {
665         sasl_FREE (default_plugin_path);
666         default_plugin_path = NULL;
667     }
668     if (default_conf_path != NULL) {
669         sasl_FREE (default_conf_path);
670         default_conf_path = NULL;
671     }
672
673     _sasl_canonuser_free();
674     _sasl_done_with_plugins();
675     
676     sasl_MUTEX_FREE(free_mutex);
677     free_mutex = NULL;
678     
679     _sasl_free_utils(&sasl_global_utils);
680     
681     if(global_mech_list) sasl_FREE(global_mech_list);
682     global_mech_list = NULL;
683 }
684
685 /* fills in the base sasl_conn_t info */
686 int _sasl_conn_init(sasl_conn_t *conn,
687                     const char *service,
688                     unsigned int flags,
689                     enum Sasl_conn_type type,
690                     int (*idle_hook)(sasl_conn_t *conn),
691                     const char *serverFQDN,
692                     const char *iplocalport,
693                     const char *ipremoteport,
694                     const sasl_callback_t *callbacks,
695                     const sasl_global_callbacks_t *global_callbacks) {
696   int result = SASL_OK;
697
698   conn->type = type;
699
700   result = _sasl_strdup(service, &conn->service, NULL);
701   if (result != SASL_OK) 
702       MEMERROR(conn);
703
704   memset(&conn->oparams, 0, sizeof(sasl_out_params_t));
705   memset(&conn->external, 0, sizeof(_sasl_external_properties_t));
706
707   conn->flags = flags;
708
709   result = sasl_setprop(conn, SASL_IPLOCALPORT, iplocalport);
710   if(result != SASL_OK)
711       RETURN(conn, result);
712   
713   result = sasl_setprop(conn, SASL_IPREMOTEPORT, ipremoteport);
714   if(result != SASL_OK)
715       RETURN(conn, result);
716   
717   conn->encode_buf = NULL;
718   conn->context = NULL;
719   conn->secret = NULL;
720   conn->idle_hook = idle_hook;
721   conn->callbacks = callbacks;
722   conn->global_callbacks = global_callbacks;
723
724   memset(&conn->props, 0, sizeof(conn->props));
725
726   /* Start this buffer out as an empty string */
727   conn->error_code = SASL_OK;
728   conn->errdetail_buf = conn->error_buf = NULL;
729   conn->errdetail_buf_len = conn->error_buf_len = 150;
730
731   result = _buf_alloc(&conn->error_buf, &conn->error_buf_len, 150);     
732   if(result != SASL_OK) MEMERROR(conn);
733   result = _buf_alloc(&conn->errdetail_buf, &conn->errdetail_buf_len, 150);
734   if(result != SASL_OK) MEMERROR(conn);
735   
736   conn->error_buf[0] = '\0';
737   conn->errdetail_buf[0] = '\0';
738   
739   conn->decode_buf = NULL;
740
741   if(serverFQDN) {
742       result = _sasl_strdup(serverFQDN, &conn->serverFQDN, NULL);
743   } else if (conn->type == SASL_CONN_SERVER) {
744       /* We can fake it because we *are* the server */
745       char name[MAXHOSTNAMELEN];
746       memset(name, 0, sizeof(name));
747       gethostname(name, MAXHOSTNAMELEN);
748       
749       result = _sasl_strdup(name, &conn->serverFQDN, NULL);
750   } else {
751       conn->serverFQDN = NULL;
752   }
753   
754
755   if(result != SASL_OK) MEMERROR( conn );
756
757   RETURN(conn, SASL_OK);
758 }
759
760 int _sasl_common_init(sasl_global_callbacks_t *global_callbacks)
761 {
762     int result;
763     
764     /* Setup the global utilities */
765     if(!sasl_global_utils) {
766         sasl_global_utils = _sasl_alloc_utils(NULL, global_callbacks);
767         if(sasl_global_utils == NULL) return SASL_NOMEM;
768     }
769
770     /* Init the canon_user plugin */
771     result = sasl_canonuser_add_plugin("INTERNAL", internal_canonuser_init);
772     if(result != SASL_OK) return result;    
773
774     if (!free_mutex)
775         free_mutex = sasl_MUTEX_ALLOC();
776     if (!free_mutex) return SASL_FAIL;
777
778     return SASL_OK;
779 }
780
781 /* dispose connection state, sets it to NULL
782  *  checks for pointer to NULL
783  */
784 void sasl_dispose(sasl_conn_t **pconn)
785 {
786   int result;
787
788   if (! pconn) return;
789   if (! *pconn) return;
790
791   /* serialize disposes. this is necessary because we can't
792      dispose of conn->mutex if someone else is locked on it */
793   result = sasl_MUTEX_LOCK(free_mutex);
794   if (result!=SASL_OK) return;
795   
796   /* *pconn might have become NULL by now */
797   if (! (*pconn)) return;
798
799   (*pconn)->destroy_conn(*pconn);
800   sasl_FREE(*pconn);
801   *pconn=NULL;
802
803   sasl_MUTEX_UNLOCK(free_mutex);
804 }
805
806 void _sasl_conn_dispose(sasl_conn_t *conn) {
807   if (conn->serverFQDN)
808       sasl_FREE(conn->serverFQDN);
809
810   if (conn->external.auth_id)
811       sasl_FREE(conn->external.auth_id);
812
813   if(conn->encode_buf) {
814       if(conn->encode_buf->data) sasl_FREE(conn->encode_buf->data);
815       sasl_FREE(conn->encode_buf);
816   }
817
818   if(conn->error_buf)
819       sasl_FREE(conn->error_buf);
820   
821   if(conn->errdetail_buf)
822       sasl_FREE(conn->errdetail_buf);
823
824   if(conn->decode_buf)
825       sasl_FREE(conn->decode_buf);
826
827   if(conn->mechlist_buf)
828       sasl_FREE(conn->mechlist_buf);
829
830   if(conn->service)
831       sasl_FREE(conn->service);
832
833   if (conn->multipacket_encoded_data.data) {
834       sasl_FREE(conn->multipacket_encoded_data.data);
835   }
836
837   /* oparams sub-members should be freed by the plugin, in so much
838    * as they were allocated by the plugin */
839 }
840
841
842 /* get property from SASL connection state
843  *  propnum       -- property number
844  *  pvalue        -- pointer to value
845  * returns:
846  *  SASL_OK       -- no error
847  *  SASL_NOTDONE  -- property not available yet
848  *  SASL_BADPARAM -- bad property number
849  */
850 int sasl_getprop(sasl_conn_t *conn, int propnum, const void **pvalue)
851 {
852   int result = SASL_OK;
853   sasl_getopt_t *getopt;
854   void *context;
855   
856   if (! conn) return SASL_BADPARAM;
857   if (! pvalue) PARAMERROR(conn);
858
859   switch(propnum)
860   {
861   case SASL_SSF:
862       *(sasl_ssf_t **)pvalue= &conn->oparams.mech_ssf;
863       break;      
864   case SASL_MAXOUTBUF:
865       *(unsigned **)pvalue = &conn->oparams.maxoutbuf;
866       break;
867   case SASL_GETOPTCTX:
868       result = _sasl_getcallback(conn, SASL_CB_GETOPT, &getopt, &context);
869       if(result != SASL_OK) break;
870       
871       *(void **)pvalue = context;
872       break;
873   case SASL_CALLBACK:
874       *(const sasl_callback_t **)pvalue = conn->callbacks;
875       break;
876   case SASL_IPLOCALPORT:
877       if(conn->got_ip_local)
878           *(const char **)pvalue = conn->iplocalport;
879       else {
880           *(const char **)pvalue = NULL;
881           result = SASL_NOTDONE;
882       }
883       break;
884   case SASL_IPREMOTEPORT:
885       if(conn->got_ip_remote)
886           *(const char **)pvalue = conn->ipremoteport;
887       else {
888           *(const char **)pvalue = NULL;
889           result = SASL_NOTDONE;
890       }   
891       break;
892   case SASL_USERNAME:
893       if(! conn->oparams.user)
894           result = SASL_NOTDONE;
895       else
896           *((const char **)pvalue) = conn->oparams.user;
897       break;
898   case SASL_AUTHUSER:
899       if(! conn->oparams.authid)
900           result = SASL_NOTDONE;
901       else
902           *((const char **)pvalue) = conn->oparams.authid;
903       break;
904   case SASL_APPNAME:
905       /* Currently we only support server side contexts, but we should
906          be able to extend this to support client side contexts as well */
907       if(conn->type != SASL_CONN_SERVER) result = SASL_BADPROT;
908       else
909           *((const char **)pvalue) = ((sasl_server_conn_t *)conn)->sparams->appname;
910       break;
911   case SASL_SERVERFQDN:
912       *((const char **)pvalue) = conn->serverFQDN;
913       break;
914   case SASL_DEFUSERREALM:
915       if(conn->type != SASL_CONN_SERVER) result = SASL_BADPROT;
916       else
917           *((const char **)pvalue) = ((sasl_server_conn_t *)conn)->user_realm;
918       break;
919   case SASL_SERVICE:
920       *((const char **)pvalue) = conn->service;
921       break;
922   case SASL_AUTHSOURCE: /* name of plugin (not name of mech) */
923       if(conn->type == SASL_CONN_CLIENT) {
924           if(!((sasl_client_conn_t *)conn)->mech) {
925               result = SASL_NOTDONE;
926               break;
927           }
928           *((const char **)pvalue) =
929               ((sasl_client_conn_t *)conn)->mech->m.plugname;
930       } else if (conn->type == SASL_CONN_SERVER) {
931           if(!((sasl_server_conn_t *)conn)->mech) {
932               result = SASL_NOTDONE;
933               break;
934           }
935           *((const char **)pvalue) =
936               ((sasl_server_conn_t *)conn)->mech->m.plugname;
937       } else {
938           result = SASL_BADPARAM;
939       }
940       break;
941   case SASL_MECHNAME: /* name of mech */
942       if(conn->type == SASL_CONN_CLIENT) {
943           if(!((sasl_client_conn_t *)conn)->mech) {
944               result = SASL_NOTDONE;
945               break;
946           }
947           *((const char **)pvalue) =
948               ((sasl_client_conn_t *)conn)->mech->m.plug->mech_name;
949       } else if (conn->type == SASL_CONN_SERVER) {
950           if(!((sasl_server_conn_t *)conn)->mech) {
951               result = SASL_NOTDONE;
952               break;
953           }
954           *((const char **)pvalue) =
955               ((sasl_server_conn_t *)conn)->mech->m.plug->mech_name;
956       } else {
957           result = SASL_BADPARAM;
958       }
959       
960       if(!(*pvalue) && result == SASL_OK) result = SASL_NOTDONE;
961       break;
962   case SASL_PLUGERR:
963       *((const char **)pvalue) = conn->error_buf;
964       break;
965   case SASL_DELEGATEDCREDS:
966       /* We can't really distinguish between "no delegated credentials"
967          and "authentication not finished" */
968       if(! conn->oparams.client_creds)
969           result = SASL_NOTDONE;
970       else
971           *((const char **)pvalue) = conn->oparams.client_creds;
972       break;
973   case SASL_SSF_EXTERNAL:
974       *((const sasl_ssf_t **)pvalue) = &conn->external.ssf;
975       break;
976   case SASL_AUTH_EXTERNAL:
977       *((const char **)pvalue) = conn->external.auth_id;
978       break;
979   case SASL_SEC_PROPS:
980       *((const sasl_security_properties_t **)pvalue) = &conn->props;
981       break;
982   default: 
983       result = SASL_BADPARAM;
984   }
985
986   if(result == SASL_BADPARAM) {
987       PARAMERROR(conn);
988   } else if(result == SASL_NOTDONE) {
989       sasl_seterror(conn, SASL_NOLOG,
990                     "Information that was requested is not yet available.");
991       RETURN(conn, result);
992   } else if(result != SASL_OK) {
993       INTERROR(conn, result);
994   } else
995       RETURN(conn, result); 
996 }
997
998 /* set property in SASL connection state
999  * returns:
1000  *  SASL_OK       -- value set
1001  *  SASL_BADPARAM -- invalid property or value
1002  */
1003 int sasl_setprop(sasl_conn_t *conn, int propnum, const void *value)
1004 {
1005   int result = SASL_OK;
1006   char *str;
1007
1008   /* make sure the sasl context is valid */
1009   if (!conn)
1010     return SASL_BADPARAM;
1011
1012   switch(propnum)
1013   {
1014   case SASL_SSF_EXTERNAL:
1015       conn->external.ssf = *((sasl_ssf_t *)value);
1016       if(conn->type == SASL_CONN_SERVER) {
1017         ((sasl_server_conn_t*)conn)->sparams->external_ssf =
1018           conn->external.ssf;
1019       } else {
1020         ((sasl_client_conn_t*)conn)->cparams->external_ssf =
1021           conn->external.ssf;
1022       }
1023       break;
1024
1025   case SASL_AUTH_EXTERNAL:
1026       if(value && strlen(value)) {
1027           result = _sasl_strdup(value, &str, NULL);
1028           if(result != SASL_OK) MEMERROR(conn);
1029       } else {
1030           str = NULL;
1031       }
1032
1033       if(conn->external.auth_id)
1034           sasl_FREE(conn->external.auth_id);
1035
1036       conn->external.auth_id = str;
1037
1038       break;
1039
1040   case SASL_DEFUSERREALM:
1041       if(conn->type != SASL_CONN_SERVER) {
1042         sasl_seterror(conn, 0, "Tried to set realm on non-server connection");
1043         result = SASL_BADPROT;
1044         break;
1045       }
1046
1047       if(value && strlen(value)) {
1048           result = _sasl_strdup(value, &str, NULL);
1049           if(result != SASL_OK) MEMERROR(conn);
1050       } else {
1051           PARAMERROR(conn);
1052       }
1053
1054       if(((sasl_server_conn_t *)conn)->user_realm)
1055           sasl_FREE(((sasl_server_conn_t *)conn)->user_realm);
1056
1057       ((sasl_server_conn_t *)conn)->user_realm = str;
1058       ((sasl_server_conn_t *)conn)->sparams->user_realm = str;
1059
1060       break;
1061
1062   case SASL_SEC_PROPS:
1063   {
1064       sasl_security_properties_t *props = (sasl_security_properties_t *)value;
1065
1066       if(props->maxbufsize == 0 && props->min_ssf != 0) {
1067           sasl_seterror(conn, 0,
1068                         "Attempt to disable security layers (maxoutbuf == 0) with min_ssf > 0");
1069           RETURN(conn, SASL_TOOWEAK);
1070       }
1071
1072       conn->props = *props;
1073
1074       if(conn->type == SASL_CONN_SERVER) {
1075         ((sasl_server_conn_t*)conn)->sparams->props = *props;
1076       } else {
1077         ((sasl_client_conn_t*)conn)->cparams->props = *props;
1078       }
1079
1080       break;
1081   }
1082       
1083   case SASL_IPREMOTEPORT:
1084   {
1085       const char *ipremoteport = (const char *)value;
1086       if(!value) {
1087           conn->got_ip_remote = 0; 
1088       } else if (_sasl_ipfromstring(ipremoteport, NULL, 0)
1089                  != SASL_OK) {
1090           sasl_seterror(conn, 0, "Bad IPREMOTEPORT value");
1091           RETURN(conn, SASL_BADPARAM);
1092       } else {
1093           strcpy(conn->ipremoteport, ipremoteport);
1094           conn->got_ip_remote = 1;
1095       }
1096       
1097       if(conn->got_ip_remote) {
1098           if(conn->type == SASL_CONN_CLIENT) {
1099               ((sasl_client_conn_t *)conn)->cparams->ipremoteport
1100                   = conn->ipremoteport;
1101               ((sasl_client_conn_t *)conn)->cparams->ipremlen =
1102                   (unsigned) strlen(conn->ipremoteport);
1103           } else if (conn->type == SASL_CONN_SERVER) {
1104               ((sasl_server_conn_t *)conn)->sparams->ipremoteport
1105                   = conn->ipremoteport;
1106               ((sasl_server_conn_t *)conn)->sparams->ipremlen =
1107                   (unsigned) strlen(conn->ipremoteport);
1108           }
1109       } else {
1110           if(conn->type == SASL_CONN_CLIENT) {
1111               ((sasl_client_conn_t *)conn)->cparams->ipremoteport
1112                   = NULL;
1113               ((sasl_client_conn_t *)conn)->cparams->ipremlen = 0;
1114           } else if (conn->type == SASL_CONN_SERVER) {
1115               ((sasl_server_conn_t *)conn)->sparams->ipremoteport
1116                   = NULL;             
1117               ((sasl_server_conn_t *)conn)->sparams->ipremlen = 0;
1118           }
1119       }
1120
1121       break;
1122   }
1123
1124   case SASL_IPLOCALPORT:
1125   {
1126       const char *iplocalport = (const char *)value;
1127       if(!value) {
1128           conn->got_ip_local = 0;         
1129       } else if (_sasl_ipfromstring(iplocalport, NULL, 0)
1130                  != SASL_OK) {
1131           sasl_seterror(conn, 0, "Bad IPLOCALPORT value");
1132           RETURN(conn, SASL_BADPARAM);
1133       } else {
1134           strcpy(conn->iplocalport, iplocalport);
1135           conn->got_ip_local = 1;
1136       }
1137
1138       if(conn->got_ip_local) {
1139           if(conn->type == SASL_CONN_CLIENT) {
1140               ((sasl_client_conn_t *)conn)->cparams->iplocalport
1141                   = conn->iplocalport;
1142               ((sasl_client_conn_t *)conn)->cparams->iploclen
1143                   = (unsigned) strlen(conn->iplocalport);
1144           } else if (conn->type == SASL_CONN_SERVER) {
1145               ((sasl_server_conn_t *)conn)->sparams->iplocalport
1146                   = conn->iplocalport;
1147               ((sasl_server_conn_t *)conn)->sparams->iploclen
1148                   = (unsigned) strlen(conn->iplocalport);
1149           }
1150       } else {
1151           if(conn->type == SASL_CONN_CLIENT) {
1152               ((sasl_client_conn_t *)conn)->cparams->iplocalport
1153                   = NULL;
1154               ((sasl_client_conn_t *)conn)->cparams->iploclen = 0;
1155           } else if (conn->type == SASL_CONN_SERVER) {
1156               ((sasl_server_conn_t *)conn)->sparams->iplocalport
1157                   = NULL;
1158               ((sasl_server_conn_t *)conn)->sparams->iploclen = 0;
1159           }
1160       }
1161       break;
1162   }
1163
1164   case SASL_APPNAME:
1165       /* Currently we only support server side contexts, but we should
1166          be able to extend this to support client side contexts as well */
1167       if(conn->type != SASL_CONN_SERVER) {
1168         sasl_seterror(conn, 0, "Tried to set application name on non-server connection");
1169         result = SASL_BADPROT;
1170         break;
1171       }
1172
1173       if(((sasl_server_conn_t *)conn)->appname) {
1174           sasl_FREE(((sasl_server_conn_t *)conn)->appname);
1175           ((sasl_server_conn_t *)conn)->appname = NULL;
1176       }
1177
1178       if(value && strlen(value)) {
1179           result = _sasl_strdup(value,
1180                                 &(((sasl_server_conn_t *)conn)->appname),
1181                                 NULL);
1182           if(result != SASL_OK) MEMERROR(conn);
1183           ((sasl_server_conn_t *)conn)->sparams->appname =
1184               ((sasl_server_conn_t *)conn)->appname;
1185           ((sasl_server_conn_t *)conn)->sparams->applen =
1186               (unsigned) strlen(((sasl_server_conn_t *)conn)->appname);
1187       } else {
1188           ((sasl_server_conn_t *)conn)->sparams->appname = NULL;
1189           ((sasl_server_conn_t *)conn)->sparams->applen = 0;
1190       }
1191       break;
1192
1193   default:
1194       sasl_seterror(conn, 0, "Unknown parameter type");
1195       result = SASL_BADPARAM;
1196   }
1197   
1198   RETURN(conn, result);
1199 }
1200
1201 /* this is apparently no longer a user function */
1202 static int sasl_usererr(int saslerr)
1203 {
1204     /* Hide the difference in a username failure and a password failure */
1205     if (saslerr == SASL_NOUSER)
1206         return SASL_BADAUTH;
1207
1208     /* otherwise return the error given; no transform necessary */
1209     return saslerr;
1210 }
1211
1212 const char *sasl_errstring(int saslerr,
1213                            const char *langlist __attribute__((unused)),
1214                            const char **outlang)
1215 {
1216   if (outlang) *outlang="en-us";
1217
1218   switch(saslerr)
1219     {
1220     case SASL_CONTINUE: return "another step is needed in authentication";
1221     case SASL_OK:       return "successful result";
1222     case SASL_FAIL:     return "generic failure";
1223     case SASL_NOMEM:    return "no memory available";
1224     case SASL_BUFOVER:  return "overflowed buffer";
1225     case SASL_NOMECH:   return "no mechanism available";
1226     case SASL_BADPROT:  return "bad protocol / cancel";
1227     case SASL_NOTDONE:  return "can't request info until later in exchange";
1228     case SASL_BADPARAM: return "invalid parameter supplied";
1229     case SASL_TRYAGAIN: return "transient failure (e.g., weak key)";
1230     case SASL_BADMAC:   return "integrity check failed";
1231     case SASL_NOTINIT:  return "SASL library not initialized";
1232                              /* -- client only codes -- */
1233     case SASL_INTERACT:   return "needs user interaction";
1234     case SASL_BADSERV:    return "server failed mutual authentication step";
1235     case SASL_WRONGMECH:  return "mechanism doesn't support requested feature";
1236                              /* -- server only codes -- */
1237     case SASL_BADAUTH:    return "authentication failure";
1238     case SASL_NOAUTHZ:    return "authorization failure";
1239     case SASL_TOOWEAK:    return "mechanism too weak for this user";
1240     case SASL_ENCRYPT:    return "encryption needed to use mechanism";
1241     case SASL_TRANS:      return "One time use of a plaintext password will enable requested mechanism for user";
1242     case SASL_EXPIRED:    return "passphrase expired, has to be reset";
1243     case SASL_DISABLED:   return "account disabled";
1244     case SASL_NOUSER:     return "user not found";
1245     case SASL_BADVERS:    return "version mismatch with plug-in";
1246     case SASL_UNAVAIL:    return "remote authentication server unavailable";
1247     case SASL_NOVERIFY:   return "user exists, but no verifier for user";
1248     case SASL_PWLOCK:     return "passphrase locked";
1249     case SASL_NOCHANGE:   return "requested change was not needed";
1250     case SASL_WEAKPASS:   return "passphrase is too weak for security policy";
1251     case SASL_NOUSERPASS: return "user supplied passwords are not permitted";
1252
1253     default:   return "undefined error!";
1254     }
1255
1256 }
1257
1258 /* Return the sanitized error detail about the last error that occured for 
1259  * a connection */
1260 const char *sasl_errdetail(sasl_conn_t *conn) 
1261 {
1262     unsigned need_len;
1263     const char *errstr;
1264     char leader[128];
1265
1266     if(!conn) return NULL;
1267     
1268     errstr = sasl_errstring(conn->error_code, NULL, NULL);
1269     snprintf(leader,128,"SASL(%d): %s: ",
1270              sasl_usererr(conn->error_code), errstr);
1271     
1272     need_len = (unsigned) (strlen(leader) + strlen(conn->error_buf) + 12);
1273     _buf_alloc(&conn->errdetail_buf, &conn->errdetail_buf_len, need_len);
1274
1275     snprintf(conn->errdetail_buf, need_len, "%s%s", leader, conn->error_buf);
1276    
1277     return conn->errdetail_buf;
1278 }
1279
1280
1281 /* Note that this needs the global callbacks, so if you don't give getcallbacks
1282  * a sasl_conn_t, you're going to need to pass it yourself (or else we couldn't
1283  * have client and server at the same time */
1284 static int _sasl_global_getopt(void *context,
1285                                const char *plugin_name,
1286                                const char *option,
1287                                const char ** result,
1288                                unsigned *len)
1289 {
1290   const sasl_global_callbacks_t * global_callbacks;
1291   const sasl_callback_t *callback;
1292
1293   global_callbacks = (const sasl_global_callbacks_t *) context;
1294
1295   if (global_callbacks && global_callbacks->callbacks) {
1296       for (callback = global_callbacks->callbacks;
1297            callback->id != SASL_CB_LIST_END;
1298            callback++) {
1299         if (callback->id == SASL_CB_GETOPT) {
1300           if (!callback->proc) return SASL_FAIL;
1301           if (((sasl_getopt_t *)(callback->proc))(callback->context,
1302                                                   plugin_name,
1303                                                   option,
1304                                                   result,
1305                                                   len)
1306               == SASL_OK)
1307             return SASL_OK;
1308         }
1309       }
1310   }
1311   
1312   /* look it up in our configuration file */
1313   *result = sasl_config_getstring(option, NULL);
1314   if (*result != NULL) {
1315       if (len) { *len = (unsigned) strlen(*result); }
1316       return SASL_OK;
1317   }
1318
1319   return SASL_FAIL;
1320 }
1321
1322 static int
1323 _sasl_conn_getopt(void *context,
1324                   const char *plugin_name,
1325                   const char *option,
1326                   const char ** result,
1327                   unsigned *len)
1328 {
1329   sasl_conn_t * conn;
1330   const sasl_callback_t *callback;
1331
1332   if (! context)
1333     return SASL_BADPARAM;
1334
1335   conn = (sasl_conn_t *) context;
1336
1337   if (conn->callbacks)
1338     for (callback = conn->callbacks;
1339          callback->id != SASL_CB_LIST_END;
1340          callback++)
1341       if (callback->id == SASL_CB_GETOPT
1342           && (((sasl_getopt_t *)(callback->proc))(callback->context,
1343                                                   plugin_name,
1344                                                   option,
1345                                                   result,
1346                                                   len)
1347               == SASL_OK))
1348         return SASL_OK;
1349
1350   /* If we made it here, we didn't find an appropriate callback
1351    * in the connection's callback list, or the callback we did
1352    * find didn't return SASL_OK.  So we attempt to use the
1353    * global callback for this connection... */
1354   return _sasl_global_getopt((void *)conn->global_callbacks,
1355                              plugin_name,
1356                              option,
1357                              result,
1358                              len);
1359 }
1360
1361 #ifdef HAVE_SYSLOG
1362 /* this is the default logging */
1363 static int _sasl_syslog(void *context,
1364                         int priority,
1365                         const char *message)
1366 {
1367     int syslog_priority;
1368     sasl_server_conn_t *sconn;
1369
1370     if (context) {
1371         if (((sasl_conn_t *)context)->type == SASL_CONN_SERVER) {
1372             sconn = (sasl_server_conn_t *)context;
1373             if (sconn->sparams->log_level < priority) 
1374                 return SASL_OK;
1375         }
1376     }
1377
1378     /* set syslog priority */
1379     switch(priority) {
1380     case SASL_LOG_NONE:
1381         return SASL_OK;
1382         break;
1383     case SASL_LOG_ERR:
1384         syslog_priority = LOG_ERR;
1385         break;
1386     case SASL_LOG_WARN:
1387         syslog_priority = LOG_WARNING;
1388         break;
1389     case SASL_LOG_NOTE:
1390     case SASL_LOG_FAIL:
1391         syslog_priority = LOG_NOTICE;
1392         break;
1393     case SASL_LOG_PASS:
1394     case SASL_LOG_TRACE:
1395     case SASL_LOG_DEBUG:
1396     default:
1397         syslog_priority = LOG_DEBUG;
1398         break;
1399     }
1400     
1401     /* do the syslog call. Do not need to call openlog? */
1402     syslog(syslog_priority | LOG_AUTH, "%s", message);
1403     
1404     return SASL_OK;
1405 }
1406 #endif                          /* HAVE_SYSLOG */
1407
1408 static int
1409 _sasl_getsimple(void *context,
1410                 int id,
1411                 const char ** result,
1412                 size_t *len)
1413 {
1414   const char *userid;
1415   sasl_conn_t *conn;
1416
1417   if (! context || ! result) return SASL_BADPARAM;
1418
1419   conn = (sasl_conn_t *)context;
1420
1421   switch(id) {
1422   case SASL_CB_AUTHNAME:
1423     userid = getenv("USER");
1424     if (userid != NULL) {
1425         *result = userid;
1426         if (len) *len = strlen(userid);
1427         return SASL_OK;
1428     }
1429     userid = getenv("USERNAME");
1430     if (userid != NULL) {
1431         *result = userid;
1432         if (len) *len = strlen(userid);
1433         return SASL_OK;
1434     }
1435 #ifdef WIN32
1436     /* for win32, try using the GetUserName standard call */
1437     {
1438         DWORD i;
1439         BOOL rval;
1440         static char sender[128];
1441         
1442         i = sizeof(sender);
1443         rval = GetUserName(sender, &i);
1444         if ( rval) { /* got a userid */
1445                 *result = sender;
1446                 if (len) *len = strlen(sender);
1447                 return SASL_OK;
1448         }
1449     }
1450 #endif /* WIN32 */
1451     return SASL_FAIL;
1452   default:
1453     return SASL_BADPARAM;
1454   }
1455 }
1456
1457 static int
1458 _sasl_getpath(void *context __attribute__((unused)),
1459               const char ** path_dest)
1460 {
1461 #if !defined(WIN32)
1462     char *path;
1463 #endif
1464     int res = SASL_OK;
1465
1466     if (! path_dest) {
1467         return SASL_BADPARAM;
1468     }
1469
1470     /* Only calculate the path once. */
1471     if (default_plugin_path == NULL) {
1472
1473 #if defined(WIN32)
1474         /* NB: On Windows platforms this value is always allocated */
1475         default_plugin_path = _sasl_get_default_win_path(context,
1476                                                          SASL_PLUGIN_PATH_ATTR,
1477                                                          PLUGINDIR);
1478 #else
1479         /* NB: On Unix platforms this value is never allocated */
1480         path = _sasl_get_default_unix_path(context,
1481                                            SASL_PATH_ENV_VAR,
1482                                            PLUGINDIR);
1483
1484         res = _sasl_strdup(path, &default_plugin_path, NULL);
1485 #endif
1486     }
1487
1488     if (res == SASL_OK) {
1489         *path_dest = default_plugin_path;
1490     }
1491
1492     return res;
1493 }
1494
1495 static int
1496 _sasl_getpath_simple(void *context __attribute__((unused)),
1497                      const char **path)
1498 {
1499     if (! path) {
1500         return SASL_BADPARAM;
1501     }
1502
1503     if (default_plugin_path == NULL) {
1504         return SASL_FAIL;
1505     }
1506
1507     *path = default_plugin_path;
1508
1509     return SASL_OK;
1510 }
1511
1512 static int
1513 _sasl_getconfpath(void *context __attribute__((unused)),
1514                   char ** path_dest)
1515 {
1516 #if !defined(WIN32)
1517     char *path;
1518 #endif
1519     int res = SASL_OK;
1520
1521     if (! path_dest) {
1522         return SASL_BADPARAM;
1523     }
1524
1525   /* Only calculate the path once. */
1526     if (default_conf_path == NULL) {
1527
1528 #if defined(WIN32)
1529         /* NB: On Windows platforms this value is always allocated */
1530         default_conf_path = _sasl_get_default_win_path(context,
1531                                                        SASL_CONF_PATH_ATTR,
1532                                                        CONFIGDIR);
1533 #else
1534         /* NB: On Unix platforms this value is never allocated */
1535         path = _sasl_get_default_unix_path(context,
1536                                            SASL_CONF_PATH_ENV_VAR,
1537                                            CONFIGDIR);
1538
1539         res = _sasl_strdup(path, &default_conf_path, NULL);
1540 #endif
1541     }
1542
1543     if (res == SASL_OK) {
1544         *path_dest = default_conf_path;
1545     }
1546
1547     return res;
1548 }
1549
1550 static int
1551 _sasl_getconfpath_simple(void *context __attribute__((unused)),
1552                          const char **path)
1553 {
1554     if (! path) {
1555         return SASL_BADPARAM;
1556     }
1557
1558     if (default_conf_path == NULL) {
1559         return SASL_FAIL;
1560     }
1561
1562     *path = default_conf_path;
1563
1564     return SASL_OK;
1565 }
1566
1567 static int
1568 _sasl_verifyfile(void *context __attribute__((unused)),
1569                  char *file  __attribute__((unused)),
1570                  int type  __attribute__((unused)))
1571 {
1572   /* always say ok */
1573   return SASL_OK;
1574 }
1575
1576
1577 static int
1578 _sasl_proxy_policy(sasl_conn_t *conn,
1579                    void *context __attribute__((unused)),
1580                    const char *requested_user, unsigned rlen,
1581                    const char *auth_identity, unsigned alen,
1582                    const char *def_realm __attribute__((unused)),
1583                    unsigned urlen __attribute__((unused)),
1584                    struct propctx *propctx __attribute__((unused)))
1585 {
1586     if (!conn)
1587         return SASL_BADPARAM;
1588
1589     if (!requested_user || *requested_user == '\0')
1590         return SASL_OK;
1591
1592     if (!auth_identity || !requested_user || rlen != alen ||
1593         (memcmp(auth_identity, requested_user, rlen) != 0)) {
1594         sasl_seterror(conn, 0,
1595                       "Requested identity not authenticated identity");
1596         RETURN(conn, SASL_BADAUTH);
1597     }
1598
1599     return SASL_OK;
1600 }
1601
1602 int _sasl_getcallback(sasl_conn_t * conn,
1603                       unsigned long callbackid,
1604                       int (**pproc)(),
1605                       void **pcontext)
1606 {
1607   const sasl_callback_t *callback;
1608
1609   if (!pproc || !pcontext)
1610       PARAMERROR(conn);
1611
1612   /* Some callbacks are always provided by the library */
1613   switch (callbackid) {
1614   case SASL_CB_LIST_END:
1615     /* Nothing ever gets to provide this */
1616       INTERROR(conn, SASL_FAIL);
1617   case SASL_CB_GETOPT:
1618       if (conn) {
1619           *pproc = &_sasl_conn_getopt;
1620           *pcontext = conn;
1621       } else {
1622           *pproc = &_sasl_global_getopt;
1623           *pcontext = NULL;
1624       }
1625       return SASL_OK;
1626   }
1627
1628   /* If it's not always provided by the library, see if there's
1629    * a version provided by the application for this connection... */
1630   if (conn && conn->callbacks) {
1631     for (callback = conn->callbacks; callback->id != SASL_CB_LIST_END;
1632          callback++) {
1633         if (callback->id == callbackid) {
1634             *pproc = callback->proc;
1635             *pcontext = callback->context;
1636             if (callback->proc) {
1637                 return SASL_OK;
1638             } else {
1639                 return SASL_INTERACT;
1640             }
1641         }
1642     }
1643   }
1644
1645   /* And, if not for this connection, see if there's one
1646    * for all {server,client} connections... */
1647   if (conn && conn->global_callbacks && conn->global_callbacks->callbacks) {
1648       for (callback = conn->global_callbacks->callbacks;
1649            callback->id != SASL_CB_LIST_END;
1650            callback++) {
1651           if (callback->id == callbackid) {
1652               *pproc = callback->proc;
1653               *pcontext = callback->context;
1654               if (callback->proc) {
1655                   return SASL_OK;
1656               } else {
1657                   return SASL_INTERACT;
1658               }
1659           }
1660       }
1661   }
1662
1663   /* Otherwise, see if the library provides a default callback. */
1664   switch (callbackid) {
1665 #ifdef HAVE_SYSLOG
1666   case SASL_CB_LOG:
1667     *pproc = (int (*)()) &_sasl_syslog;
1668     *pcontext = conn;
1669     return SASL_OK;
1670 #endif /* HAVE_SYSLOG */
1671   case SASL_CB_GETPATH:
1672     *pproc = default_getpath_cb.proc;
1673     *pcontext = default_getpath_cb.context;
1674     return SASL_OK;
1675   case SASL_CB_GETCONFPATH:
1676     *pproc = default_getconfpath_cb.proc;
1677     *pcontext = default_getconfpath_cb.context;
1678     return SASL_OK;
1679   case SASL_CB_AUTHNAME:
1680     *pproc = (int (*)()) &_sasl_getsimple;
1681     *pcontext = conn;
1682     return SASL_OK;
1683   case SASL_CB_VERIFYFILE:
1684     *pproc = & _sasl_verifyfile;
1685     *pcontext = NULL;
1686     return SASL_OK;
1687   case SASL_CB_PROXY_POLICY:
1688     *pproc = (int (*)()) &_sasl_proxy_policy;
1689     *pcontext = NULL;
1690     return SASL_OK;
1691   }
1692
1693   /* Unable to find a callback... */
1694   *pproc = NULL;
1695   *pcontext = NULL;
1696   sasl_seterror(conn, SASL_NOLOG, "Unable to find a callback: %d", callbackid);
1697   RETURN(conn,SASL_FAIL);
1698 }
1699
1700
1701 /*
1702  * This function is typically called from a plugin.
1703  * It creates a string from the formatting and varargs given
1704  * and calls the logging callback (syslog by default)
1705  *
1706  * %m will parse the value in the next argument as an errno string
1707  * %z will parse the next argument as a SASL error code.
1708  */
1709
1710 void
1711 _sasl_log (sasl_conn_t *conn,
1712            int level,
1713            const char *fmt,
1714            ...)
1715 {
1716   char *out=(char *) sasl_ALLOC(250);
1717   size_t alloclen=100; /* current allocated length */
1718   size_t outlen=0; /* current length of output buffer */
1719   size_t formatlen;
1720   size_t pos=0; /* current position in format string */
1721   int result;
1722   sasl_log_t *log_cb;
1723   void *log_ctx;
1724   
1725   int ival;
1726   unsigned int uval;
1727   char *cval;
1728   va_list ap; /* varargs thing */
1729
1730   if(!fmt) goto done;
1731   if(!out) return;
1732   
1733   formatlen = strlen(fmt);
1734
1735   /* See if we have a logging callback... */
1736   result = _sasl_getcallback(conn, SASL_CB_LOG, &log_cb, &log_ctx);
1737   if (result == SASL_OK && ! log_cb)
1738     result = SASL_FAIL;
1739   if (result != SASL_OK) goto done;
1740   
1741   va_start(ap, fmt); /* start varargs */
1742
1743   while(pos<formatlen)
1744   {
1745     if (fmt[pos]!='%') /* regular character */
1746     {
1747       result = _buf_alloc(&out, &alloclen, outlen+1);
1748       if (result != SASL_OK) goto done;
1749       out[outlen]=fmt[pos];
1750       outlen++;
1751       pos++;
1752
1753     } else { /* formating thing */
1754       int done=0;
1755       char frmt[10];
1756       int frmtpos=1;
1757       char tempbuf[21];
1758       frmt[0]='%';
1759       pos++;
1760
1761       while (done==0)
1762       {
1763         switch(fmt[pos])
1764           {
1765           case 's': /* need to handle this */
1766             cval = va_arg(ap, char *); /* get the next arg */
1767             result = _sasl_add_string(&out, &alloclen,
1768                                 &outlen, cval);
1769               
1770             if (result != SASL_OK) /* add the string */
1771                 goto done;
1772
1773             done=1;
1774             break;
1775
1776           case '%': /* double % output the '%' character */
1777             result = _buf_alloc(&out,&alloclen,outlen+1);
1778             if (result != SASL_OK)
1779                 goto done;
1780             
1781             out[outlen]='%';
1782             outlen++;
1783             done=1;
1784             break;
1785
1786           case 'm': /* insert the errno string */
1787             result = _sasl_add_string(&out, &alloclen, &outlen,
1788                                 strerror(va_arg(ap, int)));
1789             if (result != SASL_OK)
1790                 goto done;
1791             
1792             done=1;
1793             break;
1794
1795           case 'z': /* insert the sasl error string */
1796             result = _sasl_add_string(&out, &alloclen, &outlen,
1797                                 (char *) sasl_errstring(va_arg(ap, int),NULL,NULL));
1798             if (result != SASL_OK)
1799                 goto done;
1800             
1801             done=1;
1802             break;
1803
1804           case 'c':
1805             frmt[frmtpos++]=fmt[pos];
1806             frmt[frmtpos]=0;
1807             tempbuf[0] = (char) va_arg(ap, int); /* get the next arg */
1808             tempbuf[1]='\0';
1809             
1810             /* now add the character */
1811             result = _sasl_add_string(&out, &alloclen, &outlen, tempbuf);
1812             if (result != SASL_OK)
1813                 goto done;
1814                 
1815             done=1;
1816             break;
1817
1818           case 'd':
1819           case 'i':
1820             frmt[frmtpos++]=fmt[pos];
1821             frmt[frmtpos]=0;
1822             ival = va_arg(ap, int); /* get the next arg */
1823
1824             snprintf(tempbuf,20,frmt,ival); /* have snprintf do the work */
1825             /* now add the string */
1826             result = _sasl_add_string(&out, &alloclen, &outlen, tempbuf);
1827             if (result != SASL_OK)
1828                 goto done;
1829
1830             done=1;
1831             break;
1832
1833           case 'o':
1834           case 'u':
1835           case 'x':
1836           case 'X':
1837             frmt[frmtpos++]=fmt[pos];
1838             frmt[frmtpos]=0;
1839             uval = va_arg(ap, unsigned int); /* get the next arg */
1840
1841             snprintf(tempbuf,20,frmt,uval); /* have snprintf do the work */
1842             /* now add the string */
1843             result = _sasl_add_string(&out, &alloclen, &outlen, tempbuf);
1844             if (result != SASL_OK)
1845                 goto done;
1846
1847             done=1;
1848             break;
1849
1850           default: 
1851             frmt[frmtpos++]=fmt[pos]; /* add to the formating */
1852             frmt[frmtpos]=0;        
1853             if (frmtpos>9) 
1854               done=1;
1855           }
1856         pos++;
1857         if (pos>formatlen)
1858           done=1;
1859       }
1860
1861     }
1862   }
1863
1864   /* put 0 at end */
1865   result = _buf_alloc(&out, &alloclen, outlen+1);
1866   if (result != SASL_OK) goto done;
1867   out[outlen]=0;
1868
1869   va_end(ap);    
1870
1871   /* send log message */
1872   result = log_cb(log_ctx, level, out);
1873
1874  done:
1875   if(out) sasl_FREE(out);
1876 }
1877
1878
1879
1880 /* Allocate and Init a sasl_utils_t structure */
1881 sasl_utils_t *
1882 _sasl_alloc_utils(sasl_conn_t *conn,
1883                   sasl_global_callbacks_t *global_callbacks)
1884 {
1885   sasl_utils_t *utils;
1886   /* set util functions - need to do rest*/
1887   utils=sasl_ALLOC(sizeof(sasl_utils_t));
1888   if (utils==NULL)
1889     return NULL;
1890
1891   utils->conn = conn;
1892
1893   sasl_randcreate(&utils->rpool);
1894
1895   if (conn) {
1896     utils->getopt = &_sasl_conn_getopt;
1897     utils->getopt_context = conn;
1898   } else {
1899     utils->getopt = &_sasl_global_getopt;
1900     utils->getopt_context = global_callbacks;
1901   }
1902
1903   utils->malloc=_sasl_allocation_utils.malloc;
1904   utils->calloc=_sasl_allocation_utils.calloc;
1905   utils->realloc=_sasl_allocation_utils.realloc;
1906   utils->free=_sasl_allocation_utils.free;
1907
1908   utils->mutex_alloc = _sasl_mutex_utils.alloc;
1909   utils->mutex_lock = _sasl_mutex_utils.lock;
1910   utils->mutex_unlock = _sasl_mutex_utils.unlock;
1911   utils->mutex_free = _sasl_mutex_utils.free;
1912   
1913   utils->MD5Init  = &_sasl_MD5Init;
1914   utils->MD5Update= &_sasl_MD5Update;
1915   utils->MD5Final = &_sasl_MD5Final;
1916   utils->hmac_md5 = &_sasl_hmac_md5;
1917   utils->hmac_md5_init = &_sasl_hmac_md5_init;
1918   utils->hmac_md5_final = &_sasl_hmac_md5_final;
1919   utils->hmac_md5_precalc = &_sasl_hmac_md5_precalc;
1920   utils->hmac_md5_import = &_sasl_hmac_md5_import;
1921   utils->mkchal = &sasl_mkchal;
1922   utils->utf8verify = &sasl_utf8verify;
1923   utils->rand=&sasl_rand;
1924   utils->churn=&sasl_churn;  
1925   utils->checkpass=NULL;
1926   
1927   utils->encode64=&sasl_encode64;
1928   utils->decode64=&sasl_decode64;
1929   
1930   utils->erasebuffer=&sasl_erasebuffer;
1931
1932   utils->getprop=&sasl_getprop;
1933   utils->setprop=&sasl_setprop;
1934
1935   utils->getcallback=&_sasl_getcallback;
1936
1937   utils->log=&_sasl_log;
1938
1939   utils->seterror=&sasl_seterror;
1940
1941 #ifndef macintosh
1942   /* Aux Property Utilities */
1943   utils->prop_new=&prop_new;
1944   utils->prop_dup=&prop_dup;
1945   utils->prop_request=&prop_request;
1946   utils->prop_get=&prop_get;
1947   utils->prop_getnames=&prop_getnames;
1948   utils->prop_clear=&prop_clear;
1949   utils->prop_dispose=&prop_dispose;
1950   utils->prop_format=&prop_format;
1951   utils->prop_set=&prop_set;
1952   utils->prop_setvals=&prop_setvals;
1953   utils->prop_erase=&prop_erase;
1954   utils->auxprop_store=&sasl_auxprop_store;
1955 #endif
1956
1957   /* Spares */
1958   utils->spare_fptr = NULL;
1959   utils->spare_fptr1 = utils->spare_fptr2 = NULL;
1960   
1961   return utils;
1962 }
1963
1964 int
1965 _sasl_free_utils(const sasl_utils_t ** utils)
1966 {
1967     sasl_utils_t *nonconst;
1968
1969     if(!utils) return SASL_BADPARAM;
1970     if(!*utils) return SASL_OK;
1971
1972     /* I wish we could avoid this cast, it's pretty gratuitous but it
1973      * does make life easier to have it const everywhere else. */
1974     nonconst = (sasl_utils_t *)(*utils);
1975
1976     sasl_randfree(&(nonconst->rpool));
1977     sasl_FREE(nonconst);
1978
1979     *utils = NULL;
1980     return SASL_OK;
1981 }
1982
1983 int sasl_idle(sasl_conn_t *conn)
1984 {
1985   if (! conn) {
1986     if (_sasl_server_idle_hook
1987         && _sasl_server_idle_hook(NULL))
1988       return 1;
1989     if (_sasl_client_idle_hook
1990         && _sasl_client_idle_hook(NULL))
1991       return 1;
1992     return 0;
1993   }
1994
1995   if (conn->idle_hook)
1996     return conn->idle_hook(conn);
1997
1998   return 0;
1999 }
2000
2001 static const sasl_callback_t *
2002 _sasl_find_callback_by_type (const sasl_callback_t *callbacks,
2003                              unsigned long id)
2004 {
2005     if (callbacks) {
2006         while (callbacks->id != SASL_CB_LIST_END) {
2007             if (callbacks->id == id) {
2008                 return callbacks;
2009             } else {
2010                 ++callbacks;
2011             }
2012         }
2013     }
2014     return NULL;
2015 }
2016
2017 const sasl_callback_t *
2018 _sasl_find_getpath_callback(const sasl_callback_t *callbacks)
2019 {
2020   callbacks = _sasl_find_callback_by_type (callbacks, SASL_CB_GETPATH);
2021   if (callbacks != NULL) {
2022     return callbacks;
2023   } else {
2024     return &default_getpath_cb;
2025   }
2026 }
2027
2028 const sasl_callback_t *
2029 _sasl_find_getconfpath_callback(const sasl_callback_t *callbacks)
2030 {
2031   callbacks = _sasl_find_callback_by_type (callbacks, SASL_CB_GETCONFPATH);
2032   if (callbacks != NULL) {
2033     return callbacks;
2034   } else {
2035     return &default_getconfpath_cb;
2036   }
2037 }
2038
2039 const sasl_callback_t *
2040 _sasl_find_verifyfile_callback(const sasl_callback_t *callbacks)
2041 {
2042   static const sasl_callback_t default_verifyfile_cb = {
2043     SASL_CB_VERIFYFILE,
2044     &_sasl_verifyfile,
2045     NULL
2046   };
2047
2048   callbacks = _sasl_find_callback_by_type (callbacks, SASL_CB_VERIFYFILE);
2049   if (callbacks != NULL) {
2050     return callbacks;
2051   } else {
2052     return &default_verifyfile_cb;
2053   }
2054 }
2055
2056 /* Basically a conditional call to realloc(), if we need more */
2057 int _buf_alloc(char **rwbuf, size_t *curlen, size_t newlen) 
2058 {
2059     if(!(*rwbuf)) {
2060         *rwbuf = sasl_ALLOC((unsigned)newlen);
2061         if (*rwbuf == NULL) {
2062             *curlen = 0;
2063             return SASL_NOMEM;
2064         }
2065         *curlen = newlen;
2066     } else if(*rwbuf && *curlen < newlen) {
2067         size_t needed = 2*(*curlen);
2068
2069         while(needed < newlen)
2070             needed *= 2;
2071
2072         /* WARN - We will leak the old buffer on failure */
2073         *rwbuf = sasl_REALLOC(*rwbuf, (unsigned)needed);
2074         
2075         if (*rwbuf == NULL) {
2076             *curlen = 0;
2077             return SASL_NOMEM;
2078         }
2079         *curlen = needed;
2080     } 
2081
2082     return SASL_OK;
2083 }
2084
2085 /* for the mac os x cfm glue: this lets the calling function
2086    get pointers to the error buffer without having to touch the sasl_conn_t struct */
2087 void _sasl_get_errorbuf(sasl_conn_t *conn, char ***bufhdl, size_t **lenhdl)
2088 {
2089         *bufhdl = &conn->error_buf;
2090         *lenhdl = &conn->error_buf_len;
2091 }
2092
2093 /* convert an iovec to a single buffer */
2094 int _iovec_to_buf(const struct iovec *vec,
2095                   unsigned numiov, buffer_info_t **output) 
2096 {
2097     unsigned i;
2098     int ret;
2099     buffer_info_t *out;
2100     char *pos;
2101
2102     if (!vec || !output) return SASL_BADPARAM;
2103
2104     if (!(*output)) {
2105         *output = sasl_ALLOC(sizeof(buffer_info_t));
2106         if (!*output) return SASL_NOMEM;
2107         memset(*output,0,sizeof(buffer_info_t));
2108     }
2109
2110     out = *output;
2111     
2112     out->curlen = 0;
2113     for (i = 0; i < numiov; i++) {
2114         out->curlen += vec[i].iov_len;
2115     }
2116
2117     ret = _buf_alloc(&out->data, &out->reallen, out->curlen);
2118
2119     if (ret != SASL_OK) return SASL_NOMEM;
2120     
2121     memset(out->data, 0, out->reallen);
2122     pos = out->data;
2123     
2124     for (i = 0; i < numiov; i++) {
2125         memcpy(pos, vec[i].iov_base, vec[i].iov_len);
2126         pos += vec[i].iov_len;
2127     }
2128
2129     return SASL_OK;
2130 }
2131
2132 /* This code might be useful in the future, but it isn't now, so.... */
2133 #if 0
2134 int _sasl_iptostring(const struct sockaddr *addr, socklen_t addrlen,
2135                      char *out, unsigned outlen) {
2136     char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
2137     int niflags;
2138
2139     if(!addr || !out) return SASL_BADPARAM;
2140
2141     niflags = (NI_NUMERICHOST | NI_NUMERICSERV);
2142 #ifdef NI_WITHSCOPEID
2143     if (addr->sa_family == AF_INET6)
2144         niflags |= NI_WITHSCOPEID;
2145 #endif
2146     if (getnameinfo(addr, addrlen, hbuf, sizeof(hbuf), pbuf, sizeof(pbuf),
2147                     niflags) != 0)
2148         return SASL_BADPARAM;
2149
2150     if(outlen < strlen(hbuf) + strlen(pbuf) + 2)
2151         return SASL_BUFOVER;
2152
2153     snprintf(out, outlen, "%s;%s", hbuf, pbuf);
2154
2155     return SASL_OK;
2156 }
2157 #endif
2158
2159 int _sasl_ipfromstring(const char *addr,
2160                        struct sockaddr *out, socklen_t outlen) 
2161 {
2162     int i, j;
2163     struct addrinfo hints, *ai = NULL;
2164     char hbuf[NI_MAXHOST];
2165     
2166     /* A NULL out pointer just implies we don't do a copy, just verify it */
2167
2168     if(!addr) return SASL_BADPARAM;
2169
2170     /* Parse the address */
2171     for (i = 0; addr[i] != '\0' && addr[i] != ';'; i++) {
2172         if (i >= NI_MAXHOST)
2173             return SASL_BADPARAM;
2174         hbuf[i] = addr[i];
2175     }
2176     hbuf[i] = '\0';
2177
2178     if (addr[i] == ';')
2179         i++;
2180     /* XXX: Do we need this check? */
2181     for (j = i; addr[j] != '\0'; j++)
2182         if (!isdigit((int)(addr[j])))
2183             return SASL_BADPARAM;
2184
2185     memset(&hints, 0, sizeof(hints));
2186     hints.ai_family = PF_UNSPEC;
2187     hints.ai_socktype = SOCK_STREAM;
2188     hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2189     if (getaddrinfo(hbuf, &addr[i], &hints, &ai) != 0)
2190         return SASL_BADPARAM;
2191
2192     if (out) {
2193         if (outlen < (socklen_t)ai->ai_addrlen) {
2194             freeaddrinfo(ai);
2195             return SASL_BUFOVER;
2196         }
2197         memcpy(out, ai->ai_addr, ai->ai_addrlen);
2198     }
2199
2200     freeaddrinfo(ai);
2201
2202     return SASL_OK;
2203 }
2204
2205 int _sasl_build_mechlist(void) 
2206 {
2207     int count = 0;
2208     sasl_string_list_t *clist = NULL, *slist = NULL, *olist = NULL;
2209     sasl_string_list_t *p, *q, **last, *p_next;
2210
2211     clist = _sasl_client_mechs();
2212     slist = _sasl_server_mechs();
2213
2214     if(!clist) {
2215         olist = slist;
2216     } else {
2217         int flag;
2218         
2219         /* append slist to clist, and set olist to clist */
2220         for(p = slist; p; p = p_next) {
2221             flag = 0;
2222             p_next = p->next;
2223
2224             last = &clist;
2225             for(q = clist; q; q = q->next) {
2226                 if(!strcmp(q->d, p->d)) {
2227                     /* They match, set the flag */
2228                     flag = 1;
2229                     break;
2230                 }
2231                 last = &(q->next);
2232             }
2233
2234             if(!flag) {
2235                 *last = p;
2236                 p->next = NULL;
2237             } else {
2238                 sasl_FREE(p);
2239             }
2240         }
2241
2242         olist = clist;
2243     }
2244
2245     if(!olist) {
2246         printf ("no olist");
2247         return SASL_FAIL;
2248     }
2249
2250     for (p = olist; p; p = p->next) count++;
2251     
2252     if(global_mech_list) {
2253         sasl_FREE(global_mech_list);
2254         global_mech_list = NULL;
2255     }
2256     
2257     global_mech_list = sasl_ALLOC((count + 1) * sizeof(char *));
2258     if(!global_mech_list) return SASL_NOMEM;
2259     
2260     memset(global_mech_list, 0, (count + 1) * sizeof(char *));
2261     
2262     count = 0;
2263     for (p = olist; p; p = p_next) {
2264         p_next = p->next;
2265
2266         global_mech_list[count++] = (char *) p->d;
2267
2268         sasl_FREE(p);
2269     }
2270
2271     return SASL_OK;
2272 }
2273
2274 const char ** sasl_global_listmech(void) 
2275 {
2276     return (const char **)global_mech_list;
2277 }
2278
2279 int sasl_listmech(sasl_conn_t *conn,
2280                   const char *user,
2281                   const char *prefix,
2282                   const char *sep,
2283                   const char *suffix,
2284                   const char **result,
2285                   unsigned *plen,
2286                   int *pcount)
2287 {
2288     if(!conn) {
2289         return SASL_BADPARAM;
2290     } else if(conn->type == SASL_CONN_SERVER) {
2291         RETURN(conn, _sasl_server_listmech(conn, user, prefix, sep, suffix,
2292                                            result, plen, pcount));
2293     } else if (conn->type == SASL_CONN_CLIENT) {
2294         RETURN(conn, _sasl_client_listmech(conn, prefix, sep, suffix,
2295                                            result, plen, pcount));
2296     }
2297     
2298     PARAMERROR(conn);
2299 }
2300
2301
2302 #ifndef WIN32
2303 static char *
2304 _sasl_get_default_unix_path(void *context __attribute__((unused)),
2305                             char * env_var_name,
2306                             char * default_value)
2307 {
2308     char *path = NULL;
2309
2310     /* Honor external variable only in a safe environment */
2311     if (getuid() == geteuid() && getgid() == getegid()) {
2312         path = getenv(env_var_name);
2313     }
2314     if (! path) {
2315         path = default_value;
2316     }
2317
2318     return path;
2319 }
2320
2321 #else
2322 /* Return NULL on failure */
2323 static char *
2324 _sasl_get_default_win_path(void *context __attribute__((unused)),
2325                            char * reg_attr_name,
2326                            char * default_value)
2327 {
2328     /* Open registry entry, and find all registered SASL libraries.
2329      *
2330      * Registry location:
2331      *
2332      *     SOFTWARE\\Carnegie Mellon\\Project Cyrus\\SASL Library
2333      *
2334      * Key - value:
2335      *
2336      *     "SearchPath" - value: PATH like (';' delimited) list
2337      *                    of directories where to search for plugins
2338      *                    The list may contain references to environment
2339      *                    variables (e.g. %PATH%).
2340      *
2341      */
2342     HKEY  hKey;
2343     DWORD ret;
2344     DWORD ValueType;                /* value type */
2345     DWORD cbData;                   /* value size */
2346     BYTE * ValueData;               /* value */
2347     DWORD cbExpandedData;           /* "expanded" value size */
2348     BYTE * ExpandedValueData;       /* "expanded" value */
2349     char * return_value;            /* function return value */
2350     char * tmp;
2351
2352     /* Initialization */
2353     ExpandedValueData = NULL;
2354     ValueData = NULL;
2355     return_value = NULL;
2356
2357     /* Open the registry */
2358     ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
2359                        SASL_ROOT_KEY,
2360                        0,
2361                        KEY_READ,
2362                        &hKey);
2363
2364     if (ret != ERROR_SUCCESS) { 
2365         /* no registry entry */
2366         (void) _sasl_strdup (default_value, &return_value, NULL);
2367         return return_value;
2368     }
2369
2370     /* figure out value type and required buffer size */
2371     /* the size will include space for terminating NUL if required */
2372     RegQueryValueEx (hKey,
2373                      reg_attr_name,
2374                      NULL,          /* reserved */
2375                      &ValueType,
2376                      NULL,
2377                      &cbData);
2378  
2379     /* Only accept string related types */
2380     if (ValueType != REG_EXPAND_SZ &&
2381         ValueType != REG_MULTI_SZ &&
2382         ValueType != REG_SZ) {
2383         return_value = NULL;
2384         goto CLEANUP;
2385     }
2386
2387     /* Any high water mark? */
2388     ValueData = sasl_ALLOC(cbData);
2389     if (ValueData == NULL) {
2390         return_value = NULL;
2391         goto CLEANUP;
2392     };
2393
2394     RegQueryValueEx (hKey,
2395                      reg_attr_name,
2396                      NULL,          /* reserved */
2397                      &ValueType,
2398                      ValueData,
2399                      &cbData);
2400
2401     switch (ValueType) {
2402     case REG_EXPAND_SZ:
2403         /* : A random starting guess */
2404         cbExpandedData = cbData + 1024;
2405         ExpandedValueData = sasl_ALLOC(cbExpandedData);
2406         if (ExpandedValueData == NULL) {
2407             return_value = NULL;
2408             goto CLEANUP;
2409         };
2410
2411         cbExpandedData = ExpandEnvironmentStrings(
2412                                                   ValueData,
2413                                                   ExpandedValueData,
2414                                                   cbExpandedData);
2415
2416         if (cbExpandedData == 0) {
2417             /* : GetLastError() contains the reason for failure */
2418             return_value = NULL;
2419             goto CLEANUP;
2420         }
2421
2422         /* : Must retry expansion with the bigger buffer */
2423         if (cbExpandedData > cbData + 1024) {
2424             /* : Memory leak here if can't realloc */
2425             ExpandedValueData = sasl_REALLOC(ExpandedValueData, cbExpandedData);
2426             if (ExpandedValueData == NULL) {
2427                 return_value = NULL;
2428                 goto CLEANUP;
2429             };
2430
2431             cbExpandedData = ExpandEnvironmentStrings(
2432                                                       ValueData,
2433                                                       ExpandedValueData,
2434                                                       cbExpandedData);
2435
2436             /* : This should not happen */
2437             if (cbExpandedData == 0) {
2438                 /* : GetLastError() contains the reason for failure */
2439                 return_value = NULL;
2440                 goto CLEANUP;
2441             }
2442         }
2443
2444         sasl_FREE(ValueData);
2445         ValueData = ExpandedValueData;
2446         /* : This is to prevent automatical freeing of this block on cleanup */
2447         ExpandedValueData = NULL;
2448
2449         break;
2450
2451     case REG_MULTI_SZ:
2452         tmp = ValueData;
2453
2454         /* : We shouldn't overflow here, as the buffer is guarantied
2455            : to contain at least two consequent NULs */
2456         while (1) {
2457             if (tmp[0] == '\0') {
2458                 /* : Stop the process if we found the end of the string (two consequent NULs) */
2459                 if (tmp[1] == '\0') {
2460                     break;
2461                 }
2462
2463                 /* : Replace delimiting NUL with our delimiter characted */
2464                 tmp[0] = PATHS_DELIMITER;
2465             }
2466             tmp += strlen(tmp);
2467         }
2468         break;
2469
2470     case REG_SZ:
2471         /* Do nothing, it is good as is */
2472         break;
2473
2474     default:
2475         return_value = NULL;
2476         goto CLEANUP;
2477     }
2478
2479     return_value = ValueData;
2480
2481 CLEANUP:
2482     RegCloseKey(hKey);
2483     if (ExpandedValueData != NULL) sasl_FREE(ExpandedValueData);
2484     if (return_value == NULL) {
2485         if (ValueData != NULL) sasl_FREE(ValueData);
2486     }
2487
2488     return (return_value);
2489 }
2490 #endif