Print the debug thingies on stderr instead of stdout. If for nothing
[openssl.git] / crypto / engine / eng_table.c
1 /* ====================================================================
2  * Copyright (c) 2001 The OpenSSL Project.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer. 
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in
13  *    the documentation and/or other materials provided with the
14  *    distribution.
15  *
16  * 3. All advertising materials mentioning features or use of this
17  *    software must display the following acknowledgment:
18  *    "This product includes software developed by the OpenSSL Project
19  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
20  *
21  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
22  *    endorse or promote products derived from this software without
23  *    prior written permission. For written permission, please contact
24  *    licensing@OpenSSL.org.
25  *
26  * 5. Products derived from this software may not be called "OpenSSL"
27  *    nor may "OpenSSL" appear in their names without prior written
28  *    permission of the OpenSSL Project.
29  *
30  * 6. Redistributions of any form whatsoever must retain the following
31  *    acknowledgment:
32  *    "This product includes software developed by the OpenSSL Project
33  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
36  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46  * OF THE POSSIBILITY OF SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This product includes cryptographic software written by Eric Young
50  * (eay@cryptsoft.com).  This product includes software written by Tim
51  * Hudson (tjh@cryptsoft.com).
52  *
53  */
54
55 #include "cryptlib.h"
56 #include <openssl/evp.h>
57 #include <openssl/lhash.h>
58 #include "eng_int.h"
59
60 /* This is the type of item in the 'implementation' table. Each 'nid' hashes to
61  * a (potentially NULL) ENGINE_PILE structure which contains a stack of ENGINE*
62  * pointers. These pointers aren't references, because they're inserted and
63  * removed during ENGINE creation and ENGINE destruction. They point to ENGINEs
64  * that *exist* (ie. have a structural reference count greater than zero) rather
65  * than ENGINEs that are *functional*. Each pointer in those stacks are to
66  * ENGINEs that implements the algorithm corresponding to each 'nid'. */
67
68 /* The type of the items in the table */
69 typedef struct st_engine_pile
70         {
71         /* The 'nid' of the algorithm/mode this ENGINE_PILE structure represents
72          * */
73         int nid;
74         /* A stack of ENGINE pointers for ENGINEs that support this
75          * algorithm/mode. In the event that 'funct' is NULL, the first entry in
76          * this stack that initialises will be set as 'funct' and assumed as the
77          * default for operations of this type. */
78         STACK_OF(ENGINE) *sk;
79         /* The default ENGINE to perform this algorithm/mode. */
80         ENGINE *funct;
81         /* This value optimises engine_table_select(). If it is called it sets
82          * this value to 1. Any changes to this ENGINE_PILE resets it to zero.
83          * As such, no ENGINE_init() thrashing is done unless ENGINEs
84          * continually register (and/or unregister). */
85         int uptodate;
86         } ENGINE_PILE;
87
88 /* The type of the hash table of ENGINE_PILE structures such that each are
89  * unique and keyed by the 'nid' value. */
90 struct st_engine_table
91         {
92         LHASH piles;
93         }; /* ENGINE_TABLE */
94
95 /* This value stores global options controlling behaviour of (mostly) the
96  * engine_table_select() function. It's a bitmask of flag values of the form
97  * ENGINE_TABLE_FLAG_*** (as defined in engine.h) and is controlled by the
98  * ENGINE_[get|set]_table_flags() function. */
99 static unsigned int table_flags = 0;
100
101 /* API function manipulating 'table_flags' */
102 unsigned int ENGINE_get_table_flags(void)
103         {
104         return table_flags;
105         }
106 void ENGINE_set_table_flags(unsigned int flags)
107         {
108         table_flags = flags;
109         }
110
111 /* Internal functions for the "piles" hash table */
112 static unsigned long engine_pile_hash(const ENGINE_PILE *c)
113         {
114         return c->nid;
115         }
116 static int engine_pile_cmp(const ENGINE_PILE *a, const ENGINE_PILE *b)
117         {
118         return a->nid - b->nid;
119         }
120 static IMPLEMENT_LHASH_HASH_FN(engine_pile_hash, const ENGINE_PILE *)
121 static IMPLEMENT_LHASH_COMP_FN(engine_pile_cmp, const ENGINE_PILE *)
122 static int int_table_check(ENGINE_TABLE **t, int create)
123         {
124         LHASH *lh;
125         if(*t)
126                 return 1;
127         if(!create)
128                 return 0;
129         if((lh = lh_new(LHASH_HASH_FN(engine_pile_hash),
130                         LHASH_COMP_FN(engine_pile_cmp))) == NULL)
131                 return 0;
132         *t = (ENGINE_TABLE *)lh;
133         return 1;
134         }
135
136 /* Privately exposed (via eng_int.h) functions for adding and/or removing
137  * ENGINEs from the implementation table */
138 int engine_table_register(ENGINE_TABLE **table, ENGINE_CLEANUP_CB *cleanup,
139                 ENGINE *e, const int *nids, int num_nids, int setdefault)
140         {
141         int ret = 0, added = 0;
142         ENGINE_PILE tmplate, *fnd;
143         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
144         if(!(*table))
145                 added = 1;
146         if(!int_table_check(table, 1))
147                 goto end;
148         if(added)
149                 /* The cleanup callback needs to be added */
150                 engine_cleanup_add_first(cleanup);
151         while(num_nids--)
152                 {
153                 tmplate.nid = *nids;
154                 fnd = lh_retrieve(&(*table)->piles, &tmplate);
155                 if(!fnd)
156                         {
157                         fnd = OPENSSL_malloc(sizeof(ENGINE_PILE));
158                         if(!fnd)
159                                 goto end;
160                         fnd->uptodate = 1;
161                         fnd->nid = *nids;
162                         fnd->sk = sk_ENGINE_new_null();
163                         if(!fnd->sk)
164                                 {
165                                 OPENSSL_free(fnd);
166                                 goto end;
167                                 }
168                         fnd->funct= NULL;
169                         lh_insert(&(*table)->piles, fnd);
170                         }
171                 /* A registration shouldn't add duplciate entries */
172                 sk_ENGINE_delete_ptr(fnd->sk, e);
173                 /* if 'setdefault', this ENGINE goes to the head of the list */
174                 if(!sk_ENGINE_push(fnd->sk, e))
175                         goto end;
176                 /* "touch" this ENGINE_PILE */
177                 fnd->uptodate = 0;
178                 if(setdefault)
179                         {
180                         if(!engine_unlocked_init(e))
181                                 {
182                                 ENGINEerr(ENGINE_F_ENGINE_TABLE_REGISTER,
183                                                 ENGINE_R_INIT_FAILED);
184                                 goto end;
185                                 }
186                         if(fnd->funct)
187                                 engine_unlocked_finish(fnd->funct, 0);
188                         fnd->funct = e;
189                         }
190                 nids++;
191                 }
192         ret = 1;
193 end:
194         CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
195         return ret;
196         }
197 static void int_unregister_cb(ENGINE_PILE *pile, ENGINE *e)
198         {
199         int n;
200         /* Iterate the 'c->sk' stack removing any occurance of 'e' */
201         while((n = sk_ENGINE_find(pile->sk, e)) >= 0)
202                 {
203                 sk_ENGINE_delete(pile->sk, n);
204                 /* "touch" this ENGINE_CIPHER */
205                 pile->uptodate = 0;
206                 }
207         if(pile->funct == e)
208                 {
209                 engine_unlocked_finish(e, 0);
210                 pile->funct = NULL;
211                 }
212         }
213 static IMPLEMENT_LHASH_DOALL_ARG_FN(int_unregister_cb,ENGINE_PILE *,ENGINE *)
214 void engine_table_unregister(ENGINE_TABLE **table, ENGINE *e)
215         {
216         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
217         if(int_table_check(table, 0))
218                 lh_doall_arg(&(*table)->piles,
219                         LHASH_DOALL_ARG_FN(int_unregister_cb), e);
220         CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
221         }
222
223 static void int_cleanup_cb(ENGINE_PILE *p)
224         {
225         sk_ENGINE_free(p->sk);
226         if(p->funct)
227                 engine_unlocked_finish(p->funct, 0);
228         OPENSSL_free(p);
229         }
230 static IMPLEMENT_LHASH_DOALL_FN(int_cleanup_cb,ENGINE_PILE *)
231 void engine_table_cleanup(ENGINE_TABLE **table)
232         {
233         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
234         if(*table)
235                 {
236                 lh_doall(&(*table)->piles, LHASH_DOALL_FN(int_cleanup_cb));
237                 lh_free(&(*table)->piles);
238                 *table = NULL;
239                 }
240         CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
241         }
242
243 /* Exposed API function to get a functional reference from the implementation
244  * table (ie. try to get a functional reference from the tabled structural
245  * references) for a given cipher 'nid' */
246 #ifndef ENGINE_TABLE_DEBUG
247 ENGINE *engine_table_select(ENGINE_TABLE **table, int nid)
248 #else
249 ENGINE *engine_table_select_tmp(ENGINE_TABLE **table, int nid, const char *f, int l)
250 #endif
251         {
252         ENGINE *ret = NULL;
253         ENGINE_PILE tmplate, *fnd=NULL;
254         int initres, loop = 0;
255
256         /* If 'engine_ciphers' is NULL, then it's absolutely *sure* that no
257          * ENGINEs have registered any implementations! */
258         if(!(*table))
259                 {
260 #ifdef ENGINE_TABLE_DEBUG
261                 fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, no "
262                         "registered for anything!\n", f, l, nid);
263 #endif
264                 return NULL;
265                 }
266         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
267         /* Check again inside the lock otherwise we could race against cleanup
268          * operations. But don't worry about a fprintf(stderr). */
269         if(!int_table_check(table, 0))
270                 goto end;
271         tmplate.nid = nid;
272         fnd = lh_retrieve(&(*table)->piles, &tmplate);
273         if(!fnd)
274                 goto end;
275         if(fnd->funct && engine_unlocked_init(fnd->funct))
276                 {
277 #ifdef ENGINE_TABLE_DEBUG
278                 fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, using "
279                         "ENGINE '%s' cached\n", f, l, nid, fnd->funct->id);
280 #endif
281                 ret = fnd->funct;
282                 goto end;
283                 }
284         if(fnd->uptodate)
285                 {
286                 ret = fnd->funct;
287                 goto end;
288                 }
289 trynext:
290         ret = sk_ENGINE_value(fnd->sk, loop++);
291         if(!ret)
292                 {
293 #ifdef ENGINE_TABLE_DEBUG
294                 fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, no "
295                                 "registered implementations would initialise\n",
296                                 f, l, nid);
297 #endif
298                 goto end;
299                 }
300 #if 0
301         /* Don't need to get a reference if we hold the lock. If the locking has
302          * to change in future, that would be different ... */
303         ret->struct_ref++; engine_ref_debug(ret, 0, 1)
304 #endif
305         /* Try and initialise the ENGINE if it's already functional *or* if the
306          * ENGINE_TABLE_FLAG_NOINIT flag is not set. */
307         if((ret->funct_ref > 0) || !(table_flags & ENGINE_TABLE_FLAG_NOINIT))
308                 initres = engine_unlocked_init(ret);
309         else
310                 initres = 0;
311 #if 0
312         /* Release the structural reference */
313         ret->struct_ref--; engine_ref_debug(ret, 0, -1);
314 #endif
315         if(initres)
316                 {
317                 /* If we didn't have a default (functional reference) for this
318                  * 'nid' (or we had one but for whatever reason we're now
319                  * initialising a different one), use this opportunity to set
320                  * 'funct'. */
321                 if((fnd->funct != ret) && engine_unlocked_init(ret))
322                         {
323                         /* If there was a previous default we release it. */
324                         if(fnd->funct)
325                                 engine_unlocked_finish(fnd->funct, 0);
326                         /* We got an extra functional reference for the
327                          * per-'nid' default */
328                         fnd->funct = ret;
329 #ifdef ENGINE_TABLE_DEBUG
330                         fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, "
331                                 "setting default to '%s'\n", f, l, nid, ret->id);
332 #endif
333                         }
334 #ifdef ENGINE_TABLE_DEBUG
335                 fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, using "
336                                 "newly initialised '%s'\n", f, l, nid, ret->id);
337 #endif
338                 goto end;
339                 }
340         goto trynext;
341 end:
342         /* Whatever happened - we should "untouch" our uptodate file seeing as
343          * we have tried our best to find a functional reference for 'nid'. If
344          * it failed, it is unlikely to succeed again until some future
345          * registrations (or unregistrations) have taken place that affect that
346          * 'nid'. */
347         if(fnd)
348                 fnd->uptodate = 1;
349 #ifdef ENGINE_TABLE_DEBUG
350         if(ret)
351                 fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, caching "
352                                 "ENGINE '%s'\n", f, l, nid, ret->id);
353         else
354                 fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, caching "
355                                 "'no matching ENGINE'\n", f, l, nid);
356 #endif
357         CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
358         /* Whatever happened, any failed init()s are not failures in this
359          * context, so clear our error state. */
360         ERR_clear_error();
361         return ret;
362         }