Remove /* foo.c */ comments
[openssl.git] / crypto / engine / eng_dyn.c
1 /*
2  * Written by Geoff Thorpe (geoff@geoffthorpe.net) for the OpenSSL project
3  * 2001.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999-2001 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59 #include "eng_int.h"
60 #include <openssl/dso.h>
61
62 /*
63  * Shared libraries implementing ENGINEs for use by the "dynamic" ENGINE
64  * loader should implement the hook-up functions with the following
65  * prototypes.
66  */
67
68 /* Our ENGINE handlers */
69 static int dynamic_init(ENGINE *e);
70 static int dynamic_finish(ENGINE *e);
71 static int dynamic_ctrl(ENGINE *e, int cmd, long i, void *p,
72                         void (*f) (void));
73 /* Predeclare our context type */
74 typedef struct st_dynamic_data_ctx dynamic_data_ctx;
75 /* The implementation for the important control command */
76 static int dynamic_load(ENGINE *e, dynamic_data_ctx *ctx);
77
78 #define DYNAMIC_CMD_SO_PATH             ENGINE_CMD_BASE
79 #define DYNAMIC_CMD_NO_VCHECK           (ENGINE_CMD_BASE + 1)
80 #define DYNAMIC_CMD_ID                  (ENGINE_CMD_BASE + 2)
81 #define DYNAMIC_CMD_LIST_ADD            (ENGINE_CMD_BASE + 3)
82 #define DYNAMIC_CMD_DIR_LOAD            (ENGINE_CMD_BASE + 4)
83 #define DYNAMIC_CMD_DIR_ADD             (ENGINE_CMD_BASE + 5)
84 #define DYNAMIC_CMD_LOAD                (ENGINE_CMD_BASE + 6)
85
86 /* The constants used when creating the ENGINE */
87 static const char *engine_dynamic_id = "dynamic";
88 static const char *engine_dynamic_name = "Dynamic engine loading support";
89 static const ENGINE_CMD_DEFN dynamic_cmd_defns[] = {
90     {DYNAMIC_CMD_SO_PATH,
91      "SO_PATH",
92      "Specifies the path to the new ENGINE shared library",
93      ENGINE_CMD_FLAG_STRING},
94     {DYNAMIC_CMD_NO_VCHECK,
95      "NO_VCHECK",
96      "Specifies to continue even if version checking fails (boolean)",
97      ENGINE_CMD_FLAG_NUMERIC},
98     {DYNAMIC_CMD_ID,
99      "ID",
100      "Specifies an ENGINE id name for loading",
101      ENGINE_CMD_FLAG_STRING},
102     {DYNAMIC_CMD_LIST_ADD,
103      "LIST_ADD",
104      "Whether to add a loaded ENGINE to the internal list (0=no,1=yes,2=mandatory)",
105      ENGINE_CMD_FLAG_NUMERIC},
106     {DYNAMIC_CMD_DIR_LOAD,
107      "DIR_LOAD",
108      "Specifies whether to load from 'DIR_ADD' directories (0=no,1=yes,2=mandatory)",
109      ENGINE_CMD_FLAG_NUMERIC},
110     {DYNAMIC_CMD_DIR_ADD,
111      "DIR_ADD",
112      "Adds a directory from which ENGINEs can be loaded",
113      ENGINE_CMD_FLAG_STRING},
114     {DYNAMIC_CMD_LOAD,
115      "LOAD",
116      "Load up the ENGINE specified by other settings",
117      ENGINE_CMD_FLAG_NO_INPUT},
118     {0, NULL, NULL, 0}
119 };
120
121 /*
122  * Loading code stores state inside the ENGINE structure via the "ex_data"
123  * element. We load all our state into a single structure and use that as a
124  * single context in the "ex_data" stack.
125  */
126 struct st_dynamic_data_ctx {
127     /* The DSO object we load that supplies the ENGINE code */
128     DSO *dynamic_dso;
129     /*
130      * The function pointer to the version checking shared library function
131      */
132     dynamic_v_check_fn v_check;
133     /*
134      * The function pointer to the engine-binding shared library function
135      */
136     dynamic_bind_engine bind_engine;
137     /* The default name/path for loading the shared library */
138     char *DYNAMIC_LIBNAME;
139     /* Whether to continue loading on a version check failure */
140     int no_vcheck;
141     /* If non-NULL, stipulates the 'id' of the ENGINE to be loaded */
142     char *engine_id;
143     /*
144      * If non-zero, a successfully loaded ENGINE should be added to the
145      * internal ENGINE list. If 2, the add must succeed or the entire load
146      * should fail.
147      */
148     int list_add_value;
149     /* The symbol name for the version checking function */
150     const char *DYNAMIC_F1;
151     /* The symbol name for the "initialise ENGINE structure" function */
152     const char *DYNAMIC_F2;
153     /*
154      * Whether to never use 'dirs', use 'dirs' as a fallback, or only use
155      * 'dirs' for loading. Default is to use 'dirs' as a fallback.
156      */
157     int dir_load;
158     /* A stack of directories from which ENGINEs could be loaded */
159     STACK_OF(OPENSSL_STRING) *dirs;
160 };
161
162 /*
163  * This is the "ex_data" index we obtain and reserve for use with our context
164  * structure.
165  */
166 static int dynamic_ex_data_idx = -1;
167
168 static void int_free_str(char *s)
169 {
170     OPENSSL_free(s);
171 }
172
173 /*
174  * Because our ex_data element may or may not get allocated depending on
175  * whether a "first-use" occurs before the ENGINE is freed, we have a memory
176  * leak problem to solve. We can't declare a "new" handler for the ex_data as
177  * we don't want a dynamic_data_ctx in *all* ENGINE structures of all types
178  * (this is a bug in the design of CRYPTO_EX_DATA). As such, we just declare
179  * a "free" handler and that will get called if an ENGINE is being destroyed
180  * and there was an ex_data element corresponding to our context type.
181  */
182 static void dynamic_data_ctx_free_func(void *parent, void *ptr,
183                                        CRYPTO_EX_DATA *ad, int idx, long argl,
184                                        void *argp)
185 {
186     if (ptr) {
187         dynamic_data_ctx *ctx = (dynamic_data_ctx *)ptr;
188         DSO_free(ctx->dynamic_dso);
189         OPENSSL_free(ctx->DYNAMIC_LIBNAME);
190         OPENSSL_free(ctx->engine_id);
191         sk_OPENSSL_STRING_pop_free(ctx->dirs, int_free_str);
192         OPENSSL_free(ctx);
193     }
194 }
195
196 /*
197  * Construct the per-ENGINE context. We create it blindly and then use a lock
198  * to check for a race - if so, all but one of the threads "racing" will have
199  * wasted their time. The alternative involves creating everything inside the
200  * lock which is far worse.
201  */
202 static int dynamic_set_data_ctx(ENGINE *e, dynamic_data_ctx **ctx)
203 {
204     dynamic_data_ctx *c = OPENSSL_zalloc(sizeof(*c));
205
206     if (c == NULL) {
207         ENGINEerr(ENGINE_F_DYNAMIC_SET_DATA_CTX, ERR_R_MALLOC_FAILURE);
208         return 0;
209     }
210     c->dirs = sk_OPENSSL_STRING_new_null();
211     if (c->dirs == NULL) {
212         ENGINEerr(ENGINE_F_DYNAMIC_SET_DATA_CTX, ERR_R_MALLOC_FAILURE);
213         OPENSSL_free(c);
214         return 0;
215     }
216     c->DYNAMIC_F1 = "v_check";
217     c->DYNAMIC_F2 = "bind_engine";
218     c->dir_load = 1;
219     CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
220     if ((*ctx = (dynamic_data_ctx *)ENGINE_get_ex_data(e,
221                                                        dynamic_ex_data_idx))
222         == NULL) {
223         /* Good, we're the first */
224         ENGINE_set_ex_data(e, dynamic_ex_data_idx, c);
225         *ctx = c;
226         c = NULL;
227     }
228     CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
229     /*
230      * If we lost the race to set the context, c is non-NULL and *ctx is the
231      * context of the thread that won.
232      */
233     if (c)
234         sk_OPENSSL_STRING_free(c->dirs);
235     OPENSSL_free(c);
236     return 1;
237 }
238
239 /*
240  * This function retrieves the context structure from an ENGINE's "ex_data",
241  * or if it doesn't exist yet, sets it up.
242  */
243 static dynamic_data_ctx *dynamic_get_data_ctx(ENGINE *e)
244 {
245     dynamic_data_ctx *ctx;
246     if (dynamic_ex_data_idx < 0) {
247         /*
248          * Create and register the ENGINE ex_data, and associate our "free"
249          * function with it to ensure any allocated contexts get freed when
250          * an ENGINE goes underground.
251          */
252         int new_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL,
253                                               dynamic_data_ctx_free_func);
254         if (new_idx == -1) {
255             ENGINEerr(ENGINE_F_DYNAMIC_GET_DATA_CTX, ENGINE_R_NO_INDEX);
256             return NULL;
257         }
258         CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
259         /* Avoid a race by checking again inside this lock */
260         if (dynamic_ex_data_idx < 0) {
261             /* Good, someone didn't beat us to it */
262             dynamic_ex_data_idx = new_idx;
263             new_idx = -1;
264         }
265         CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
266         /*
267          * In theory we could "give back" the index here if (new_idx>-1), but
268          * it's not possible and wouldn't gain us much if it were.
269          */
270     }
271     ctx = (dynamic_data_ctx *)ENGINE_get_ex_data(e, dynamic_ex_data_idx);
272     /* Check if the context needs to be created */
273     if ((ctx == NULL) && !dynamic_set_data_ctx(e, &ctx))
274         /* "set_data" will set errors if necessary */
275         return NULL;
276     return ctx;
277 }
278
279 static ENGINE *engine_dynamic(void)
280 {
281     ENGINE *ret = ENGINE_new();
282     if (ret == NULL)
283         return NULL;
284     if (!ENGINE_set_id(ret, engine_dynamic_id) ||
285         !ENGINE_set_name(ret, engine_dynamic_name) ||
286         !ENGINE_set_init_function(ret, dynamic_init) ||
287         !ENGINE_set_finish_function(ret, dynamic_finish) ||
288         !ENGINE_set_ctrl_function(ret, dynamic_ctrl) ||
289         !ENGINE_set_flags(ret, ENGINE_FLAGS_BY_ID_COPY) ||
290         !ENGINE_set_cmd_defns(ret, dynamic_cmd_defns)) {
291         ENGINE_free(ret);
292         return NULL;
293     }
294     return ret;
295 }
296
297 void ENGINE_load_dynamic(void)
298 {
299     ENGINE *toadd = engine_dynamic();
300     if (!toadd)
301         return;
302     ENGINE_add(toadd);
303     /*
304      * If the "add" worked, it gets a structural reference. So either way, we
305      * release our just-created reference.
306      */
307     ENGINE_free(toadd);
308     /*
309      * If the "add" didn't work, it was probably a conflict because it was
310      * already added (eg. someone calling ENGINE_load_blah then calling
311      * ENGINE_load_builtin_engines() perhaps).
312      */
313     ERR_clear_error();
314 }
315
316 static int dynamic_init(ENGINE *e)
317 {
318     /*
319      * We always return failure - the "dyanamic" engine itself can't be used
320      * for anything.
321      */
322     return 0;
323 }
324
325 static int dynamic_finish(ENGINE *e)
326 {
327     /*
328      * This should never be called on account of "dynamic_init" always
329      * failing.
330      */
331     return 0;
332 }
333
334 static int dynamic_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
335 {
336     dynamic_data_ctx *ctx = dynamic_get_data_ctx(e);
337     int initialised;
338
339     if (!ctx) {
340         ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ENGINE_R_NOT_LOADED);
341         return 0;
342     }
343     initialised = ((ctx->dynamic_dso == NULL) ? 0 : 1);
344     /* All our control commands require the ENGINE to be uninitialised */
345     if (initialised) {
346         ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ENGINE_R_ALREADY_LOADED);
347         return 0;
348     }
349     switch (cmd) {
350     case DYNAMIC_CMD_SO_PATH:
351         /* a NULL 'p' or a string of zero-length is the same thing */
352         if (p && (strlen((const char *)p) < 1))
353             p = NULL;
354         OPENSSL_free(ctx->DYNAMIC_LIBNAME);
355         if (p)
356             ctx->DYNAMIC_LIBNAME = OPENSSL_strdup(p);
357         else
358             ctx->DYNAMIC_LIBNAME = NULL;
359         return (ctx->DYNAMIC_LIBNAME ? 1 : 0);
360     case DYNAMIC_CMD_NO_VCHECK:
361         ctx->no_vcheck = ((i == 0) ? 0 : 1);
362         return 1;
363     case DYNAMIC_CMD_ID:
364         /* a NULL 'p' or a string of zero-length is the same thing */
365         if (p && (strlen((const char *)p) < 1))
366             p = NULL;
367         OPENSSL_free(ctx->engine_id);
368         if (p)
369             ctx->engine_id = OPENSSL_strdup(p);
370         else
371             ctx->engine_id = NULL;
372         return (ctx->engine_id ? 1 : 0);
373     case DYNAMIC_CMD_LIST_ADD:
374         if ((i < 0) || (i > 2)) {
375             ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ENGINE_R_INVALID_ARGUMENT);
376             return 0;
377         }
378         ctx->list_add_value = (int)i;
379         return 1;
380     case DYNAMIC_CMD_LOAD:
381         return dynamic_load(e, ctx);
382     case DYNAMIC_CMD_DIR_LOAD:
383         if ((i < 0) || (i > 2)) {
384             ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ENGINE_R_INVALID_ARGUMENT);
385             return 0;
386         }
387         ctx->dir_load = (int)i;
388         return 1;
389     case DYNAMIC_CMD_DIR_ADD:
390         /* a NULL 'p' or a string of zero-length is the same thing */
391         if (!p || (strlen((const char *)p) < 1)) {
392             ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ENGINE_R_INVALID_ARGUMENT);
393             return 0;
394         }
395         {
396             char *tmp_str = OPENSSL_strdup(p);
397             if (!tmp_str) {
398                 ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ERR_R_MALLOC_FAILURE);
399                 return 0;
400             }
401             sk_OPENSSL_STRING_insert(ctx->dirs, tmp_str, -1);
402         }
403         return 1;
404     default:
405         break;
406     }
407     ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED);
408     return 0;
409 }
410
411 static int int_load(dynamic_data_ctx *ctx)
412 {
413     int num, loop;
414     /* Unless told not to, try a direct load */
415     if ((ctx->dir_load != 2) && (DSO_load(ctx->dynamic_dso,
416                                           ctx->DYNAMIC_LIBNAME, NULL,
417                                           0)) != NULL)
418         return 1;
419     /* If we're not allowed to use 'dirs' or we have none, fail */
420     if (!ctx->dir_load || (num = sk_OPENSSL_STRING_num(ctx->dirs)) < 1)
421         return 0;
422     for (loop = 0; loop < num; loop++) {
423         const char *s = sk_OPENSSL_STRING_value(ctx->dirs, loop);
424         char *merge = DSO_merge(ctx->dynamic_dso, ctx->DYNAMIC_LIBNAME, s);
425         if (!merge)
426             return 0;
427         if (DSO_load(ctx->dynamic_dso, merge, NULL, 0)) {
428             /* Found what we're looking for */
429             OPENSSL_free(merge);
430             return 1;
431         }
432         OPENSSL_free(merge);
433     }
434     return 0;
435 }
436
437 static int dynamic_load(ENGINE *e, dynamic_data_ctx *ctx)
438 {
439     ENGINE cpy;
440     dynamic_fns fns;
441
442     if (ctx->dynamic_dso == NULL)
443         ctx->dynamic_dso = DSO_new();
444     if (ctx->dynamic_dso == NULL)
445         return 0;
446     if (!ctx->DYNAMIC_LIBNAME) {
447         if (!ctx->engine_id)
448             return 0;
449         ctx->DYNAMIC_LIBNAME =
450             DSO_convert_filename(ctx->dynamic_dso, ctx->engine_id);
451     }
452     if (!int_load(ctx)) {
453         ENGINEerr(ENGINE_F_DYNAMIC_LOAD, ENGINE_R_DSO_NOT_FOUND);
454         DSO_free(ctx->dynamic_dso);
455         ctx->dynamic_dso = NULL;
456         return 0;
457     }
458     /* We have to find a bind function otherwise it'll always end badly */
459     if (!
460         (ctx->bind_engine =
461          (dynamic_bind_engine) DSO_bind_func(ctx->dynamic_dso,
462                                              ctx->DYNAMIC_F2))) {
463         ctx->bind_engine = NULL;
464         DSO_free(ctx->dynamic_dso);
465         ctx->dynamic_dso = NULL;
466         ENGINEerr(ENGINE_F_DYNAMIC_LOAD, ENGINE_R_DSO_FAILURE);
467         return 0;
468     }
469     /* Do we perform version checking? */
470     if (!ctx->no_vcheck) {
471         unsigned long vcheck_res = 0;
472         /*
473          * Now we try to find a version checking function and decide how to
474          * cope with failure if/when it fails.
475          */
476         ctx->v_check =
477             (dynamic_v_check_fn) DSO_bind_func(ctx->dynamic_dso,
478                                                ctx->DYNAMIC_F1);
479         if (ctx->v_check)
480             vcheck_res = ctx->v_check(OSSL_DYNAMIC_VERSION);
481         /*
482          * We fail if the version checker veto'd the load *or* if it is
483          * deferring to us (by returning its version) and we think it is too
484          * old.
485          */
486         if (vcheck_res < OSSL_DYNAMIC_OLDEST) {
487             /* Fail */
488             ctx->bind_engine = NULL;
489             ctx->v_check = NULL;
490             DSO_free(ctx->dynamic_dso);
491             ctx->dynamic_dso = NULL;
492             ENGINEerr(ENGINE_F_DYNAMIC_LOAD,
493                       ENGINE_R_VERSION_INCOMPATIBILITY);
494             return 0;
495         }
496     }
497     /*
498      * First binary copy the ENGINE structure so that we can roll back if the
499      * hand-over fails
500      */
501     memcpy(&cpy, e, sizeof(ENGINE));
502     /*
503      * Provide the ERR, "ex_data", memory, and locking callbacks so the
504      * loaded library uses our state rather than its own. FIXME: As noted in
505      * engine.h, much of this would be simplified if each area of code
506      * provided its own "summary" structure of all related callbacks. It
507      * would also increase opaqueness.
508      */
509     fns.static_state = ENGINE_get_static_state();
510     fns.lock_fns.lock_locking_cb = CRYPTO_get_locking_callback();
511     fns.lock_fns.lock_add_lock_cb = CRYPTO_get_add_lock_callback();
512     fns.lock_fns.dynlock_create_cb = CRYPTO_get_dynlock_create_callback();
513     fns.lock_fns.dynlock_lock_cb = CRYPTO_get_dynlock_lock_callback();
514     fns.lock_fns.dynlock_destroy_cb = CRYPTO_get_dynlock_destroy_callback();
515     /*
516      * Now that we've loaded the dynamic engine, make sure no "dynamic"
517      * ENGINE elements will show through.
518      */
519     engine_set_all_null(e);
520
521     /* Try to bind the ENGINE onto our own ENGINE structure */
522     if (!ctx->bind_engine(e, ctx->engine_id, &fns)) {
523         ctx->bind_engine = NULL;
524         ctx->v_check = NULL;
525         DSO_free(ctx->dynamic_dso);
526         ctx->dynamic_dso = NULL;
527         ENGINEerr(ENGINE_F_DYNAMIC_LOAD, ENGINE_R_INIT_FAILED);
528         /* Copy the original ENGINE structure back */
529         memcpy(e, &cpy, sizeof(ENGINE));
530         return 0;
531     }
532     /* Do we try to add this ENGINE to the internal list too? */
533     if (ctx->list_add_value > 0) {
534         if (!ENGINE_add(e)) {
535             /* Do we tolerate this or fail? */
536             if (ctx->list_add_value > 1) {
537                 /*
538                  * Fail - NB: By this time, it's too late to rollback, and
539                  * trying to do so allows the bind_engine() code to have
540                  * created leaks. We just have to fail where we are, after
541                  * the ENGINE has changed.
542                  */
543                 ENGINEerr(ENGINE_F_DYNAMIC_LOAD,
544                           ENGINE_R_CONFLICTING_ENGINE_ID);
545                 return 0;
546             }
547             /* Tolerate */
548             ERR_clear_error();
549         }
550     }
551     return 1;
552 }