@@ -55,23 +55,15 @@ def get_selinux_default_context(file, resource_ensure = nil)
5555
5656 # If the file exists we should pass the mode to matchpathcon for the most specific
5757 # 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 )
7059
7160 retval = Selinux . matchpathcon ( file , mode )
7261 retval == -1 ? nil : retval [ 1 ]
7362 end
7463
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.
7567 def get_selinux_default_context_with_handle ( file , handle , resource_ensure = nil )
7668 return nil unless selinux_support?
7769 # 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)
8375
8476 # If the file exists we should pass the mode to selabel_lookup for the most specific
8577 # 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 )
9879
9980 retval = Selinux . selabel_lookup ( handle , file , mode )
10081 retval == -1 ? nil : retval [ 1 ]
@@ -260,6 +241,22 @@ def get_create_mode(resource_ensure)
260241 mode
261242 end
262243
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+
263260 # Internal helper function to read and parse /proc/mounts
264261 def read_mounts
265262 mounts = '' . dup
0 commit comments