1 /*
2  * Copyright (C) 2008 Stefan Walter
3  * Copyright (C) 2011 Collabora Ltd.
4  * Copyright (C) 2017 Red Hat, Inc.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  *     * Redistributions of source code must retain the above
11  *       copyright notice, this list of conditions and the
12  *       following disclaimer.
13  *     * Redistributions in binary form must reproduce the
14  *       above copyright notice, this list of conditions and
15  *       the following disclaimer in the documentation and/or
16  *       other materials provided with the distribution.
17  *     * The names of contributors to this software may not be
18  *       used to endorse or promote products derived from this
19  *       software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
28  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
31  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
32  * DAMAGE.
33  *
34  * Author: Stef Walter <stefw@collabora.co.uk>
35  */
36 
37 #include "config.h"
38 
39 /* We use and define deprecated functions here */
40 #define P11_KIT_NO_DEPRECATIONS
41 #define P11_DEBUG_FLAG P11_DEBUG_LIB
42 
43 #include "conf.h"
44 #include "debug.h"
45 #include "dict.h"
46 #include "library.h"
47 #include "log.h"
48 #include "message.h"
49 #include "modules.h"
50 #include "path.h"
51 #include "pkcs11.h"
52 #include "p11-kit.h"
53 #include "private.h"
54 #include "proxy.h"
55 #include "rpc.h"
56 #include "virtual.h"
57 
58 #include <sys/stat.h>
59 #include <sys/types.h>
60 
61 #include <assert.h>
62 #include <ctype.h>
63 #include <dirent.h>
64 #include <errno.h>
65 #include <limits.h>
66 #include <stdarg.h>
67 #include <stddef.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <unistd.h>
72 
73 #ifdef ENABLE_NLS
74 #include <libintl.h>
75 #define _(x) dgettext(PACKAGE_NAME, x)
76 #else
77 #define _(x) (x)
78 #endif
79 
80 /**
81  * SECTION:p11-kit
82  * @title: Modules
83  * @short_description: Module loading and initializing
84  *
85  * PKCS\#11 modules are used by crypto libraries and applications to access
86  * crypto objects (like keys and certificates) and to perform crypto operations.
87  *
88  * In order for applications to behave consistently with regard to the user's
89  * installed PKCS\#11 modules, each module must be configured so that applications
90  * or libraries know that they should load it.
91  *
92  * When multiple consumers of a module (such as libraries or applications) are
93  * in the same process, coordination of the initialization and finalization
94  * of PKCS\#11 modules is required. To do this modules are managed by p11-kit.
95  * This means that various unsafe methods are coordinated between callers. Unmanaged
96  * modules are simply the raw PKCS\#11 module pointers without p11-kit getting in the
97  * way. It is highly recommended that the default managed behavior is used.
98  *
99  * The functions here provide support for initializing configured modules. The
100  * p11_kit_modules_load() function should be used to load and initialize
101  * the configured modules. When done, the p11_kit_modules_release() function
102  * should be used to release those modules and associated resources.
103  *
104  * In addition p11_kit_config_option() can be used to access other parts
105  * of the module configuration.
106  *
107  * If a consumer wishes to load an arbitrary PKCS\#11 module that's not
108  * configured use p11_kit_module_load() to do so. And use p11_kit_module_release()
109  * to later release it.
110  *
111  * Modules are represented by a pointer to their <code>CK_FUNCTION_LIST</code>
112  * entry points.
113  */
114 
115 /**
116  * SECTION:p11-kit-deprecated
117  * @title: Deprecated
118  * @short_description: Deprecated functions
119  *
120  * These functions have been deprecated from p11-kit and are not recommended for
121  * general usage. In large part they were deprecated because they did not adequately
122  * insulate multiple callers of a PKCS\#11 module from another, and could not
123  * support the 'managed' mode needed to do this.
124  */
125 
126 /**
127  * P11_KIT_MODULE_UNMANAGED:
128  *
129  * Module is loaded in non 'managed' mode. This is not recommended,
130  * disables many features, and prevents coordination between multiple
131  * callers of the same module.
132  */
133 
134 /**
135  * P11_KIT_MODULE_CRITICAL:
136  *
137  * Flag to load a module in 'critical' mode. Failure to load a critical module
138  * will prevent all other modules from loading. A failure when loading a
139  * non-critical module skips that module.
140  */
141 
142 typedef struct _Module {
143 	/*
144 	 * When using managed modules, this forms the base of the
145 	 * virtual stack into which all the other modules call. This is also
146 	 * the first field in this structure so we can cast between them.
147 	 */
148 	p11_virtual virt;
149 
150 	/* The initialize args built from configuration */
151 	CK_C_INITIALIZE_ARGS init_args;
152 	int ref_count;
153 	int init_count;
154 
155 	/* Registered modules */
156 	char *name;
157 	char *filename;
158 	p11_dict *config;
159 	bool critical;
160 
161 	/*
162 	 * This is a pointer to the actual dl shared module, or perhaps
163 	 * the RPC client context.
164 	 */
165 	void *loaded_module;
166 	p11_kit_destroyer loaded_destroy;
167 
168 	/* Initialization, mutex must be held */
169 	p11_mutex_t initialize_mutex;
170 	unsigned int initialize_called;
171 	p11_thread_id_t initialize_thread;
172 } Module;
173 
174 /*
175  * Shared data between threads, protected by the mutex, a structure so
176  * we can audit thread safety easier.
177  */
178 static struct _Shared {
179 	p11_dict *modules;
180 	p11_dict *unmanaged_by_funcs;
181 	p11_dict *managed_by_closure;
182 	p11_dict *config;
183 } gl = { NULL, NULL };
184 
185 /* These are global variables to be overridden in tests */
186 const char *p11_config_system_file = P11_SYSTEM_CONFIG_FILE;
187 const char *p11_config_user_file = P11_USER_CONFIG_FILE;
188 const char *p11_config_package_modules = P11_PACKAGE_CONFIG_MODULES;
189 const char *p11_config_system_modules = P11_SYSTEM_CONFIG_MODULES;
190 const char *p11_config_user_modules = P11_USER_CONFIG_MODULES;
191 
192 /* -----------------------------------------------------------------------------
193  * P11-KIT FUNCTIONALITY
194  */
195 
196 /**
197  * p11_kit_override_system_files:
198  * @system_conf: the system configuration file (default: system_config_dir/pkcs11.conf)
199  * @user_conf: the user configuration file (default: ~/.config/pkcs11/pkcs11.conf)
200  * @package_modules: location of modules shipped by p11-kit (default: system_config/modules)
201  * @system_modules: location of system pkcs11 modules (default: system_config/modules)
202  * @user_modules: location of user modules (default: ~/.config/pkcs11/modules)
203  *
204  * Overrides the default system configuration files. The
205  * provided values should be accessible for the lifetime
206  * of p11-kit usage.
207  *
208  * When the value %NULL is provided for any of the locations,
209  * it will not be updated.
210  *
211  * This is function intended to be used in test suites and
212  * not production, and as such %P11_KIT_FUTURE_UNSTABLE_API
213  * must be defined before including p11-kit.h.
214  *
215  * Since: 0.23.10
216  *
217  */
218 void
p11_kit_override_system_files(const char * system_conf,const char * user_conf,const char * package_modules,const char * system_modules,const char * user_modules)219 p11_kit_override_system_files (const char *system_conf,
220                                const char *user_conf,
221                                const char *package_modules,
222                                const char *system_modules,
223                                const char *user_modules)
224 {
225 	if (system_conf)
226 		p11_config_system_file = system_conf;
227 
228 	if (user_conf)
229 		p11_config_user_file = user_conf;
230 
231 	if (package_modules)
232 		p11_config_package_modules = package_modules;
233 
234 	if (system_modules)
235 		p11_config_system_modules = system_modules;
236 
237 	if (user_modules)
238 		p11_config_user_modules = user_modules;
239 }
240 
241 static CK_RV
create_mutex(CK_VOID_PTR_PTR mut)242 create_mutex (CK_VOID_PTR_PTR mut)
243 {
244 	p11_mutex_t *pmutex;
245 
246 	return_val_if_fail (mut != NULL, CKR_ARGUMENTS_BAD);
247 
248 	pmutex = malloc (sizeof (p11_mutex_t));
249 	return_val_if_fail (pmutex != NULL, CKR_HOST_MEMORY);
250 
251 	p11_mutex_init (pmutex);
252 	*mut = pmutex;
253 	return CKR_OK;
254 }
255 
256 static CK_RV
destroy_mutex(CK_VOID_PTR mut)257 destroy_mutex (CK_VOID_PTR mut)
258 {
259 	p11_mutex_t *pmutex = mut;
260 
261 	return_val_if_fail (mut != NULL, CKR_MUTEX_BAD);
262 
263 	p11_mutex_uninit (pmutex);
264 	free (pmutex);
265 	return CKR_OK;
266 }
267 
268 static CK_RV
lock_mutex(CK_VOID_PTR mut)269 lock_mutex (CK_VOID_PTR mut)
270 {
271 	p11_mutex_t *pmutex = mut;
272 
273 	return_val_if_fail (mut != NULL, CKR_MUTEX_BAD);
274 
275 	p11_mutex_lock (pmutex);
276 	return CKR_OK;
277 }
278 
279 static CK_RV
unlock_mutex(CK_VOID_PTR mut)280 unlock_mutex (CK_VOID_PTR mut)
281 {
282 	p11_mutex_t *pmutex = mut;
283 
284 	return_val_if_fail (mut != NULL, CKR_MUTEX_BAD);
285 
286 	p11_mutex_unlock (pmutex);
287 	return CKR_OK;
288 }
289 
290 static void
free_module_unlocked(void * data)291 free_module_unlocked (void *data)
292 {
293 	Module *mod = data;
294 
295 	assert (mod != NULL);
296 
297 	/* Module must have no outstanding references */
298 	assert (mod->ref_count == 0);
299 
300 	if (mod->init_count > 0) {
301 		p11_debug_precond ("module unloaded without C_Finalize having been "
302 		                   "called for each C_Initialize");
303 	} else {
304 		assert (mod->initialize_thread == 0);
305 	}
306 
307 	p11_virtual_uninit (&mod->virt);
308 
309 	if (mod->loaded_destroy)
310 		mod->loaded_destroy (mod->loaded_module);
311 
312 	p11_mutex_uninit (&mod->initialize_mutex);
313 	p11_dict_free (mod->config);
314 	free (mod->name);
315 	free (mod->filename);
316 	free (mod->init_args.pReserved);
317 	free (mod);
318 }
319 
320 static Module *
alloc_module_unlocked(void)321 alloc_module_unlocked (void)
322 {
323 	Module *mod;
324 
325 	mod = calloc (1, sizeof (Module));
326 	return_val_if_fail (mod != NULL, NULL);
327 
328 	mod->init_args.CreateMutex = create_mutex;
329 	mod->init_args.DestroyMutex = destroy_mutex;
330 	mod->init_args.LockMutex = lock_mutex;
331 	mod->init_args.UnlockMutex = unlock_mutex;
332 	mod->init_args.flags = CKF_OS_LOCKING_OK;
333 	p11_mutex_init (&mod->initialize_mutex);
334 
335 	/*
336 	 * The default for configured modules is non-critical, but for
337 	 * modules loaded explicitly, and not from config, we treat them
338 	 * as critical. So this gets overridden for configured modules
339 	 * later when the config is loaded.
340 	 */
341 	mod->critical = true;
342 
343 	return mod;
344 }
345 
346 #ifdef __GNUC__
347 bool       p11_proxy_module_check                    (CK_FUNCTION_LIST_PTR module) __attribute__((weak));
348 
349 bool
p11_proxy_module_check(CK_FUNCTION_LIST_PTR module)350 p11_proxy_module_check (CK_FUNCTION_LIST_PTR module)
351 {
352 	return false;
353 }
354 #endif
355 
356 static CK_RV
dlopen_and_get_function_list(Module * mod,const char * path,CK_FUNCTION_LIST ** funcs)357 dlopen_and_get_function_list (Module *mod,
358                               const char *path,
359                               CK_FUNCTION_LIST **funcs)
360 {
361 	CK_C_GetFunctionList gfl;
362 	dl_module_t dl;
363 	char *error;
364 	CK_RV rv;
365 
366 	assert (mod != NULL);
367 	assert (path != NULL);
368 	assert (funcs != NULL);
369 
370 	dl = p11_dl_open (path);
371 	if (dl == NULL) {
372 		error = p11_dl_error ();
373 		p11_message (_("couldn't load module: %s: %s"), path, error);
374 		free (error);
375 		return CKR_GENERAL_ERROR;
376 	}
377 
378 	/* When the Module goes away, dlclose the loaded module */
379 	mod->loaded_destroy = (p11_kit_destroyer)p11_dl_close;
380 	mod->loaded_module = dl;
381 
382 	gfl = p11_dl_symbol (dl, "C_GetFunctionList");
383 	if (!gfl) {
384 		error = p11_dl_error ();
385 		p11_message (_("couldn't find C_GetFunctionList entry point in module: %s: %s"),
386 		             path, error);
387 		free (error);
388 		return CKR_GENERAL_ERROR;
389 	}
390 
391 	rv = gfl (funcs);
392 	if (rv != CKR_OK) {
393 		p11_message (_("call to C_GetFunctiontList failed in module: %s: %s"),
394 		             path, p11_kit_strerror (rv));
395 		return rv;
396 	}
397 
398 	if (p11_proxy_module_check (*funcs)) {
399 		p11_message (_("refusing to load the p11-kit-proxy.so module as a registered module"));
400 		return CKR_FUNCTION_FAILED;
401 	}
402 
403 	p11_virtual_init (&mod->virt, &p11_virtual_base, *funcs, NULL);
404 	p11_debug ("opened module: %s", path);
405 	return CKR_OK;
406 }
407 
408 static CK_RV
load_module_from_file_inlock(const char * name,const char * path,Module ** result)409 load_module_from_file_inlock (const char *name,
410                               const char *path,
411                               Module **result)
412 {
413 	CK_FUNCTION_LIST *funcs;
414 	char *expand = NULL;
415 	Module *mod;
416 	Module *prev;
417 	CK_RV rv;
418 
419 	assert (path != NULL);
420 	assert (result != NULL);
421 
422 	mod = alloc_module_unlocked ();
423 	return_val_if_fail (mod != NULL, CKR_HOST_MEMORY);
424 
425 	if (!p11_path_absolute (path)) {
426 		p11_debug ("module path is relative, loading from: %s", P11_MODULE_PATH);
427 		path = expand = p11_path_build (P11_MODULE_PATH, path, NULL);
428 		return_val_if_fail (path != NULL, CKR_HOST_MEMORY);
429 	}
430 
431 	p11_debug ("loading module %s%sfrom path: %s",
432 	           name ? name : "", name ? " " : "", path);
433 
434 	mod->filename = strdup (path);
435 
436 	rv = dlopen_and_get_function_list (mod, path, &funcs);
437 	free (expand);
438 
439 	if (rv != CKR_OK) {
440 		free_module_unlocked (mod);
441 		return rv;
442 	}
443 
444 	/* Do we have a previous one like this, if so ignore load */
445 	prev = p11_dict_get (gl.unmanaged_by_funcs, funcs);
446 
447 	/* If same module was loaded previously, just take over config */
448 	if (prev != NULL) {
449 		if (!name || prev->name || prev->config)
450 			p11_debug ("duplicate module %s, using previous", name);
451 		free_module_unlocked (mod);
452 		mod = prev;
453 
454 	/* This takes ownership of the module */
455 	} else if (!p11_dict_set (gl.modules, mod, mod) ||
456 		   !p11_dict_set (gl.unmanaged_by_funcs, funcs, mod)) {
457 		return_val_if_reached (CKR_HOST_MEMORY);
458 	}
459 
460 	*result= mod;
461 	return CKR_OK;
462 }
463 
464 static CK_RV
setup_module_for_remote_inlock(const char * name,const char * remote,Module ** result)465 setup_module_for_remote_inlock (const char *name,
466                                 const char *remote,
467                                 Module **result)
468 {
469 	p11_rpc_transport *rpc;
470 	Module *mod;
471 
472 	p11_debug ("remoting module %s using: %s", name, remote);
473 
474 	mod = alloc_module_unlocked ();
475 	return_val_if_fail (mod != NULL, CKR_HOST_MEMORY);
476 
477 	rpc = p11_rpc_transport_new (&mod->virt, remote, name);
478 	if (rpc == NULL) {
479 		free_module_unlocked (mod);
480 		return CKR_DEVICE_ERROR;
481 	}
482 
483 	mod->filename = NULL;
484 	mod->loaded_module = rpc;
485 	mod->loaded_destroy = p11_rpc_transport_free;
486 
487 	/* This takes ownership of the module */
488 	if (!p11_dict_set (gl.modules, mod, mod))
489 		return_val_if_reached (CKR_HOST_MEMORY);
490 
491 	*result = mod;
492 	return CKR_OK;
493 }
494 
495 static int
is_list_delimiter(char ch)496 is_list_delimiter (char ch)
497 {
498 	return ch == ',' ||  isspace (ch);
499 }
500 
501 static bool
is_string_in_list(const char * list,const char * string)502 is_string_in_list (const char *list,
503                    const char *string)
504 {
505 	const char *where;
506 	const char *start = list;
507 
508 	while (*start != '\0') {
509 		where = strstr (start, string);
510 		if (where == NULL)
511 			return false;
512 
513 		/* Has to be at beginning/end of string, and delimiter before/after */
514 		if (where != list && !is_list_delimiter (*(where - 1))) {
515 			start += strlen (string);
516 			continue;
517 		}
518 
519 		where += strlen (string);
520 		if (*where == '\0' || is_list_delimiter (*where)) {
521 			return true;
522 		}
523 		start = where;
524 	}
525 
526 	return false;
527 }
528 
529 static bool
is_module_enabled_unlocked(const char * name,p11_dict * config,int flags)530 is_module_enabled_unlocked (const char *name,
531                             p11_dict *config,
532                             int flags)
533 {
534 	const char *progname;
535 	const char *enable_in;
536 	const char *disable_in;
537 	bool enable = false;
538 
539 	enable_in = p11_dict_get (config, "enable-in");
540 	disable_in = p11_dict_get (config, "disable-in");
541 
542 	/* Defaults to enabled if neither of these are set */
543 	if (!enable_in && !disable_in)
544 		return true;
545 
546 	progname = _p11_get_progname_unlocked ();
547 	if (enable_in && disable_in)
548 		p11_message (_("module '%s' has both enable-in and disable-in options"), name);
549 	if (enable_in) {
550 		enable = (progname != NULL &&
551 			  is_string_in_list (enable_in, progname)) ||
552 			((flags & P11_KIT_MODULE_LOADED_FROM_PROXY) != 0 &&
553 			 is_string_in_list (enable_in, "p11-kit-proxy"));
554 	} else if (disable_in) {
555 		enable = (progname == NULL ||
556 			  !is_string_in_list (disable_in, progname)) &&
557 			((flags & P11_KIT_MODULE_LOADED_FROM_PROXY) == 0 ||
558 			 !is_string_in_list (disable_in, "p11-kit-proxy"));
559 	}
560 
561 	p11_debug ("%s module '%s' running in '%s'",
562 	            enable ? "enabled" : "disabled",
563 	            name,
564 	            progname ? progname : "(null)");
565 	return enable;
566 }
567 
568 static CK_RV
take_config_and_load_module_inlock(char ** name,p11_dict ** config,bool critical,bool verbose)569 take_config_and_load_module_inlock (char **name,
570                                     p11_dict **config,
571                                     bool critical,
572                                     bool verbose)
573 {
574 	const char *filename = NULL;
575 	const char *remote = NULL;
576 	char *init_reserved = NULL;
577 	CK_RV rv = CKR_OK;
578 	Module *mod;
579 
580 	assert (name);
581 	assert (*name);
582 	assert (config);
583 	assert (*config);
584 
585 	if (!is_module_enabled_unlocked (*name, *config, 0))
586 		goto out;
587 
588 	remote = p11_dict_get (*config, "remote");
589 	if (remote == NULL) {
590 		filename = p11_dict_get (*config, "module");
591 		if (filename == NULL) {
592 			p11_debug ("no module path for module, skipping: %s", *name);
593 			goto out;
594 		}
595 	}
596 
597 	if (remote != NULL) {
598 		rv = setup_module_for_remote_inlock (*name, remote, &mod);
599 		if (rv != CKR_OK)
600 			goto out;
601 
602 	} else {
603 
604 		rv = load_module_from_file_inlock (*name, filename, &mod);
605 		if (rv != CKR_OK)
606 			goto out;
607 	}
608 
609 	/*
610 	 * We support setting of CK_C_INITIALIZE_ARGS.pReserved from
611 	 * 'x-init-reserved' setting in the config. This only works with specific
612 	 * PKCS#11 modules, and is non-standard use of that field.
613 	 */
614 	init_reserved = p11_dict_get (*config, "x-init-reserved");
615 	if (init_reserved) {
616 		if (verbose) {
617 			init_reserved = strconcat (init_reserved, " verbose=yes", NULL);
618 		} else {
619 			init_reserved = strdup (init_reserved);
620 		}
621 		if (init_reserved == NULL) {
622 			rv = CKR_HOST_MEMORY;
623 			goto out;
624 		}
625 	}
626 	mod->init_args.pReserved = init_reserved;
627 
628 	/* Take ownership of these variables */
629 	p11_dict_free (mod->config);
630 	mod->config = *config;
631 	*config = NULL;
632 	free (mod->name);
633 	mod->name = *name;
634 	*name = NULL;
635 	mod->critical = critical;
636 
637 out:
638 	return rv;
639 }
640 
641 static CK_RV
load_registered_modules_unlocked(int flags)642 load_registered_modules_unlocked (int flags)
643 {
644 	p11_dictiter iter;
645 	p11_dict *configs;
646 	void *key;
647 	char *name;
648 	p11_dict *config;
649 	int mode;
650 	CK_RV rv;
651 	bool critical;
652 	bool verbose;
653 
654 	if (gl.config)
655 		return CKR_OK;
656 
657 	/* Load the global configuration files */
658 	config = _p11_conf_load_globals (p11_config_system_file, p11_config_user_file, &mode);
659 	if (config == NULL)
660 		return CKR_GENERAL_ERROR;
661 
662 	assert (mode != CONF_USER_INVALID);
663 
664 	configs = _p11_conf_load_modules (mode,
665 	                                  p11_config_package_modules,
666 	                                  p11_config_system_modules,
667 	                                  p11_config_user_modules);
668 	if (configs == NULL) {
669 		rv = CKR_GENERAL_ERROR;
670 		p11_dict_free (config);
671 		return rv;
672 	}
673 
674 	assert (gl.config == NULL);
675 	gl.config = config;
676 
677 	/*
678 	 * Now go through each config and turn it into a module. As we iterate
679 	 * we steal the values of the config.
680 	 */
681 	p11_dict_iterate (configs, &iter);
682 	while (p11_dict_next (&iter, &key, NULL)) {
683 		if (!p11_dict_steal (configs, key, (void**)&name, (void**)&config))
684 			assert_not_reached ();
685 
686 		/* Is this a critical module, should abort loading of others? */
687 		critical = _p11_conf_parse_boolean (p11_dict_get (config, "critical"), false);
688 		verbose = (flags & P11_KIT_MODULE_VERBOSE) != 0;
689 		rv = take_config_and_load_module_inlock (&name, &config, critical, verbose);
690 
691 		/*
692 		 * These variables will be cleared if ownership is transeferred
693 		 * by the above function call.
694 		 */
695 		p11_dict_free (config);
696 
697 		if (critical && rv != CKR_OK) {
698 			p11_message (_("aborting initialization because module '%s' was marked as critical"),
699 			             name);
700 			p11_dict_free (configs);
701 			free (name);
702 			return rv;
703 		}
704 
705 		free (name);
706 	}
707 
708 	p11_dict_free (configs);
709 	return CKR_OK;
710 }
711 
712 static CK_RV
initialize_module_inlock_reentrant(Module * mod,CK_C_INITIALIZE_ARGS * init_args)713 initialize_module_inlock_reentrant (Module *mod, CK_C_INITIALIZE_ARGS *init_args)
714 {
715 	CK_RV rv = CKR_OK;
716 	p11_thread_id_t self;
717 
718 	assert (mod);
719 
720 	self = p11_thread_id_self ();
721 
722 	if (mod->initialize_thread == self) {
723 		p11_message (_("p11-kit initialization called recursively"));
724 		return CKR_FUNCTION_FAILED;
725 	}
726 
727 	/*
728 	 * Increase ref first, so module doesn't get freed out from
729 	 * underneath us when the mutex is unlocked below.
730 	 */
731 	++mod->ref_count;
732 	mod->initialize_thread = self;
733 
734 	/* Change over to the module specific mutex */
735 	p11_unlock ();
736 	p11_mutex_lock (&mod->initialize_mutex);
737 
738 	if (mod->initialize_called != p11_forkid) {
739 		p11_debug ("C_Initialize: calling");
740 
741 		/* The init_args argument takes precedence over mod->init_args */
742 		if (init_args == NULL)
743 			init_args = &mod->init_args;
744 
745 		rv = mod->virt.funcs.C_Initialize (&mod->virt.funcs,
746 						   init_args);
747 
748 		p11_debug ("C_Initialize: result: %lu", rv);
749 
750 		/* Module was initialized and C_Finalize should be called */
751 		if (rv == CKR_OK)
752 			mod->initialize_called = p11_forkid;
753 		else
754 			mod->initialize_called = 0;
755 
756 		/* Module was already initialized, we don't call C_Finalize */
757 		if (rv == CKR_CRYPTOKI_ALREADY_INITIALIZED)
758 			rv = CKR_OK;
759 
760 		/* Matches the init count in finalize_module_inlock_reentrant() */
761 		if (rv == CKR_OK)
762 			mod->init_count = 0;
763 	}
764 
765 	p11_mutex_unlock (&mod->initialize_mutex);
766 	p11_lock ();
767 
768 	if (rv == CKR_OK) {
769 		/* Matches the ref count in finalize_module_inlock_reentrant() */
770 		if (mod->init_count == 0)
771 			mod->ref_count++;
772 		mod->init_count++;
773 	}
774 
775 	mod->ref_count--;
776 	mod->initialize_thread = 0;
777 	return rv;
778 }
779 
780 static CK_RV
init_globals_unlocked(void)781 init_globals_unlocked (void)
782 {
783 	static bool once = false;
784 
785 	if (!gl.modules) {
786 		gl.modules = p11_dict_new (p11_dict_direct_hash,
787 		                           p11_dict_direct_equal,
788 		                           free_module_unlocked, NULL);
789 		return_val_if_fail (gl.modules != NULL, CKR_HOST_MEMORY);
790 	}
791 
792 	if (!gl.unmanaged_by_funcs) {
793 		gl.unmanaged_by_funcs = p11_dict_new (p11_dict_direct_hash,
794 		                                      p11_dict_direct_equal,
795 		                                      NULL, NULL);
796 		return_val_if_fail (gl.unmanaged_by_funcs != NULL, CKR_HOST_MEMORY);
797 	}
798 
799 	if (!gl.managed_by_closure) {
800 		gl.managed_by_closure = p11_dict_new (p11_dict_direct_hash,
801 		                                      p11_dict_direct_equal,
802 		                                      NULL, NULL);
803 		return_val_if_fail (gl.managed_by_closure != NULL, CKR_HOST_MEMORY);
804 	}
805 
806 	if (once)
807 		return CKR_OK;
808 
809 	once = true;
810 
811 	return CKR_OK;
812 }
813 
814 static void
free_modules_when_no_refs_unlocked(void)815 free_modules_when_no_refs_unlocked (void)
816 {
817 	if (gl.modules) {
818 		Module *mod;
819 		p11_dictiter iter;
820 
821 		/* Check if any modules have a ref count */
822 		p11_dict_iterate (gl.modules, &iter);
823 		while (p11_dict_next (&iter, (void **)&mod, NULL)) {
824 			if (mod->ref_count)
825 				return;
826 		}
827 	}
828 
829 	p11_dict_free (gl.unmanaged_by_funcs);
830 	gl.unmanaged_by_funcs = NULL;
831 
832 	p11_dict_free (gl.managed_by_closure);
833 	gl.managed_by_closure = NULL;
834 
835 	p11_dict_free (gl.modules);
836 	gl.modules = NULL;
837 
838 	p11_dict_free (gl.config);
839 	gl.config = NULL;
840 }
841 
842 static CK_RV
finalize_module_inlock_reentrant(Module * mod)843 finalize_module_inlock_reentrant (Module *mod)
844 {
845 	assert (mod);
846 
847 	/*
848 	 * We leave module info around until all are finalized
849 	 * so we can encounter these zombie Module structures.
850 	 */
851 	if (mod->ref_count == 0)
852 		return CKR_ARGUMENTS_BAD;
853 
854 	if (--mod->init_count > 0)
855 		return CKR_OK;
856 
857 	/*
858 	 * Because of the mutex unlock below, we temporarily increase
859 	 * the ref count. This prevents module from being freed out
860 	 * from ounder us.
861 	 */
862 
863 	p11_unlock ();
864 	p11_mutex_lock (&mod->initialize_mutex);
865 
866 	if (mod->initialize_called == p11_forkid) {
867 		mod->virt.funcs.C_Finalize (&mod->virt.funcs, NULL);
868 		mod->initialize_called = 0;
869 	}
870 
871 	p11_mutex_unlock (&mod->initialize_mutex);
872 	p11_lock ();
873 
874 	/* Match the ref increment in initialize_module_inlock_reentrant() */
875 	mod->ref_count--;
876 
877 	free_modules_when_no_refs_unlocked ();
878 	return CKR_OK;
879 }
880 
881 static CK_RV
initialize_registered_inlock_reentrant(void)882 initialize_registered_inlock_reentrant (void)
883 {
884 	p11_dictiter iter;
885 	Module *mod;
886 	CK_RV rv;
887 
888 	/*
889 	 * This is only called by deprecated code. The caller expects all
890 	 * configured and enabled modules to be initialized.
891 	 */
892 
893 	rv = init_globals_unlocked ();
894 	if (rv != CKR_OK)
895 		return rv;
896 
897 	rv = load_registered_modules_unlocked (0);
898 	if (rv == CKR_OK) {
899 		p11_dict_iterate (gl.unmanaged_by_funcs, &iter);
900 		while (rv == CKR_OK && p11_dict_next (&iter, NULL, (void **)&mod)) {
901 
902 			/* Skip all modules that aren't registered or enabled */
903 			if (mod->name == NULL || !is_module_enabled_unlocked (mod->name, mod->config, 0))
904 				continue;
905 
906 			rv = initialize_module_inlock_reentrant (mod, NULL);
907 			if (rv != CKR_OK) {
908 				if (mod->critical) {
909 					p11_message (_("initialization of critical module '%s' failed: %s"),
910 					             mod->name, p11_kit_strerror (rv));
911 				} else {
912 					p11_message (_("skipping module '%s' whose initialization failed: %s"),
913 					             mod->name, p11_kit_strerror (rv));
914 					rv = CKR_OK;
915 				}
916 			}
917 		}
918 	}
919 
920 	return rv;
921 }
922 
923 static Module *
module_for_functions_inlock(CK_FUNCTION_LIST * funcs)924 module_for_functions_inlock (CK_FUNCTION_LIST *funcs)
925 {
926 	if (p11_virtual_is_wrapper (funcs))
927 		return p11_dict_get (gl.managed_by_closure, funcs);
928 	else
929 		return p11_dict_get (gl.unmanaged_by_funcs, funcs);
930 }
931 
932 static CK_FUNCTION_LIST *
unmanaged_for_module_inlock(Module * mod)933 unmanaged_for_module_inlock (Module *mod)
934 {
935 	CK_FUNCTION_LIST *funcs;
936 
937 	funcs = mod->virt.lower_module;
938 	if (p11_dict_get (gl.unmanaged_by_funcs, funcs) == mod)
939 		return funcs;
940 
941 	return NULL;
942 }
943 
944 /**
945  * p11_kit_initialize_registered:
946  *
947  * Initialize all the registered PKCS\#11 modules.
948  *
949  * If this is the first time this function is called multiple times
950  * consecutively within a single process, then it merely increments an
951  * initialization reference count for each of these modules.
952  *
953  * Use p11_kit_finalize_registered() to finalize these registered modules once
954  * the caller is done with them.
955  *
956  * If this function fails, then an error message will be available via the
957  * p11_kit_message() function.
958  *
959  * Deprecated: Since: 0.19.0: Use p11_kit_modules_load() instead.
960  *
961  * Returns: CKR_OK if the initialization succeeded, or an error code.
962  */
963 CK_RV
p11_kit_initialize_registered(void)964 p11_kit_initialize_registered (void)
965 {
966 	CK_RV rv;
967 
968 	p11_library_init_once ();
969 
970 	/* WARNING: This function must be reentrant */
971 	p11_debug ("in");
972 
973 	p11_lock ();
974 
975 		p11_message_clear ();
976 
977 		/* WARNING: Reentrancy can occur here */
978 		rv = initialize_registered_inlock_reentrant ();
979 
980 		_p11_kit_default_message (rv);
981 
982 	p11_unlock ();
983 
984 	/* Cleanup any partial initialization */
985 	if (rv != CKR_OK)
986 		p11_kit_finalize_registered ();
987 
988 	p11_debug ("out: %lu", rv);
989 	return rv;
990 }
991 
992 static CK_RV
finalize_registered_inlock_reentrant(void)993 finalize_registered_inlock_reentrant (void)
994 {
995 	Module *mod;
996 	p11_dictiter iter;
997 	Module **to_finalize;
998 	int i, count;
999 
1000 	/*
1001 	 * This is only called from deprecated code. The caller expects all
1002 	 * modules initialized earlier to be finalized (once). If non-critical
1003 	 * modules failed to initialize, then it is not possible to completely
1004 	 * guarantee the internal state.
1005 	 */
1006 
1007 	if (!gl.modules)
1008 		return CKR_CRYPTOKI_NOT_INITIALIZED;
1009 
1010 	/* WARNING: This function must be reentrant */
1011 
1012 	to_finalize = calloc (p11_dict_size (gl.unmanaged_by_funcs) + 1, sizeof (Module *));
1013 	if (!to_finalize)
1014 		return CKR_HOST_MEMORY;
1015 
1016 	count = 0;
1017 	p11_dict_iterate (gl.unmanaged_by_funcs, &iter);
1018 	while (p11_dict_next (&iter, NULL, (void **)&mod)) {
1019 
1020 		/* Skip all modules that aren't registered */
1021 		if (mod->name && mod->init_count)
1022 			to_finalize[count++] = mod;
1023 	}
1024 
1025 	p11_debug ("finalizing %d modules", count);
1026 
1027 	for (i = 0; i < count; ++i) {
1028 		/* WARNING: Reentrant calls can occur here */
1029 		finalize_module_inlock_reentrant (to_finalize[i]);
1030 	}
1031 
1032 	free (to_finalize);
1033 
1034 	/* In case nothing loaded, free up internal memory */
1035 	if (count == 0)
1036 		free_modules_when_no_refs_unlocked ();
1037 
1038 	return CKR_OK;
1039 }
1040 
1041 /**
1042  * p11_kit_finalize_registered:
1043  *
1044  * Finalize all the registered PKCS\#11 modules. These should have been
1045  * initialized with p11_kit_initialize_registered().
1046  *
1047  * If p11_kit_initialize_registered() has been called more than once in this
1048  * process, then this function must be called the same number of times before
1049  * actual finalization will occur.
1050  *
1051  * If this function fails, then an error message will be available via the
1052  * p11_kit_message() function.
1053  *
1054  * Deprecated: Since 0.19.0: Use p11_kit_modules_release() instead.
1055  *
1056  * Returns: CKR_OK if the finalization succeeded, or an error code.
1057  */
1058 
1059 CK_RV
p11_kit_finalize_registered(void)1060 p11_kit_finalize_registered (void)
1061 {
1062 	CK_RV rv;
1063 
1064 	p11_library_init_once ();
1065 
1066 	/* WARNING: This function must be reentrant */
1067 	p11_debug ("in");
1068 
1069 	p11_lock ();
1070 
1071 		p11_message_clear ();
1072 
1073 		/* WARNING: Reentrant calls can occur here */
1074 		rv = finalize_registered_inlock_reentrant ();
1075 
1076 		_p11_kit_default_message (rv);
1077 
1078 	p11_unlock ();
1079 
1080 	p11_debug ("out: %lu", rv);
1081 	return rv;
1082 }
1083 
1084 static int
compar_priority(const void * one,const void * two)1085 compar_priority (const void *one,
1086                  const void *two)
1087 {
1088 	CK_FUNCTION_LIST_PTR f1 = *((CK_FUNCTION_LIST_PTR *)one);
1089 	CK_FUNCTION_LIST_PTR f2 = *((CK_FUNCTION_LIST_PTR *)two);
1090 	Module *m1, *m2;
1091 	const char *v1, *v2;
1092 	int o1, o2;
1093 
1094 	m1 = module_for_functions_inlock (f1);
1095 	m2 = module_for_functions_inlock (f2);
1096 	assert (m1 != NULL && m2 != NULL);
1097 
1098 	v1 = p11_dict_get (m1->config, "priority");
1099 	v2 = p11_dict_get (m2->config, "priority");
1100 
1101 	o1 = atoi (v1 ? v1 : "0");
1102 	o2 = atoi (v2 ? v2 : "0");
1103 
1104 	/* Priority is in descending order, highest first */
1105 	if (o1 != o2)
1106 		return o1 > o2 ? -1 : 1;
1107 
1108 	/*
1109 	 * Otherwise use the names alphabetically in ascending order. This
1110 	 * is really just to provide consistency between various loads of
1111 	 * the configuration.
1112 	 */
1113 	if (m1->name == m2->name)
1114 		return 0;
1115 	if (!m1->name)
1116 		return -1;
1117 	if (!m2->name)
1118 		return 1;
1119 	return strcmp (m1->name, m2->name);
1120 }
1121 
1122 static void
sort_modules_by_priority(CK_FUNCTION_LIST_PTR * modules,int count)1123 sort_modules_by_priority (CK_FUNCTION_LIST_PTR *modules,
1124                           int count)
1125 {
1126 	qsort (modules, count, sizeof (CK_FUNCTION_LIST_PTR), compar_priority);
1127 }
1128 
1129 static CK_FUNCTION_LIST **
list_registered_modules_inlock(void)1130 list_registered_modules_inlock (void)
1131 {
1132 	CK_FUNCTION_LIST **result = NULL;
1133 	CK_FUNCTION_LIST *funcs;
1134 	Module *mod;
1135 	p11_dictiter iter;
1136 	int i = 0;
1137 
1138 	/*
1139 	 * This is only called by deprecated code. The caller expects to get
1140 	 * a list of all registered enabled modules that have been initialized.
1141 	 */
1142 
1143 	if (gl.unmanaged_by_funcs) {
1144 		result = calloc (p11_dict_size (gl.unmanaged_by_funcs) + 1,
1145 		                 sizeof (CK_FUNCTION_LIST *));
1146 		return_val_if_fail (result != NULL, NULL);
1147 
1148 		p11_dict_iterate (gl.unmanaged_by_funcs, &iter);
1149 		while (p11_dict_next (&iter, (void **)&funcs, (void **)&mod)) {
1150 
1151 			/*
1152 			 * We don't include unreferenced modules. We don't include
1153 			 * modules that have been initialized but aren't in the
1154 			 * registry. These have a NULL name.
1155 			 *
1156 			 * In addition we check again that the module isn't disabled
1157 			 * using enable-in or disable-in. This is because a caller
1158 			 * can change the progname we recognize the process as after
1159 			 * having initialized. This is a corner case, but want to make
1160 			 * sure to cover it.
1161 			 */
1162 			if (mod->ref_count && mod->name && mod->init_count &&
1163 			    is_module_enabled_unlocked (mod->name, mod->config, 0)) {
1164 				result[i++] = funcs;
1165 			}
1166 		}
1167 
1168 		sort_modules_by_priority (result, i);
1169 	}
1170 
1171 	return result;
1172 }
1173 
1174 /**
1175  * p11_kit_registered_modules:
1176  *
1177  * Get a list of all the registered PKCS\#11 modules. This list will be valid
1178  * once the p11_kit_initialize_registered() function has been called.
1179  *
1180  * The returned value is a <code>NULL</code> terminated array of
1181  * <code>CK_FUNCTION_LIST_PTR</code> pointers.
1182  *
1183  * The returned modules are unmanaged.
1184  *
1185  * Deprecated: Since 0.19.0: Use p11_kit_modules_load() instead.
1186  *
1187  * Returns: A list of all the registered modules. Use the free() function to
1188  * free the list.
1189  */
1190 CK_FUNCTION_LIST_PTR_PTR
p11_kit_registered_modules(void)1191 p11_kit_registered_modules (void)
1192 {
1193 	CK_FUNCTION_LIST_PTR_PTR result;
1194 
1195 	p11_library_init_once ();
1196 
1197 	p11_lock ();
1198 
1199 		p11_message_clear ();
1200 
1201 		result = list_registered_modules_inlock ();
1202 
1203 	p11_unlock ();
1204 
1205 	return result;
1206 }
1207 
1208 /**
1209  * p11_kit_registered_module_to_name:
1210  * @module: pointer to a registered module
1211  *
1212  * Get the name of a registered PKCS\#11 module.
1213  *
1214  * You can use p11_kit_registered_modules() to get a list of all the registered
1215  * modules. This name is specified by the registered module configuration.
1216  *
1217  * Deprecated: Since 0.19.0: Use p11_kit_module_get_name() instead.
1218  *
1219  * Returns: A newly allocated string containing the module name, or
1220  *     <code>NULL</code> if no such registered module exists. Use free() to
1221  *     free this string.
1222  */
1223 char*
p11_kit_registered_module_to_name(CK_FUNCTION_LIST_PTR module)1224 p11_kit_registered_module_to_name (CK_FUNCTION_LIST_PTR module)
1225 {
1226 	return_val_if_fail (module != NULL, NULL);
1227 	return p11_kit_module_get_name (module);
1228 }
1229 
1230 /**
1231  * p11_kit_module_get_name:
1232  * @module: pointer to a loaded module
1233  *
1234  * Get the configured name of the PKCS\#11 module.
1235  *
1236  * Configured modules are loaded by p11_kit_modules_load(). The module
1237  * passed to this function can be either managed or unmanaged. Non
1238  * configured modules will return %NULL.
1239  *
1240  * Use free() to release the return value when you're done with it.
1241  *
1242  * Returns: a newly allocated string containing the module name, or
1243  *     <code>NULL</code> if the module is not a configured module
1244  */
1245 char *
p11_kit_module_get_name(CK_FUNCTION_LIST * module)1246 p11_kit_module_get_name (CK_FUNCTION_LIST *module)
1247 {
1248 	Module *mod;
1249 	char *name = NULL;
1250 
1251 	return_val_if_fail (module != NULL, NULL);
1252 
1253 	p11_library_init_once ();
1254 
1255 	p11_lock ();
1256 
1257 		p11_message_clear ();
1258 
1259 		if (gl.modules) {
1260 			mod = module_for_functions_inlock (module);
1261 			if (mod && mod->name)
1262 				name = strdup (mod->name);
1263 		}
1264 
1265 	p11_unlock ();
1266 
1267 	return name;
1268 }
1269 
1270 /**
1271  * p11_kit_module_get_filename:
1272  * @module: pointer to a loaded module
1273  *
1274  * Get the configured name of the PKCS\#11 module.
1275  *
1276  * Configured modules are loaded by p11_kit_modules_load(). The module
1277  * passed to this function can be either managed or unmanaged. Non
1278  * configured modules will return %NULL.
1279  *
1280  * Use free() to release the return value when you're done with it.
1281  *
1282  * Returns: a newly allocated string containing the module name, or
1283  *     <code>NULL</code> if the module is not a configured module
1284  */
1285 char *
p11_kit_module_get_filename(CK_FUNCTION_LIST * module)1286 p11_kit_module_get_filename (CK_FUNCTION_LIST *module)
1287 {
1288 	Module *mod;
1289 	char *name = NULL;
1290 
1291 	return_val_if_fail (module != NULL, NULL);
1292 
1293 	p11_library_init_once ();
1294 
1295 	p11_lock ();
1296 
1297 		p11_message_clear ();
1298 
1299 		if (gl.modules) {
1300 			mod = module_for_functions_inlock (module);
1301 			if (mod && mod->filename)
1302 				name = strdup (mod->filename);
1303 		}
1304 
1305 	p11_unlock ();
1306 
1307 	return name;
1308 }
1309 
1310 static const char *
module_get_option_inlock(Module * mod,const char * option)1311 module_get_option_inlock (Module *mod,
1312                           const char *option)
1313 {
1314 	p11_dict *config;
1315 
1316 	if (mod == NULL)
1317 		config = gl.config;
1318 	else
1319 		config = mod->config;
1320 	if (config == NULL)
1321 		return NULL;
1322 	return p11_dict_get (config, option);
1323 }
1324 
1325 /**
1326  * p11_kit_module_get_flags:
1327  * @module: the module
1328  *
1329  * Get the flags for this module.
1330  *
1331  * The %P11_KIT_MODULE_UNMANAGED flag will be set if the module is not
1332  * managed by p11-kit. It is a raw PKCS\#11 module function list.
1333  *
1334  * The %P11_KIT_MODULE_CRITICAL flag will be set if the module is configured
1335  * to be critical, and not be skipped over if it fails to initialize or
1336  * load. This flag is also set for modules that are not configured, but have
1337  * been loaded in another fashion.
1338  *
1339  * Returns: the flags for the module
1340  */
1341 int
p11_kit_module_get_flags(CK_FUNCTION_LIST * module)1342 p11_kit_module_get_flags (CK_FUNCTION_LIST *module)
1343 {
1344 	const char *trusted;
1345 	Module *mod;
1346 	int flags = 0;
1347 
1348 	return_val_if_fail (module != NULL, 0);
1349 
1350 	p11_library_init_once ();
1351 
1352 	p11_lock ();
1353 
1354 		p11_message_clear ();
1355 
1356 		if (gl.modules) {
1357 			if (p11_virtual_is_wrapper (module)) {
1358 				mod = p11_dict_get (gl.managed_by_closure, module);
1359 			} else {
1360 				flags |= P11_KIT_MODULE_UNMANAGED;
1361 				mod = p11_dict_get (gl.unmanaged_by_funcs, module);
1362 			}
1363 			if (!mod || mod->critical)
1364 				flags |= P11_KIT_MODULE_CRITICAL;
1365 			if (mod) {
1366 				trusted = module_get_option_inlock (mod, "trust-policy");
1367 				if (_p11_conf_parse_boolean (trusted, false))
1368 					flags |= P11_KIT_MODULE_TRUSTED;
1369 			}
1370 		}
1371 
1372 	p11_unlock ();
1373 
1374 	return flags;
1375 }
1376 
1377 /**
1378  * p11_kit_registered_name_to_module:
1379  * @name: name of a registered module
1380  *
1381  * Lookup a registered PKCS\#11 module by its name. This name is specified by
1382  * the registered module configuration.
1383  *
1384  * Deprecated: Since 0.19.0: Use p11_kit_module_for_name() instead.
1385  *
1386  * Returns: a pointer to a PKCS\#11 module, or <code>NULL</code> if this name was
1387  *     not found.
1388  */
1389 CK_FUNCTION_LIST_PTR
p11_kit_registered_name_to_module(const char * name)1390 p11_kit_registered_name_to_module (const char *name)
1391 {
1392 	CK_FUNCTION_LIST_PTR module = NULL;
1393 	CK_FUNCTION_LIST_PTR funcs;
1394 	p11_dictiter iter;
1395 	Module *mod;
1396 
1397 	return_val_if_fail (name != NULL, NULL);
1398 
1399 	p11_lock ();
1400 
1401 	p11_message_clear ();
1402 
1403 	if (gl.modules) {
1404 
1405 		assert (name);
1406 
1407 		p11_dict_iterate (gl.unmanaged_by_funcs, &iter);
1408 		while (p11_dict_next (&iter, (void **)&funcs, (void **)&mod)) {
1409 			if (mod->ref_count && mod->name && strcmp (name, mod->name) == 0) {
1410 				module = funcs;
1411 				break;
1412 			}
1413 		}
1414 	}
1415 
1416 	p11_unlock ();
1417 
1418 	return module;
1419 }
1420 
1421 /**
1422  * p11_kit_module_for_name:
1423  * @modules: a list of modules to look through
1424  * @name: the name of the module to find
1425  *
1426  * Look through the list of @modules and return the module whose @name
1427  * matches.
1428  *
1429  * Only configured modules have names. Configured modules are loaded by
1430  * p11_kit_modules_load(). The module passed to this function can be either
1431  * managed or unmanaged.
1432  *
1433  * The return value is not copied or duplicated in anyway. It is still
1434  * 'owned' by the @modules list.
1435  *
1436  * Returns: the module which matches the name, or %NULL if no match.
1437  */
1438 CK_FUNCTION_LIST *
p11_kit_module_for_name(CK_FUNCTION_LIST ** modules,const char * name)1439 p11_kit_module_for_name (CK_FUNCTION_LIST **modules,
1440                          const char *name)
1441 {
1442 	CK_FUNCTION_LIST *ret = NULL;
1443 	Module *mod;
1444 	int i;
1445 
1446 	return_val_if_fail (name != NULL, NULL);
1447 
1448 	if (!modules)
1449 		return NULL;
1450 
1451 	p11_library_init_once ();
1452 
1453 	p11_lock ();
1454 
1455 		p11_message_clear ();
1456 
1457 		for (i = 0; gl.modules && modules[i] != NULL; i++) {
1458 			mod = module_for_functions_inlock (modules[i]);
1459 			if (mod && mod->name && strcmp (mod->name, name) == 0) {
1460 				ret = modules[i];
1461 				break;
1462 			}
1463 		}
1464 
1465 	p11_unlock ();
1466 
1467 	return ret;
1468 }
1469 
1470 /**
1471  * p11_kit_registered_option:
1472  * @module: a pointer to a registered module
1473  * @field: the name of the option to lookup.
1474  *
1475  * Lookup a configured option for a registered PKCS\#11 module. If a
1476  * <code>NULL</code> module argument is specified, then this will lookup
1477  * the configuration option in the global config file.
1478  *
1479  * Deprecated: Since 0.19.0: Use p11_kit_config_option() instead.
1480  *
1481  * Returns: A newly allocated string containing the option value, or
1482  *     <code>NULL</code> if the registered module or the option were not found.
1483  *     Use free() to free the returned string.
1484  */
1485 char*
p11_kit_registered_option(CK_FUNCTION_LIST_PTR module,const char * field)1486 p11_kit_registered_option (CK_FUNCTION_LIST_PTR module, const char *field)
1487 {
1488 	Module *mod = NULL;
1489 	char *option = NULL;
1490 	const char *value;
1491 
1492 	return_val_if_fail (field != NULL, NULL);
1493 
1494 	p11_library_init_once ();
1495 
1496 	p11_lock ();
1497 
1498 		p11_message_clear ();
1499 
1500 		if (module == NULL)
1501 			mod = NULL;
1502 		else
1503 			mod = gl.unmanaged_by_funcs ? p11_dict_get (gl.unmanaged_by_funcs, module) : NULL;
1504 
1505 		value = module_get_option_inlock (mod, field);
1506 		if (value)
1507 			option = strdup (value);
1508 
1509 	p11_unlock ();
1510 
1511 	return option;
1512 }
1513 
1514 /**
1515  * p11_kit_config_option:
1516  * @module: the module to retrieve the option for, or %NULL for global options
1517  * @option: the option to retrieve
1518  *
1519  * Retrieve the value for a configured option.
1520  *
1521  * If @module is %NULL, then the global option with the given name will
1522  * be retrieved. Otherwise @module should point to a configured loaded module.
1523  * If no such @option or configured @module exists, then %NULL will be returned.
1524  *
1525  * Use free() to release the returned value.
1526  *
1527  * Returns: the option value or %NULL
1528  */
1529 char *
p11_kit_config_option(CK_FUNCTION_LIST * module,const char * option)1530 p11_kit_config_option (CK_FUNCTION_LIST *module,
1531                        const char *option)
1532 {
1533 	Module *mod = NULL;
1534 	const char *value = NULL;
1535 	char *ret = NULL;
1536 
1537 	return_val_if_fail (option != NULL, NULL);
1538 
1539 	p11_library_init_once ();
1540 
1541 	p11_lock ();
1542 
1543 		p11_message_clear ();
1544 
1545 		if (gl.modules) {
1546 			if (module != NULL) {
1547 				mod = module_for_functions_inlock (module);
1548 				if (mod == NULL)
1549 					goto cleanup;
1550 			}
1551 
1552 			value = module_get_option_inlock (mod, option);
1553 			if (value)
1554 				ret = strdup (value);
1555 		}
1556 
1557 
1558 cleanup:
1559 	p11_unlock ();
1560 	return ret;
1561 }
1562 
1563 typedef struct {
1564 	p11_virtual virt;
1565 	Module *mod;
1566 	unsigned int initialized;
1567 	p11_dict *sessions;
1568 } Managed;
1569 
1570 static CK_RV
managed_C_Initialize(CK_X_FUNCTION_LIST * self,CK_VOID_PTR init_args)1571 managed_C_Initialize (CK_X_FUNCTION_LIST *self,
1572                       CK_VOID_PTR init_args)
1573 {
1574 	Managed *managed = ((Managed *)self);
1575 	p11_dict *sessions;
1576 	CK_RV rv;
1577 
1578 	p11_debug ("in");
1579 	p11_lock ();
1580 
1581 	if (managed->initialized == p11_forkid) {
1582 		rv = CKR_CRYPTOKI_ALREADY_INITIALIZED;
1583 
1584 	} else {
1585 		sessions = p11_dict_new (p11_dict_ulongptr_hash,
1586 		                         p11_dict_ulongptr_equal,
1587 		                         free, free);
1588 		if (!sessions)
1589 			rv = CKR_HOST_MEMORY;
1590 		else
1591 			rv = initialize_module_inlock_reentrant (managed->mod, init_args);
1592 		if (rv == CKR_OK) {
1593 			if (managed->sessions)
1594 				p11_dict_free (managed->sessions);
1595 			managed->sessions = sessions;
1596 			managed->initialized = p11_forkid;
1597 		} else {
1598 			p11_dict_free (sessions);
1599 		}
1600 	}
1601 
1602 	p11_unlock ();
1603 	p11_debug ("out: %lu", rv);
1604 
1605 	return rv;
1606 }
1607 
1608 static CK_RV
managed_track_session_inlock(p11_dict * sessions,CK_SLOT_ID slot_id,CK_SESSION_HANDLE session)1609 managed_track_session_inlock (p11_dict *sessions,
1610                               CK_SLOT_ID slot_id,
1611                               CK_SESSION_HANDLE session)
1612 {
1613 	void *key;
1614 	void *value;
1615 
1616 	key = memdup (&session, sizeof (CK_SESSION_HANDLE));
1617 	return_val_if_fail (key != NULL, CKR_HOST_MEMORY);
1618 
1619 	value = memdup (&slot_id, sizeof (CK_SESSION_HANDLE));
1620 	return_val_if_fail (value != NULL, CKR_HOST_MEMORY);
1621 
1622 	if (!p11_dict_set (sessions, key, value))
1623 		return_val_if_reached (CKR_HOST_MEMORY);
1624 
1625 	return CKR_OK;
1626 }
1627 
1628 static void
managed_untrack_session_inlock(p11_dict * sessions,CK_SESSION_HANDLE session)1629 managed_untrack_session_inlock (p11_dict *sessions,
1630                                 CK_SESSION_HANDLE session)
1631 {
1632 	p11_dict_remove (sessions, &session);
1633 }
1634 
1635 static CK_SESSION_HANDLE *
managed_steal_sessions_inlock(p11_dict * sessions,bool matching_slot_id,CK_SLOT_ID slot_id,int * count)1636 managed_steal_sessions_inlock (p11_dict *sessions,
1637                         bool matching_slot_id,
1638                         CK_SLOT_ID slot_id,
1639                         int *count)
1640 {
1641 	CK_SESSION_HANDLE *stolen;
1642 	CK_SESSION_HANDLE *key;
1643 	CK_SLOT_ID *value;
1644 	p11_dictiter iter;
1645 	int at, i;
1646 
1647 	assert (sessions != NULL);
1648 	assert (count != NULL);
1649 
1650 	stolen = calloc (p11_dict_size (sessions) + 1, sizeof (CK_SESSION_HANDLE));
1651 	return_val_if_fail (stolen != NULL, NULL);
1652 
1653 	at = 0;
1654 	p11_dict_iterate (sessions, &iter);
1655 	while (p11_dict_next (&iter, (void **)&key, (void **)&value)) {
1656 		if (!matching_slot_id || slot_id == *value)
1657 			stolen[at++] = *key;
1658 	}
1659 
1660 	/* Removed them all, clear the whole array */
1661 	if (at == p11_dict_size (sessions)) {
1662 		p11_dict_clear (sessions);
1663 
1664 	/* Only removed some, go through and remove those */
1665 	} else {
1666 		for (i = 0; i < at; i++) {
1667 			if (!p11_dict_remove (sessions, stolen + i))
1668 				assert_not_reached ();
1669 		}
1670 	}
1671 
1672 	*count = at;
1673 	return stolen;
1674 }
1675 
1676 static void
managed_close_sessions(CK_X_FUNCTION_LIST * funcs,CK_SESSION_HANDLE * stolen,int count)1677 managed_close_sessions (CK_X_FUNCTION_LIST *funcs,
1678                         CK_SESSION_HANDLE *stolen,
1679                         int count)
1680 {
1681 	CK_RV rv;
1682 	int i;
1683 
1684 	for (i = 0; i < count; i++) {
1685 		rv = funcs->C_CloseSession (funcs, stolen[i]);
1686 		if (rv != CKR_OK)
1687 			p11_message (_("couldn't close session: %s"), p11_kit_strerror (rv));
1688 	}
1689 }
1690 
1691 static CK_RV
managed_C_Finalize(CK_X_FUNCTION_LIST * self,CK_VOID_PTR reserved)1692 managed_C_Finalize (CK_X_FUNCTION_LIST *self,
1693                     CK_VOID_PTR reserved)
1694 {
1695 	Managed *managed = ((Managed *)self);
1696 	CK_SESSION_HANDLE *sessions;
1697 	int count;
1698 	CK_RV rv;
1699 
1700 	p11_debug ("in");
1701 	p11_lock ();
1702 
1703 	if (managed->initialized == 0) {
1704 		rv = CKR_CRYPTOKI_NOT_INITIALIZED;
1705 
1706 	} else if (managed->initialized != p11_forkid) {
1707 		/*
1708 		 * In theory we should be returning CKR_CRYPTOKI_NOT_INITIALIZED here
1709 		 * but enough callers are not completely aware of their forking.
1710 		 * So we just clean up any state we have, rather than forcing callers
1711 		 * to initialize just to finalize.
1712 		 */
1713 		p11_debug ("finalizing module in wrong process, skipping C_Finalize");
1714 		rv = CKR_OK;
1715 
1716 	} else {
1717 		sessions = managed_steal_sessions_inlock (managed->sessions, false, 0, &count);
1718 
1719 		if (sessions && count) {
1720 			/* WARNING: reentrancy can occur here */
1721 			p11_unlock ();
1722 			managed_close_sessions (&managed->mod->virt.funcs, sessions, count);
1723 			p11_lock ();
1724 		}
1725 
1726 		free (sessions);
1727 
1728 		/* WARNING: reentrancy can occur here */
1729 		rv = finalize_module_inlock_reentrant (managed->mod);
1730 	}
1731 
1732 	if (rv == CKR_OK) {
1733 		managed->initialized = 0;
1734 		p11_dict_free (managed->sessions);
1735 		managed->sessions = NULL;
1736 	}
1737 
1738 	p11_unlock ();
1739 	p11_debug ("out: %lu", rv);
1740 
1741 	return rv;
1742 }
1743 
1744 static CK_RV
managed_C_OpenSession(CK_X_FUNCTION_LIST * self,CK_SLOT_ID slot_id,CK_FLAGS flags,CK_VOID_PTR application,CK_NOTIFY notify,CK_SESSION_HANDLE_PTR session)1745 managed_C_OpenSession (CK_X_FUNCTION_LIST *self,
1746                        CK_SLOT_ID slot_id,
1747                        CK_FLAGS flags,
1748                        CK_VOID_PTR application,
1749                        CK_NOTIFY notify,
1750                        CK_SESSION_HANDLE_PTR session)
1751 {
1752 	Managed *managed = ((Managed *)self);
1753 	CK_RV rv;
1754 
1755 	return_val_if_fail (session != NULL, CKR_ARGUMENTS_BAD);
1756 
1757 	self = &managed->mod->virt.funcs;
1758 	rv = self->C_OpenSession (self, slot_id, flags, application, notify, session);
1759 
1760 	if (rv == CKR_OK) {
1761 		p11_lock ();
1762 		rv = managed_track_session_inlock (managed->sessions, slot_id, *session);
1763 		p11_unlock ();
1764 	}
1765 
1766 	return rv;
1767 }
1768 
1769 static CK_RV
managed_C_CloseSession(CK_X_FUNCTION_LIST * self,CK_SESSION_HANDLE session)1770 managed_C_CloseSession (CK_X_FUNCTION_LIST *self,
1771                         CK_SESSION_HANDLE session)
1772 {
1773 	Managed *managed = ((Managed *)self);
1774 	CK_RV rv;
1775 
1776 	self = &managed->mod->virt.funcs;
1777 	rv = self->C_CloseSession (self, session);
1778 
1779 	if (rv == CKR_OK) {
1780 		p11_lock ();
1781 		managed_untrack_session_inlock (managed->sessions, session);
1782 		p11_unlock ();
1783 	}
1784 
1785 	return rv;
1786 }
1787 
1788 static CK_RV
managed_C_CloseAllSessions(CK_X_FUNCTION_LIST * self,CK_SLOT_ID slot_id)1789 managed_C_CloseAllSessions (CK_X_FUNCTION_LIST *self,
1790                             CK_SLOT_ID slot_id)
1791 {
1792 	Managed *managed = ((Managed *)self);
1793 	CK_SESSION_HANDLE *stolen;
1794 	int count;
1795 
1796 	p11_lock ();
1797 	stolen = managed_steal_sessions_inlock (managed->sessions, true, slot_id, &count);
1798 	p11_unlock ();
1799 
1800 	self = &managed->mod->virt.funcs;
1801 	managed_close_sessions (self, stolen, count);
1802 	if (stolen) {
1803 		free (stolen);
1804 		return CKR_OK;
1805 	} else {
1806 		return CKR_GENERAL_ERROR;
1807 	}
1808 
1809 }
1810 
1811 static void
managed_free_inlock(void * data)1812 managed_free_inlock (void *data)
1813 {
1814 	Managed *managed = data;
1815 	managed->mod->ref_count--;
1816 	free (managed);
1817 }
1818 
1819 static p11_virtual *
managed_create_inlock(Module * mod)1820 managed_create_inlock (Module *mod)
1821 {
1822 	Managed *managed;
1823 
1824 	managed = calloc (1, sizeof (Managed));
1825 	return_val_if_fail (managed != NULL, NULL);
1826 
1827 	p11_virtual_init (&managed->virt, &p11_virtual_stack,
1828 	                  &mod->virt, NULL);
1829 	managed->virt.funcs.C_Initialize = managed_C_Initialize;
1830 	managed->virt.funcs.C_Finalize = managed_C_Finalize;
1831 	managed->virt.funcs.C_CloseAllSessions = managed_C_CloseAllSessions;
1832 	managed->virt.funcs.C_CloseSession = managed_C_CloseSession;
1833 	managed->virt.funcs.C_OpenSession = managed_C_OpenSession;
1834 	managed->mod = mod;
1835 	mod->ref_count++;
1836 
1837 	return &managed->virt;
1838 }
1839 
1840 static bool
lookup_managed_option(Module * mod,bool supported,const char * option,bool def_value)1841 lookup_managed_option (Module *mod,
1842                        bool supported,
1843                        const char *option,
1844                        bool def_value)
1845 {
1846 	const char *string;
1847 	bool value;
1848 
1849 	string = module_get_option_inlock (NULL, option);
1850 	if (!string)
1851 		string = module_get_option_inlock (mod, option);
1852 	if (!string) {
1853 		if (!supported)
1854 			return false;
1855 		return def_value;
1856 	}
1857 
1858 	value = _p11_conf_parse_boolean (string, def_value);
1859 
1860 	if (!supported && value != supported) {
1861 	  /*
1862 	   * This is because the module is running in unmanaged mode, so turn off the
1863 	   */
1864 	  p11_message (_("the '%s' option for module '%s' is only supported for managed modules"),
1865 		       option, mod->name);
1866 	}
1867 
1868 	return value;
1869 }
1870 
1871 static CK_RV
release_module_inlock_rentrant(CK_FUNCTION_LIST * module,const char * caller_func)1872 release_module_inlock_rentrant (CK_FUNCTION_LIST *module,
1873                                 const char *caller_func)
1874 {
1875 	Module *mod;
1876 
1877 	assert (module != NULL);
1878 
1879 	/* See if a managed module, and finalize if so */
1880 	if (p11_virtual_is_wrapper (module)) {
1881 		mod = p11_dict_get (gl.managed_by_closure, module);
1882 		if (mod != NULL) {
1883 			if (!p11_dict_remove (gl.managed_by_closure, module))
1884 				assert_not_reached ();
1885 			p11_virtual_unwrap (module);
1886 		}
1887 
1888 	/* If an unmanaged module then caller should have finalized */
1889 	} else {
1890 		mod = p11_dict_get (gl.unmanaged_by_funcs, module);
1891 	}
1892 
1893 	if (mod == NULL) {
1894 		p11_debug_precond ("invalid module pointer passed to %s", caller_func);
1895 		return CKR_ARGUMENTS_BAD;
1896 	}
1897 
1898 	/* Matches the ref in prepare_module_inlock_reentrant() */
1899 	mod->ref_count--;
1900 	return CKR_OK;
1901 }
1902 
1903 CK_RV
p11_modules_release_inlock_reentrant(CK_FUNCTION_LIST ** modules)1904 p11_modules_release_inlock_reentrant (CK_FUNCTION_LIST **modules)
1905 {
1906 	CK_RV ret = CKR_OK;
1907 	CK_RV rv;
1908 	int i;
1909 
1910 	for (i = 0; modules[i] != NULL; i++) {
1911 		rv = release_module_inlock_rentrant (modules[i], __PRETTY_FUNCTION__);
1912 		if (rv != CKR_OK)
1913 			ret = rv;
1914 	}
1915 
1916 	free (modules);
1917 
1918 	/* In case nothing loaded, free up internal memory */
1919 	free_modules_when_no_refs_unlocked ();
1920 
1921 	return ret;
1922 }
1923 
1924 static CK_RV
prepare_module_inlock_reentrant(Module * mod,int flags,CK_FUNCTION_LIST ** module)1925 prepare_module_inlock_reentrant (Module *mod,
1926                                  int flags,
1927                                  CK_FUNCTION_LIST **module)
1928 {
1929 	p11_destroyer destroyer;
1930 	const char *trusted;
1931 	p11_virtual *virt;
1932 	bool is_managed;
1933 	bool with_log;
1934 
1935 	assert (module != NULL);
1936 
1937 	if (flags & P11_KIT_MODULE_TRUSTED) {
1938 		trusted = module_get_option_inlock (mod, "trust-policy");
1939 		if (!_p11_conf_parse_boolean (trusted, false))
1940 			return CKR_FUNCTION_NOT_SUPPORTED;
1941 	}
1942 
1943 	if (flags & P11_KIT_MODULE_UNMANAGED) {
1944 		is_managed = false;
1945 		with_log = false;
1946 	} else {
1947 		is_managed = lookup_managed_option (mod, true, "managed", true);
1948 		with_log = lookup_managed_option (mod, is_managed, "log-calls", false);
1949 	}
1950 
1951 	if (is_managed) {
1952 		virt = managed_create_inlock (mod);
1953 		return_val_if_fail (virt != NULL, CKR_HOST_MEMORY);
1954 		destroyer = managed_free_inlock;
1955 
1956 		/* Add the logger if configured */
1957 		if (p11_log_force || with_log) {
1958 			virt = p11_log_subclass (virt, destroyer);
1959 			destroyer = p11_log_release;
1960 		}
1961 
1962 		*module = p11_virtual_wrap (virt, destroyer);
1963 		if (*module == NULL)
1964 			return CKR_GENERAL_ERROR;
1965 
1966 		if (!p11_dict_set (gl.managed_by_closure, *module, mod))
1967 			return_val_if_reached (CKR_HOST_MEMORY);
1968 
1969 	} else {
1970 		*module = unmanaged_for_module_inlock (mod);
1971 		if (*module == NULL)
1972 			return CKR_FUNCTION_NOT_SUPPORTED;
1973 	}
1974 
1975 	/* Matches the deref in release_module_inlock_rentrant() */
1976 	mod->ref_count++;
1977 	return CKR_OK;
1978 }
1979 
1980 CK_RV
p11_modules_load_inlock_reentrant(int flags,CK_FUNCTION_LIST *** results)1981 p11_modules_load_inlock_reentrant (int flags,
1982                                    CK_FUNCTION_LIST ***results)
1983 {
1984 	CK_FUNCTION_LIST **modules;
1985 	Module *mod;
1986 	p11_dictiter iter;
1987 	CK_RV rv;
1988 	int at;
1989 
1990 	rv = init_globals_unlocked ();
1991 	if (rv != CKR_OK)
1992 		return rv;
1993 
1994 	rv = load_registered_modules_unlocked (flags);
1995 	if (rv != CKR_OK)
1996 		return rv;
1997 
1998 	modules = calloc (p11_dict_size (gl.modules) + 1, sizeof (CK_FUNCTION_LIST *));
1999 	return_val_if_fail (modules != NULL, CKR_HOST_MEMORY);
2000 
2001 	at = 0;
2002 	rv = CKR_OK;
2003 
2004 	p11_dict_iterate (gl.modules, &iter);
2005 	while (p11_dict_next (&iter, NULL, (void **)&mod)) {
2006 
2007 		/*
2008 		 * We don't include unreferenced modules. We don't include
2009 		 * modules that have been initialized but aren't in the
2010 		 * registry. These have a NULL name.
2011 		 *
2012 		 * In addition we check again that the module isn't disabled
2013 		 * using enable-in or disable-in. This is because a caller
2014 		 * can change the progname we recognize the process as after
2015 		 * having initialized. This is a corner case, but want to make
2016 		 * sure to cover it.
2017 		 */
2018 		if (!mod->name || !is_module_enabled_unlocked (mod->name, mod->config, flags))
2019 			continue;
2020 
2021 		rv = prepare_module_inlock_reentrant (mod, flags, modules + at);
2022 		if (rv == CKR_OK)
2023 			at++;
2024 		else if (rv == CKR_FUNCTION_NOT_SUPPORTED)
2025 			rv = CKR_OK;
2026 		else
2027 			break;
2028 	}
2029 
2030 	modules[at] = NULL;
2031 
2032 	if (rv != CKR_OK) {
2033 		p11_modules_release_inlock_reentrant (modules);
2034 		return rv;
2035 	}
2036 
2037 	sort_modules_by_priority (modules, at);
2038 	*results = modules;
2039 	return CKR_OK;
2040 }
2041 
2042 /**
2043  * p11_kit_modules_load:
2044  * @reserved: set to %NULL
2045  * @flags: flags to use to load the module
2046  *
2047  * Load the configured PKCS\#11 modules.
2048  *
2049  * If @flags contains the %P11_KIT_MODULE_UNMANAGED flag, then the
2050  * modules will be not be loaded in 'managed' mode regardless of its
2051  * configuration. This is not recommended for general usage.
2052  *
2053  * If @flags contains the %P11_KIT_MODULE_CRITICAL flag then the
2054  * modules will all be treated as 'critical', regardless of the module
2055  * configuration. This means that a failure to load any module will
2056  * cause this function to fail.
2057  *
2058  * For unmanaged modules there is no guarantee to the state of the
2059  * modules. Other callers may be using the modules. Using unmanaged
2060  * modules haphazardly is not recommended for this reason. Some
2061  * modules (such as those configured with RPC) cannot be loaded in
2062  * unmanaged mode, and will be skipped.
2063  *
2064  * If @flags contains the %P11_KIT_MODULE_TRUSTED flag then only the
2065  * marked as trusted modules will be loaded.
2066  *
2067  * Use p11_kit_modules_release() to release the modules returned by
2068  * this function.
2069  *
2070  * If this function fails, then an error message will be available via the
2071  * p11_kit_message() function.
2072  *
2073  * Returns: a null terminated list of modules represented as PKCS\#11
2074  *     function lists, or %NULL on failure
2075  */
2076 CK_FUNCTION_LIST **
p11_kit_modules_load(const char * reserved,int flags)2077 p11_kit_modules_load (const char *reserved,
2078                       int flags)
2079 {
2080 	CK_FUNCTION_LIST **modules;
2081 	CK_RV rv;
2082 
2083 	/* progname attribute not implemented yet */
2084 	return_val_if_fail (reserved == NULL, NULL);
2085 
2086 	p11_library_init_once ();
2087 
2088 	/* WARNING: This function must be reentrant */
2089 	p11_debug ("in");
2090 
2091 	/* mask out internal flags */
2092 	flags &= P11_KIT_MODULE_MASK;
2093 
2094 	p11_lock ();
2095 
2096 		p11_message_clear ();
2097 
2098 		/* WARNING: Reentrancy can occur here */
2099 		rv = p11_modules_load_inlock_reentrant (flags, &modules);
2100 
2101 	p11_unlock ();
2102 
2103 	if (rv != CKR_OK)
2104 		modules = NULL;
2105 
2106 	p11_debug ("out: %s", modules ? "success" : "fail");
2107 	return modules;
2108 }
2109 
2110 /**
2111  * p11_kit_modules_initialize:
2112  * @modules: a %NULL terminated list of modules
2113  * @failure_callback: called with modules that fail to initialize
2114  *
2115  * Initialize all the modules in the @modules list by calling their
2116  * <literal>C_Initialize</literal> function.
2117  *
2118  * For managed modules the <literal>C_Initialize</literal> function
2119  * is overridden so that multiple callers can initialize the same
2120  * modules. In addition for managed modules multiple callers can
2121  * initialize from different threads, and still guarantee consistent
2122  * thread-safe behavior.
2123  *
2124  * For unmanaged modules if multiple callers try to initialize
2125  * a module, then one of the calls will return
2126  * <literal>CKR_CRYPTOKI_ALREADY_INITIALIZED</literal> according to the
2127  * PKCS\#11 specification. In addition there are no guarantees that
2128  * thread-safe behavior will occur if multiple callers initialize from
2129  * different threads.
2130  *
2131  * When a module fails to initialize it is removed from the @modules list.
2132  * If the @failure_callback is not %NULL then it is called with the modules that
2133  * fail to initialize. For example, you may pass p11_kit_module_release()
2134  * as a @failure_callback if the @modules list was loaded wit p11_kit_modules_load().
2135  *
2136  * The return value will return the failure code of the last critical
2137  * module that failed to initialize. Non-critical module failures do not affect
2138  * the return value. If no critical modules failed to initialize then the
2139  * return value will be <literal>CKR_OK</literal>.
2140  *
2141  * When modules are removed, the list will be %NULL terminated at the
2142  * appropriate place so it can continue to be used as a modules list.
2143  *
2144  * This function does not accept a <code>CK_C_INITIALIZE_ARGS</code> argument.
2145  * Custom initialization arguments cannot be supported when multiple consumers
2146  * load the same module.
2147  *
2148  * Returns: <literal>CKR_OK</literal> or the failure code of the last critical
2149  * 	module that failed to initialize.
2150  */
2151 CK_RV
p11_kit_modules_initialize(CK_FUNCTION_LIST ** modules,p11_kit_destroyer failure_callback)2152 p11_kit_modules_initialize (CK_FUNCTION_LIST **modules,
2153                             p11_kit_destroyer failure_callback)
2154 {
2155 	CK_RV ret = CKR_OK;
2156 	CK_RV rv;
2157 	bool critical;
2158 	char *name;
2159 	int i, out;
2160 
2161 	return_val_if_fail (modules != NULL, CKR_ARGUMENTS_BAD);
2162 
2163 	for (i = 0, out = 0; modules[i] != NULL; i++, out++) {
2164 		rv = modules[i]->C_Initialize (NULL);
2165 		if (rv != CKR_OK && rv != CKR_CRYPTOKI_ALREADY_INITIALIZED) {
2166 			name = p11_kit_module_get_name (modules[i]);
2167 			if (name == NULL)
2168 				name = strdup ("(unknown)");
2169 			return_val_if_fail (name != NULL, CKR_HOST_MEMORY);
2170 			critical = (p11_kit_module_get_flags (modules[i]) & P11_KIT_MODULE_CRITICAL);
2171 			p11_message (_("%s: module failed to initialize%s: %s"),
2172 			             name, critical ? "" : ", skipping", p11_kit_strerror (rv));
2173 			if (critical)
2174 				ret = rv;
2175 			if (failure_callback)
2176 				failure_callback (modules[i]);
2177 			out--;
2178 			free (name);
2179 		} else {
2180 			if (rv == CKR_CRYPTOKI_ALREADY_INITIALIZED) {
2181 				name = p11_kit_module_get_name (modules[i]);
2182 				p11_message (_("%s: module was already initialized"),
2183 				             name ? name : "(unknown)");
2184 				free (name);
2185 			}
2186 			modules[out] = modules[i];
2187 		}
2188 	}
2189 
2190 	/* NULL terminate after above changes */
2191 	modules[out] = NULL;
2192 	return ret;
2193 }
2194 
2195 /**
2196  * p11_kit_modules_load_and_initialize:
2197  * @flags: flags to use to load the modules
2198  *
2199  * Load and initialize configured modules.
2200  *
2201  * If a critical module fails to load or initialize then the function will
2202  * return <literal>NULL</literal>. Non-critical modules will be skipped
2203  * and not included in the returned module list.
2204  *
2205  * Use p11_kit_modules_finalize_and_release() when you're done with the
2206  * modules returned by this function.
2207  *
2208  * The @flags allowed by this function, as well as their meaning, are the
2209  * same as with p11_kit_modules_load().
2210  *
2211  * Returns: a <literal>NULL</literal> terminated list of modules, or
2212  * 	<literal>NULL</literal> on failure
2213  */
2214 CK_FUNCTION_LIST **
p11_kit_modules_load_and_initialize(int flags)2215 p11_kit_modules_load_and_initialize (int flags)
2216 {
2217 	CK_FUNCTION_LIST **modules;
2218 	CK_RV rv;
2219 
2220 	/* mask out internal flags */
2221 	flags &= P11_KIT_MODULE_MASK;
2222 
2223 	modules = p11_kit_modules_load (NULL, flags);
2224 	if (modules == NULL)
2225 		return NULL;
2226 
2227 	rv = p11_kit_modules_initialize (modules, (p11_destroyer)p11_kit_module_release);
2228 	if (rv != CKR_OK) {
2229 		p11_kit_modules_release (modules);
2230 		modules = NULL;
2231 	}
2232 
2233 	return modules;
2234 }
2235 
2236 /**
2237  * p11_kit_modules_finalize:
2238  * @modules: a <literal>NULL</literal> terminated list of modules
2239  *
2240  * Finalize each module in the @modules list by calling its
2241  * <literal>C_Finalize</literal> function. Regardless of failures, all
2242  * @modules will have their <literal>C_Finalize</literal> function called.
2243  *
2244  * If a module returns a failure from its <literal>C_Finalize</literal>
2245  * method it will be returned. If multiple modules fail, the last failure
2246  * will be returned.
2247  *
2248  * For managed modules the <literal>C_Finalize</literal> function
2249  * is overridden so that multiple callers can finalize the same
2250  * modules. In addition for managed modules multiple callers can
2251  * finalize from different threads, and still guarantee consistent
2252  * thread-safe behavior.
2253  *
2254  * For unmanaged modules if multiple callers try to finalize
2255  * a module, then one of the calls will return
2256  * <literal>CKR_CRYPTOKI_NOT_INITIALIZED</literal> according to the
2257  * PKCS\#11 specification. In addition there are no guarantees that
2258  * thread-safe behavior will occur if multiple callers finalize from
2259  * different threads.
2260  *
2261  * Returns: <literal>CKR_OK</literal> or the failure code of the last
2262  * 	module that failed to finalize
2263  */
2264 CK_RV
p11_kit_modules_finalize(CK_FUNCTION_LIST ** modules)2265 p11_kit_modules_finalize (CK_FUNCTION_LIST **modules)
2266 {
2267 	CK_RV ret = CKR_OK;
2268 	CK_RV rv;
2269 	char *name;
2270 	int i;
2271 
2272 	return_val_if_fail (modules != NULL, CKR_ARGUMENTS_BAD);
2273 
2274 	for (i = 0; modules[i] != NULL; i++) {
2275 		rv = modules[i]->C_Finalize (NULL);
2276 		if (rv != CKR_OK) {
2277 			name = p11_kit_module_get_name (modules[i]);
2278 			p11_message (_("%s: module failed to finalize: %s"),
2279 			             name ? name : "(unknown)", p11_kit_strerror (rv));
2280 			free (name);
2281 			ret = rv;
2282 		}
2283 	}
2284 
2285 	return ret;
2286 }
2287 
2288 /**
2289  * p11_kit_modules_release:
2290  * @modules: the modules to release
2291  *
2292  * Release the a set of loaded PKCS\#11 modules.
2293  *
2294  * The modules may be either managed or unmanaged. The array containing
2295  * the module pointers is also freed by this function.
2296  *
2297  * Managed modules will not be actually released until all
2298  * callers using them have done so. If the modules were initialized, they
2299  * should have been finalized first.
2300  */
2301 void
p11_kit_modules_release(CK_FUNCTION_LIST ** modules)2302 p11_kit_modules_release (CK_FUNCTION_LIST **modules)
2303 {
2304 	p11_library_init_once ();
2305 
2306 	return_if_fail (modules != NULL);
2307 
2308 	/* WARNING: This function must be reentrant */
2309 	p11_debug ("in");
2310 
2311 	p11_lock ();
2312 
2313 		p11_message_clear ();
2314 		p11_modules_release_inlock_reentrant (modules);
2315 
2316 	p11_unlock ();
2317 
2318 	p11_debug ("out");
2319 }
2320 
2321 /**
2322  * p11_kit_modules_finalize_and_release:
2323  * @modules: the modules to release
2324  *
2325  * Finalize and then release the a set of loaded PKCS\#11 modules.
2326  *
2327  * The modules may be either managed or unmanaged. The array containing
2328  * the module pointers is also freed by this function.
2329  *
2330  * Modules are released even if their finalization returns an error code.
2331  * Managed modules will not be actually finalized or released until all
2332  * callers using them have done so.
2333  *
2334  * For managed modules the <literal>C_Finalize</literal> function
2335  * is overridden so that multiple callers can finalize the same
2336  * modules. In addition for managed modules multiple callers can
2337  * finalize from different threads, and still guarantee consistent
2338  * thread-safe behavior.
2339  *
2340  * For unmanaged modules if multiple callers try to finalize
2341  * a module, then one of the calls will return
2342  * <literal>CKR_CRYPTOKI_NOT_INITIALIZED</literal> according to the
2343  * PKCS\#11 specification. In addition there are no guarantees that
2344  * thread-safe behavior will occur if multiple callers initialize from
2345  * different threads.
2346  */
2347 void
p11_kit_modules_finalize_and_release(CK_FUNCTION_LIST ** modules)2348 p11_kit_modules_finalize_and_release (CK_FUNCTION_LIST **modules)
2349 {
2350 	return_if_fail (modules != NULL);
2351 	p11_kit_modules_finalize (modules);
2352 	p11_kit_modules_release (modules);
2353 }
2354 
2355 /**
2356  * p11_kit_initialize_module:
2357  * @module: loaded module to initialize.
2358  *
2359  * Initialize an arbitrary PKCS\#11 module. Normally using the
2360  * p11_kit_initialize_registered() is preferred.
2361  *
2362  * Using this function to initialize modules allows coordination between
2363  * multiple users of the same module in a single process. It should be called
2364  * on modules that have been loaded (with dlopen() for example) but not yet
2365  * initialized. The caller should not yet have called the module's
2366  * <code>C_Initialize</code> method. This function will call
2367  * <code>C_Initialize</code> as necessary.
2368  *
2369  * Subsequent calls to this function for the same module will result in an
2370  * initialization count being incremented for the module. It is safe (although
2371  * usually unnecessary) to use this function on registered modules.
2372  *
2373  * The module must be finalized with p11_kit_finalize_module() instead of
2374  * calling its <code>C_Finalize</code> method directly.
2375  *
2376  * This function does not accept a <code>CK_C_INITIALIZE_ARGS</code> argument.
2377  * Custom initialization arguments cannot be supported when multiple consumers
2378  * load the same module.
2379  *
2380  * If this function fails, then an error message will be available via the
2381  * p11_kit_message() function.
2382  *
2383  * Deprecated: Since 0.19.0: Use p11_kit_module_initialize() instead.
2384  *
2385  * Returns: CKR_OK if the initialization was successful.
2386  */
2387 CK_RV
p11_kit_initialize_module(CK_FUNCTION_LIST_PTR module)2388 p11_kit_initialize_module (CK_FUNCTION_LIST_PTR module)
2389 {
2390 	CK_FUNCTION_LIST_PTR result;
2391 	Module *mod;
2392 	int flags;
2393 	CK_RV rv;
2394 
2395 	return_val_if_fail (module != NULL, CKR_ARGUMENTS_BAD);
2396 
2397 	p11_library_init_once ();
2398 
2399 	/* WARNING: This function must be reentrant for the same arguments */
2400 	p11_debug ("in");
2401 
2402 	p11_lock ();
2403 
2404 		p11_message_clear ();
2405 
2406 		flags = P11_KIT_MODULE_CRITICAL | P11_KIT_MODULE_UNMANAGED;
2407 		rv = p11_module_load_inlock_reentrant (module, flags, &result);
2408 
2409 		/* An unmanaged module should return the same pointer */
2410 		assert (rv != CKR_OK || result == module);
2411 
2412 		if (rv == CKR_OK) {
2413 			mod = p11_dict_get (gl.unmanaged_by_funcs, module);
2414 			assert (mod != NULL);
2415 			rv = initialize_module_inlock_reentrant (mod, NULL);
2416 			if (rv != CKR_OK) {
2417 				p11_message (_("module initialization failed: %s"), p11_kit_strerror (rv));
2418 			}
2419 		}
2420 
2421 	p11_unlock ();
2422 
2423 	p11_debug ("out: %lu", rv);
2424 	return rv;
2425 }
2426 
2427 CK_RV
p11_module_load_inlock_reentrant(CK_FUNCTION_LIST * module,int flags,CK_FUNCTION_LIST ** result)2428 p11_module_load_inlock_reentrant (CK_FUNCTION_LIST *module,
2429                                   int flags,
2430                                   CK_FUNCTION_LIST **result)
2431 {
2432 	Module *allocated = NULL;
2433 	Module *mod;
2434 	CK_RV rv = CKR_OK;
2435 
2436 	rv = init_globals_unlocked ();
2437 	if (rv == CKR_OK) {
2438 
2439 		mod = p11_dict_get (gl.unmanaged_by_funcs, module);
2440 		if (mod == NULL) {
2441 			p11_debug ("allocating new module");
2442 			allocated = mod = alloc_module_unlocked ();
2443 			return_val_if_fail (mod != NULL, CKR_HOST_MEMORY);
2444 			p11_virtual_init (&mod->virt, &p11_virtual_base, module, NULL);
2445 		}
2446 
2447 		/* If this was newly allocated, add it to the list */
2448 		if (allocated) {
2449 			if (!p11_dict_set (gl.modules, allocated, allocated) ||
2450 			    !p11_dict_set (gl.unmanaged_by_funcs, module, allocated))
2451 				return_val_if_reached (CKR_HOST_MEMORY);
2452 			allocated = NULL;
2453 		}
2454 
2455 			/* WARNING: Reentrancy can occur here */
2456 			rv = prepare_module_inlock_reentrant (mod, flags, result);
2457 
2458 		free (allocated);
2459 	}
2460 
2461 	/*
2462 	 * If initialization failed, we may need to cleanup.
2463 	 * If we added this module above, then this will
2464 	 * clean things up as expected.
2465 	 */
2466 	if (rv != CKR_OK)
2467 		free_modules_when_no_refs_unlocked ();
2468 
2469 	_p11_kit_default_message (rv);
2470 	return rv;
2471 }
2472 
2473 /**
2474  * p11_kit_module_load:
2475  * @module_path: relative or full file path of module library
2476  * @flags: flags to use when loading the module
2477  *
2478  * Load an arbitrary PKCS\#11 module from a dynamic library file, and
2479  * initialize it. Normally using the p11_kit_modules_load() function
2480  * is preferred.
2481  *
2482  * A full file path or just (path/)filename relative to
2483  * P11_MODULE_PATH are accepted.
2484  *
2485  * Using this function to load modules allows coordination between multiple
2486  * callers of the same module in a single process. If @flags contains the
2487  * %P11_KIT_MODULE_UNMANAGED flag, then the modules will be not be loaded
2488  * in 'managed' mode and not be coordinated. This is not recommended
2489  * for general usage.
2490  *
2491  * Subsequent calls to this function for the same module will result in an
2492  * initialization count being incremented for the module. It is safe (although
2493  * usually unnecessary) to use this function on registered modules.
2494  *
2495  * The module should be released with p11_kit_module_release().
2496  *
2497  * If this function fails, then an error message will be available via the
2498  * p11_kit_message() function.
2499  *
2500  * Returns: the loaded module PKCS\#11 functions or %NULL on failure
2501  */
2502 CK_FUNCTION_LIST *
p11_kit_module_load(const char * module_path,int flags)2503 p11_kit_module_load (const char *module_path,
2504                      int flags)
2505 {
2506 	CK_FUNCTION_LIST *module = NULL;
2507 	CK_RV rv;
2508 	Module *mod;
2509 
2510 	return_val_if_fail (module_path != NULL, NULL);
2511 
2512 	p11_library_init_once ();
2513 
2514 	/* WARNING: This function must be reentrant for the same arguments */
2515 	p11_debug ("in: %s", module_path);
2516 
2517 	/* mask out internal flags */
2518 	flags &= P11_KIT_MODULE_MASK;
2519 
2520 	p11_lock ();
2521 
2522 		p11_message_clear ();
2523 
2524 		rv = init_globals_unlocked ();
2525 		if (rv == CKR_OK) {
2526 
2527 			rv = load_module_from_file_inlock (NULL, module_path, &mod);
2528 			if (rv == CKR_OK) {
2529 				/* WARNING: Reentrancy can occur here */
2530 				rv = prepare_module_inlock_reentrant (mod, flags, &module);
2531 				if (rv != CKR_OK)
2532 					module = NULL;
2533 			}
2534 		}
2535 
2536 		/*
2537 		 * If initialization failed, we may need to cleanup.
2538 		 * If we added this module above, then this will
2539 		 * clean things up as expected.
2540 		 */
2541 		if (rv != CKR_OK)
2542 			free_modules_when_no_refs_unlocked ();
2543 
2544 	p11_unlock ();
2545 
2546 	p11_debug ("out: %s", module ? "success" : "fail");
2547 	return module;
2548 
2549 }
2550 
2551 /**
2552  * p11_kit_finalize_module:
2553  * @module: loaded module to finalize.
2554  *
2555  * Finalize an arbitrary PKCS\#11 module. The module must have been initialized
2556  * using p11_kit_initialize_module(). In most cases callers will want to use
2557  * p11_kit_finalize_registered() instead of this function.
2558  *
2559  * Using this function to finalize modules allows coordination between
2560  * multiple users of the same module in a single process. The caller should not
2561  * call the module's <code>C_Finalize</code> method. This function will call
2562  * <code>C_Finalize</code> as necessary.
2563  *
2564  * If the module was initialized more than once, then this function will
2565  * decrement an initialization count for the module. When the count reaches zero
2566  * the module will be truly finalized. It is safe (although usually unnecessary)
2567  * to use this function on registered modules if (and only if) they were
2568  * initialized using p11_kit_initialize_module() for some reason.
2569  *
2570  * If this function fails, then an error message will be available via the
2571  * p11_kit_message() function.
2572  *
2573  * Deprecated: Since 0.19.0: Use p11_kit_module_finalize() and
2574  * 	p11_kit_module_release() instead.
2575  *
2576  * Returns: CKR_OK if the finalization was successful.
2577  */
2578 CK_RV
p11_kit_finalize_module(CK_FUNCTION_LIST * module)2579 p11_kit_finalize_module (CK_FUNCTION_LIST *module)
2580 {
2581 	Module *mod;
2582 	CK_RV rv = CKR_OK;
2583 
2584 	return_val_if_fail (module != NULL, CKR_ARGUMENTS_BAD);
2585 
2586 	p11_library_init_once ();
2587 
2588 	/* WARNING: This function must be reentrant for the same arguments */
2589 	p11_debug ("in");
2590 
2591 	p11_lock ();
2592 
2593 		p11_message_clear ();
2594 
2595 		mod = gl.unmanaged_by_funcs ? p11_dict_get (gl.unmanaged_by_funcs, module) : NULL;
2596 		if (mod == NULL) {
2597 			p11_debug ("module not found");
2598 			rv = CKR_ARGUMENTS_BAD;
2599 		} else {
2600 			/* WARNING: Rentrancy can occur here */
2601 			rv = finalize_module_inlock_reentrant (mod);
2602 		}
2603 
2604 		_p11_kit_default_message (rv);
2605 
2606 	p11_unlock ();
2607 
2608 	p11_debug ("out: %lu", rv);
2609 	return rv;
2610 }
2611 
2612 /**
2613  * p11_kit_module_initialize:
2614  * @module: the module to initialize
2615  *
2616  * Initialize a PKCS\#11 module by calling its <literal>C_Initialize</literal>
2617  * function.
2618  *
2619  * For managed modules the <literal>C_Initialize</literal> function
2620  * is overridden so that multiple callers can initialize the same
2621  * modules. In addition for managed modules multiple callers can
2622  * initialize from different threads, and still guarantee consistent
2623  * thread-safe behavior.
2624  *
2625  * For unmanaged modules if multiple callers try to initialize
2626  * a module, then one of the calls will return
2627  * <literal>CKR_CRYPTOKI_ALREADY_INITIALIZED</literal> according to the
2628  * PKCS\#11 specification. In addition there are no guarantees that
2629  * thread-safe behavior will occur if multiple callers initialize from
2630  * different threads.
2631  *
2632  * This function does not accept a <code>CK_C_INITIALIZE_ARGS</code> argument.
2633  * Custom initialization arguments cannot be supported when multiple consumers
2634  * load the same module.
2635  *
2636  * Returns: <literal>CKR_OK</literal> or a failure code
2637  */
2638 CK_RV
p11_kit_module_initialize(CK_FUNCTION_LIST * module)2639 p11_kit_module_initialize (CK_FUNCTION_LIST *module)
2640 {
2641 	char *name;
2642 	CK_RV rv;
2643 
2644 	return_val_if_fail (module != NULL, CKR_ARGUMENTS_BAD);
2645 
2646 	rv = module->C_Initialize (NULL);
2647 	if (rv != CKR_OK) {
2648 		name = p11_kit_module_get_name (module);
2649 		p11_message (_("%s: module failed to initialize: %s"),
2650 		             name ? name : "(unknown)", p11_kit_strerror (rv));
2651 		free (name);
2652 	}
2653 
2654 	return rv;
2655 }
2656 
2657 /**
2658  * p11_kit_module_finalize:
2659  * @module: the module to finalize
2660  *
2661  * Finalize a PKCS\#11 module by calling its <literal>C_Finalize</literal>
2662  * function.
2663  *
2664  * For managed modules the <literal>C_Finalize</literal> function
2665  * is overridden so that multiple callers can finalize the same
2666  * modules. In addition for managed modules multiple callers can
2667  * finalize from different threads, and still guarantee consistent
2668  * thread-safe behavior.
2669  *
2670  * For unmanaged modules if multiple callers try to finalize
2671  * a module, then one of the calls will return
2672  * <literal>CKR_CRYPTOKI_NOT_INITIALIZED</literal> according to the
2673  * PKCS\#11 specification. In addition there are no guarantees that
2674  * thread-safe behavior will occur if multiple callers finalize from
2675  * different threads.
2676  *
2677  * Returns: <literal>CKR_OK</literal> or a failure code
2678  */
2679 CK_RV
p11_kit_module_finalize(CK_FUNCTION_LIST * module)2680 p11_kit_module_finalize (CK_FUNCTION_LIST *module)
2681 {
2682 	char *name;
2683 	CK_RV rv;
2684 
2685 	return_val_if_fail (module != NULL, CKR_ARGUMENTS_BAD);
2686 
2687 	rv = module->C_Finalize (NULL);
2688 	if (rv != CKR_OK) {
2689 		name = p11_kit_module_get_name (module);
2690 		p11_message (_("%s: module failed to finalize: %s"),
2691 		             name ? name : "(unknown)", p11_kit_strerror (rv));
2692 		free (name);
2693 	}
2694 
2695 	return rv;
2696 
2697 }
2698 
2699 
2700 /**
2701  * p11_kit_module_release:
2702  * @module: the module to release
2703  *
2704  * Release the a loaded PKCS\#11 modules.
2705  *
2706  * The module may be either managed or unmanaged. The <literal>C_Finalize</literal>
2707  * function will be called if no other callers are using this module.
2708  */
2709 void
p11_kit_module_release(CK_FUNCTION_LIST * module)2710 p11_kit_module_release (CK_FUNCTION_LIST *module)
2711 {
2712 	return_if_fail (module != NULL);
2713 
2714 	p11_library_init_once ();
2715 
2716 	/* WARNING: This function must be reentrant for the same arguments */
2717 	p11_debug ("in");
2718 
2719 	p11_lock ();
2720 
2721 		p11_message_clear ();
2722 
2723 		release_module_inlock_rentrant (module, __PRETTY_FUNCTION__);
2724 
2725 	p11_unlock ();
2726 
2727 	p11_debug ("out");
2728 }
2729 
2730 CK_RV
p11_module_release_inlock_reentrant(CK_FUNCTION_LIST * module)2731 p11_module_release_inlock_reentrant (CK_FUNCTION_LIST *module)
2732 {
2733 	return release_module_inlock_rentrant (module, __PRETTY_FUNCTION__);
2734 }
2735 
2736 /**
2737  * p11_kit_load_initialize_module:
2738  * @module_path: full file path of module library
2739  * @module: location to place loaded module pointer
2740  *
2741  * Load an arbitrary PKCS\#11 module from a dynamic library file, and
2742  * initialize it. Normally using the p11_kit_initialize_registered() function
2743  * is preferred.
2744  *
2745  * Using this function to load and initialize modules allows coordination between
2746  * multiple users of the same module in a single process. The caller should not
2747  * call the module's <code>C_Initialize</code> method. This function will call
2748  * <code>C_Initialize</code> as necessary.
2749  *
2750  * If a module has already been loaded, then use of this function is unnecesasry.
2751  * Instead use the p11_kit_initialize_module() function to initialize it.
2752  *
2753  * Subsequent calls to this function for the same module will result in an
2754  * initialization count being incremented for the module. It is safe (although
2755  * usually unnecessary) to use this function on registered modules.
2756  *
2757  * The module must be finalized with p11_kit_finalize_module() instead of
2758  * calling its <code>C_Finalize</code> method directly.
2759  *
2760  * This function does not accept a <code>CK_C_INITIALIZE_ARGS</code> argument.
2761  * Custom initialization arguments cannot be supported when multiple consumers
2762  * load the same module.
2763  *
2764  * If this function fails, then an error message will be available via the
2765  * p11_kit_message() function.
2766  *
2767  * Deprecated: Since 0.19.0: Use p11_kit_module_load() instead.
2768  *
2769  * Returns: CKR_OK if the initialization was successful.
2770  */
2771 CK_RV
p11_kit_load_initialize_module(const char * module_path,CK_FUNCTION_LIST_PTR_PTR module)2772 p11_kit_load_initialize_module (const char *module_path,
2773                                 CK_FUNCTION_LIST_PTR_PTR module)
2774 {
2775 	Module *mod;
2776 	CK_RV rv = CKR_OK;
2777 
2778 	return_val_if_fail (module_path != NULL, CKR_ARGUMENTS_BAD);
2779 	return_val_if_fail (module != NULL, CKR_ARGUMENTS_BAD);
2780 
2781 	p11_library_init_once ();
2782 
2783 	/* WARNING: This function must be reentrant for the same arguments */
2784 	p11_debug ("in: %s", module_path);
2785 
2786 	p11_lock ();
2787 
2788 		p11_message_clear ();
2789 
2790 		rv = init_globals_unlocked ();
2791 		if (rv == CKR_OK) {
2792 
2793 			rv = load_module_from_file_inlock (NULL, module_path, &mod);
2794 			if (rv == CKR_OK) {
2795 
2796 				/* WARNING: Reentrancy can occur here */
2797 				rv = initialize_module_inlock_reentrant (mod, NULL);
2798 			}
2799 		}
2800 
2801 		if (rv == CKR_OK) {
2802 			*module = unmanaged_for_module_inlock (mod);
2803 			assert (*module != NULL);
2804 		}
2805 
2806 		/*
2807 		 * If initialization failed, we may need to cleanup.
2808 		 * If we added this module above, then this will
2809 		 * clean things up as expected.
2810 		 */
2811 		if (rv != CKR_OK)
2812 			free_modules_when_no_refs_unlocked ();
2813 
2814 		_p11_kit_default_message (rv);
2815 
2816 	p11_unlock ();
2817 
2818 	p11_debug ("out: %lu", rv);
2819 	return rv;
2820 }
2821