1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include "cryptsetup-keyfile.h"
4 #include "fileio.h"
5 #include "path-util.h"
6 #include "strv.h"
7 
find_key_file(const char * key_file,char ** search_path,const char * bindname,void ** ret_key,size_t * ret_key_size)8 int find_key_file(
9                 const char *key_file,
10                 char **search_path,
11                 const char *bindname,
12                 void **ret_key,
13                 size_t *ret_key_size) {
14 
15         int r;
16 
17         assert(key_file);
18         assert(ret_key);
19         assert(ret_key_size);
20 
21         if (strv_isempty(search_path) || path_is_absolute(key_file)) {
22 
23                 r = read_full_file_full(
24                                 AT_FDCWD, key_file, UINT64_MAX, SIZE_MAX,
25                                 READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
26                                 bindname,
27                                 (char**) ret_key, ret_key_size);
28                 if (r == -E2BIG)
29                         return log_error_errno(r, "Key file '%s' too large.", key_file);
30                 if (r < 0)
31                         return log_error_errno(r, "Failed to load key file '%s': %m", key_file);
32 
33                 return 1;
34         }
35 
36         STRV_FOREACH(i, search_path) {
37                 _cleanup_free_ char *joined = NULL;
38 
39                 joined = path_join(*i, key_file);
40                 if (!joined)
41                         return log_oom();
42 
43                 r = read_full_file_full(
44                                 AT_FDCWD, joined, UINT64_MAX, SIZE_MAX,
45                                 READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
46                                 bindname,
47                                 (char**) ret_key, ret_key_size);
48                 if (r >= 0)
49                         return 1;
50                 if (r == -E2BIG) {
51                         log_warning_errno(r, "Key file '%s' too large, ignoring.", key_file);
52                         continue;
53                 }
54                 if (r != -ENOENT)
55                         return log_error_errno(r, "Failed to load key file '%s': %m", key_file);
56         }
57 
58         /* Search path supplied, but file not found, report by returning NULL, but not failing */
59         *ret_key = NULL;
60         *ret_key_size = 0;
61         return 0;
62 }
63