@@ -55,23 +55,15 @@ def get_selinux_default_context(file, resource_ensure = nil)
55
55
56
56
# If the file exists we should pass the mode to matchpathcon for the most specific
57
57
# matching. If not, we can pass a mode of 0.
58
- begin
59
- filestat = file_lstat ( file )
60
- mode = filestat . mode
61
- rescue Errno ::EACCES
62
- mode = 0
63
- rescue Errno ::ENOENT
64
- if resource_ensure
65
- mode = get_create_mode ( resource_ensure )
66
- else
67
- mode = 0
68
- end
69
- end
58
+ mode = file_mode ( file , resource_ensure )
70
59
71
60
retval = Selinux . matchpathcon ( file , mode )
72
61
retval == -1 ? nil : retval [ 1 ]
73
62
end
74
63
64
+ # Retrieve and return the default context of the file using an selinux handle.
65
+ # If we don't have SELinux support or if the SELinux call fails to file a
66
+ # default then return nil.
75
67
def get_selinux_default_context_with_handle ( file , handle , resource_ensure = nil )
76
68
return nil unless selinux_support?
77
69
# If the filesystem has no support for SELinux labels, return a default of nil
@@ -83,18 +75,7 @@ def get_selinux_default_context_with_handle(file, handle, resource_ensure = nil)
83
75
84
76
# If the file exists we should pass the mode to selabel_lookup for the most specific
85
77
# matching. If not, we can pass a mode of 0.
86
- begin
87
- filestat = file_lstat ( file )
88
- mode = filestat . mode
89
- rescue Errno ::EACCES
90
- mode = 0
91
- rescue Errno ::ENOENT
92
- if resource_ensure
93
- mode = get_create_mode ( resource_ensure )
94
- else
95
- mode = 0
96
- end
97
- end
78
+ mode = file_mode ( file , resource_ensure )
98
79
99
80
retval = Selinux . selabel_lookup ( handle , file , mode )
100
81
retval == -1 ? nil : retval [ 1 ]
@@ -260,6 +241,22 @@ def get_create_mode(resource_ensure)
260
241
mode
261
242
end
262
243
244
+ # If the file/directory/symlink exists, return its mode. Otherwise, get the default mode
245
+ # that should be used to create the file/directory/symlink taking into account the desired
246
+ # file type specified in +resource_ensure+.
247
+ def file_mode ( file , resource_ensure )
248
+ filestat = file_lstat ( file )
249
+ filestat . mode
250
+ rescue Errno ::EACCES
251
+ 0
252
+ rescue Errno ::ENOENT
253
+ if resource_ensure
254
+ get_create_mode ( resource_ensure )
255
+ else
256
+ 0
257
+ end
258
+ end
259
+
263
260
# Internal helper function to read and parse /proc/mounts
264
261
def read_mounts
265
262
mounts = '' . dup
0 commit comments