chef-config 12.7.2 → 12.8.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,264 +1,272 @@
1
- #
2
- # Author:: Bryan McLellan <btm@loftninjas.org>
3
- # Copyright:: Copyright 2014-2016, Chef Software, Inc.
4
- # License:: Apache License, Version 2.0
5
- #
6
- # Licensed under the Apache License, Version 2.0 (the "License");
7
- # you may not use this file except in compliance with the License.
8
- # You may obtain a copy of the License at
9
- #
10
- # http://www.apache.org/licenses/LICENSE-2.0
11
- #
12
- # Unless required by applicable law or agreed to in writing, software
13
- # distributed under the License is distributed on an "AS IS" BASIS,
14
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- # See the License for the specific language governing permissions and
16
- # limitations under the License.
17
- #
18
-
19
- require "chef-config/windows"
20
- require "chef-config/logger"
21
- require "chef-config/exceptions"
22
-
23
- module ChefConfig
24
- class PathHelper
25
- # Maximum characters in a standard Windows path (260 including drive letter and NUL)
26
- WIN_MAX_PATH = 259
27
-
28
- def self.dirname(path)
29
- if ChefConfig.windows?
30
- # Find the first slash, not counting trailing slashes
31
- end_slash = path.size
32
- loop do
33
- slash = path.rindex(/[#{Regexp.escape(File::SEPARATOR)}#{Regexp.escape(path_separator)}]/, end_slash - 1)
34
- if !slash
35
- return end_slash == path.size ? "." : path_separator
36
- elsif slash == end_slash - 1
37
- end_slash = slash
38
- else
39
- return path[0..slash - 1]
40
- end
41
- end
42
- else
43
- ::File.dirname(path)
44
- end
45
- end
46
-
47
- BACKSLASH = '\\'.freeze
48
-
49
- def self.path_separator
50
- if ChefConfig.windows?
51
- File::ALT_SEPARATOR || BACKSLASH
52
- else
53
- File::SEPARATOR
54
- end
55
- end
56
-
57
- def self.join(*args)
58
- path_separator_regex = Regexp.escape(File::SEPARATOR)
59
- unless path_separator == File::SEPARATOR
60
- path_separator_regex << Regexp.escape(path_separator)
61
- end
62
-
63
- trailing_slashes = /[#{path_separator_regex}]+$/
64
- leading_slashes = /^[#{path_separator_regex}]+/
65
-
66
- args.flatten.inject() do |joined_path, component|
67
- joined_path = joined_path.sub(trailing_slashes, "")
68
- component = component.sub(leading_slashes, "")
69
- joined_path += "#{path_separator}#{component}"
70
- end
71
- end
72
-
73
- def self.validate_path(path)
74
- if ChefConfig.windows?
75
- unless printable?(path)
76
- msg = "Path '#{path}' contains non-printable characters. Check that backslashes are escaped with another backslash (e.g. C:\\\\Windows) in double-quoted strings."
77
- ChefConfig.logger.error(msg)
78
- raise ChefConfig::InvalidPath, msg
79
- end
80
-
81
- if windows_max_length_exceeded?(path)
82
- ChefConfig.logger.debug("Path '#{path}' is longer than #{WIN_MAX_PATH}, prefixing with'\\\\?\\'")
83
- path.insert(0, "\\\\?\\")
84
- end
85
- end
86
-
87
- path
88
- end
89
-
90
- def self.windows_max_length_exceeded?(path)
91
- # Check to see if paths without the \\?\ prefix are over the maximum allowed length for the Windows API
92
- # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
93
- unless path =~ /^\\\\?\\/
94
- if path.length > WIN_MAX_PATH
95
- return true
96
- end
97
- end
98
-
99
- false
100
- end
101
-
102
- def self.printable?(string)
103
- # returns true if string is free of non-printable characters (escape sequences)
104
- # this returns false for whitespace escape sequences as well, e.g. \n\t
105
- if string =~ /[^[:print:]]/
106
- false
107
- else
108
- true
109
- end
110
- end
111
-
112
- # Produces a comparable path.
113
- def self.canonical_path(path, add_prefix = true)
114
- # First remove extra separators and resolve any relative paths
115
- abs_path = File.absolute_path(path)
116
-
117
- if ChefConfig.windows?
118
- # Add the \\?\ API prefix on Windows unless add_prefix is false
119
- # Downcase on Windows where paths are still case-insensitive
120
- abs_path.gsub!(::File::SEPARATOR, path_separator)
121
- if add_prefix && abs_path !~ /^\\\\?\\/
122
- abs_path.insert(0, "\\\\?\\")
123
- end
124
-
125
- abs_path.downcase!
126
- end
127
-
128
- abs_path
129
- end
130
-
131
- def self.cleanpath(path)
132
- path = Pathname.new(path).cleanpath.to_s
133
- # ensure all forward slashes are backslashes
134
- if ChefConfig.windows?
135
- path = path.gsub(File::SEPARATOR, path_separator)
136
- end
137
- path
138
- end
139
-
140
- def self.paths_eql?(path1, path2)
141
- canonical_path(path1) == canonical_path(path2)
142
- end
143
-
144
- # Paths which may contain glob-reserved characters need
145
- # to be escaped before globbing can be done.
146
- # http://stackoverflow.com/questions/14127343
147
- def self.escape_glob(*parts)
148
- path = cleanpath(join(*parts))
149
- path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x }
150
- end
151
-
152
- def self.relative_path_from(from, to)
153
- Pathname.new(cleanpath(to)).relative_path_from(Pathname.new(cleanpath(from)))
154
- end
155
-
156
- # Retrieves the "home directory" of the current user while trying to ascertain the existence
157
- # of said directory. The path returned uses / for all separators (the ruby standard format).
158
- # If the home directory doesn't exist or an error is otherwise encountered, nil is returned.
159
- #
160
- # If a set of path elements is provided, they are appended as-is to the home path if the
161
- # homepath exists.
162
- #
163
- # If an optional block is provided, the joined path is passed to that block if the home path is
164
- # valid and the result of the block is returned instead.
165
- #
166
- # Home-path discovery is performed once. If a path is discovered, that value is memoized so
167
- # that subsequent calls to home_dir don't bounce around.
168
- #
169
- # See self.all_homes.
170
- def self.home(*args)
171
- @@home_dir ||= self.all_homes { |p| break p }
172
- if @@home_dir
173
- path = File.join(@@home_dir, *args)
174
- block_given? ? (yield path) : path
175
- end
176
- end
177
-
178
- # See self.home. This method performs a similar operation except that it yields all the different
179
- # possible values of 'HOME' that one could have on this platform. Hence, on windows, if
180
- # HOMEDRIVE\HOMEPATH and USERPROFILE are different, the provided block will be called twice.
181
- # This method goes out and checks the existence of each location at the time of the call.
182
- #
183
- # The return is a list of all the returned values from each block invocation or a list of paths
184
- # if no block is provided.
185
- def self.all_homes(*args)
186
- paths = []
187
- if ChefConfig.windows?
188
- # By default, Ruby uses the the following environment variables to determine Dir.home:
189
- # HOME
190
- # HOMEDRIVE HOMEPATH
191
- # USERPROFILE
192
- # Ruby only checks to see if the variable is specified - not if the directory actually exists.
193
- # On Windows, HOMEDRIVE HOMEPATH can point to a different location (such as an unavailable network mounted drive)
194
- # while USERPROFILE points to the location where the user application settings and profile are stored. HOME
195
- # is not defined as an environment variable (usually). If the home path actually uses UNC, then the prefix is
196
- # HOMESHARE instead of HOMEDRIVE.
197
- #
198
- # We instead walk down the following and only include paths that actually exist.
199
- # HOME
200
- # HOMEDRIVE HOMEPATH
201
- # HOMESHARE HOMEPATH
202
- # USERPROFILE
203
-
204
- paths << ENV["HOME"]
205
- paths << ENV["HOMEDRIVE"] + ENV["HOMEPATH"] if ENV["HOMEDRIVE"] && ENV["HOMEPATH"]
206
- paths << ENV["HOMESHARE"] + ENV["HOMEPATH"] if ENV["HOMESHARE"] && ENV["HOMEPATH"]
207
- paths << ENV["USERPROFILE"]
208
- end
209
- paths << Dir.home if ENV["HOME"]
210
-
211
- # Depending on what environment variables we're using, the slashes can go in any which way.
212
- # Just change them all to / to keep things consistent.
213
- # Note: Maybe this is a bad idea on some unixy systems where \ might be a valid character depending on
214
- # the particular brand of kool-aid you consume. This code assumes that \ and / are both
215
- # path separators on any system being used.
216
- paths = paths.map { |home_path| home_path.gsub(path_separator, ::File::SEPARATOR) if home_path }
217
-
218
- # Filter out duplicate paths and paths that don't exist.
219
- valid_paths = paths.select { |home_path| home_path && Dir.exists?(home_path) }
220
- valid_paths = valid_paths.uniq
221
-
222
- # Join all optional path elements at the end.
223
- # If a block is provided, invoke it - otherwise just return what we've got.
224
- joined_paths = valid_paths.map { |home_path| File.join(home_path, *args) }
225
- if block_given?
226
- joined_paths.each { |p| yield p }
227
- else
228
- joined_paths
229
- end
230
- end
231
-
232
- # Determine if the given path is protected by OS X System Integrity Protection.
233
- def self.is_sip_path?(path, node)
234
- if node["platform"] == "mac_os_x" and Gem::Version.new(node["platform_version"]) >= Gem::Version.new("10.11")
235
- # todo: parse rootless.conf for this?
236
- sip_paths = [
237
- "/System", "/bin", "/sbin", "/usr"
238
- ]
239
- sip_paths.each do |sip_path|
240
- ChefConfig.logger.info("This is a SIP path, checking if it in exceptions list.")
241
- return true if path.start_with?(sip_path)
242
- end
243
- false
244
- else
245
- false
246
- end
247
- end
248
-
249
- # Determine if the given path is on the exception list for OS X System Integrity Protection.
250
- def self.writable_sip_path?(path)
251
- # todo: parse rootless.conf for this?
252
- sip_exceptions = [
253
- "/System/Library/Caches", "/System/Library/Extensions",
254
- "/System/Library/Speech", "/System/Library/User Template",
255
- "/usr/libexec/cups", "/usr/local", "/usr/share/man"
256
- ]
257
- sip_exceptions.each do |exception_path|
258
- return true if path.start_with?(exception_path)
259
- end
260
- ChefConfig.logger.error("Cannot write to a SIP Path on OS X 10.11+")
261
- false
262
- end
263
- end
264
- end
1
+ #
2
+ # Author:: Bryan McLellan <btm@loftninjas.org>
3
+ # Copyright:: Copyright 2014-2016, Chef Software, Inc.
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require "chef-config/windows"
20
+ require "chef-config/logger"
21
+ require "chef-config/exceptions"
22
+
23
+ module ChefConfig
24
+ class PathHelper
25
+ # Maximum characters in a standard Windows path (260 including drive letter and NUL)
26
+ WIN_MAX_PATH = 259
27
+
28
+ def self.dirname(path)
29
+ if ChefConfig.windows?
30
+ # Find the first slash, not counting trailing slashes
31
+ end_slash = path.size
32
+ loop do
33
+ slash = path.rindex(/[#{Regexp.escape(File::SEPARATOR)}#{Regexp.escape(path_separator)}]/, end_slash - 1)
34
+ if !slash
35
+ return end_slash == path.size ? "." : path_separator
36
+ elsif slash == end_slash - 1
37
+ end_slash = slash
38
+ else
39
+ return path[0..slash - 1]
40
+ end
41
+ end
42
+ else
43
+ ::File.dirname(path)
44
+ end
45
+ end
46
+
47
+ BACKSLASH = '\\'.freeze
48
+
49
+ def self.path_separator
50
+ if ChefConfig.windows?
51
+ File::ALT_SEPARATOR || BACKSLASH
52
+ else
53
+ File::SEPARATOR
54
+ end
55
+ end
56
+
57
+ def self.join(*args)
58
+ path_separator_regex = Regexp.escape(File::SEPARATOR)
59
+ unless path_separator == File::SEPARATOR
60
+ path_separator_regex << Regexp.escape(path_separator)
61
+ end
62
+
63
+ trailing_slashes = /[#{path_separator_regex}]+$/
64
+ leading_slashes = /^[#{path_separator_regex}]+/
65
+
66
+ args.flatten.inject() do |joined_path, component|
67
+ joined_path = joined_path.sub(trailing_slashes, "")
68
+ component = component.sub(leading_slashes, "")
69
+ joined_path += "#{path_separator}#{component}"
70
+ end
71
+ end
72
+
73
+ def self.validate_path(path)
74
+ if ChefConfig.windows?
75
+ unless printable?(path)
76
+ msg = "Path '#{path}' contains non-printable characters. Check that backslashes are escaped with another backslash (e.g. C:\\\\Windows) in double-quoted strings."
77
+ ChefConfig.logger.error(msg)
78
+ raise ChefConfig::InvalidPath, msg
79
+ end
80
+
81
+ if windows_max_length_exceeded?(path)
82
+ ChefConfig.logger.debug("Path '#{path}' is longer than #{WIN_MAX_PATH}, prefixing with'\\\\?\\'")
83
+ path.insert(0, "\\\\?\\")
84
+ end
85
+ end
86
+
87
+ path
88
+ end
89
+
90
+ def self.windows_max_length_exceeded?(path)
91
+ # Check to see if paths without the \\?\ prefix are over the maximum allowed length for the Windows API
92
+ # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
93
+ unless path =~ /^\\\\?\\/
94
+ if path.length > WIN_MAX_PATH
95
+ return true
96
+ end
97
+ end
98
+
99
+ false
100
+ end
101
+
102
+ def self.printable?(string)
103
+ # returns true if string is free of non-printable characters (escape sequences)
104
+ # this returns false for whitespace escape sequences as well, e.g. \n\t
105
+ if string =~ /[^[:print:]]/
106
+ false
107
+ else
108
+ true
109
+ end
110
+ end
111
+
112
+ # Produces a comparable path.
113
+ def self.canonical_path(path, add_prefix = true)
114
+ # First remove extra separators and resolve any relative paths
115
+ abs_path = File.absolute_path(path)
116
+
117
+ if ChefConfig.windows?
118
+ # Add the \\?\ API prefix on Windows unless add_prefix is false
119
+ # Downcase on Windows where paths are still case-insensitive
120
+ abs_path.gsub!(::File::SEPARATOR, path_separator)
121
+ if add_prefix && abs_path !~ /^\\\\?\\/
122
+ abs_path.insert(0, "\\\\?\\")
123
+ end
124
+
125
+ abs_path.downcase!
126
+ end
127
+
128
+ abs_path
129
+ end
130
+
131
+ def self.cleanpath(path)
132
+ path = Pathname.new(path).cleanpath.to_s
133
+ # ensure all forward slashes are backslashes
134
+ if ChefConfig.windows?
135
+ path = path.gsub(File::SEPARATOR, path_separator)
136
+ end
137
+ path
138
+ end
139
+
140
+ def self.paths_eql?(path1, path2)
141
+ canonical_path(path1) == canonical_path(path2)
142
+ end
143
+
144
+ # Note: this method is deprecated. Please use escape_glob_dirs
145
+ # Paths which may contain glob-reserved characters need
146
+ # to be escaped before globbing can be done.
147
+ # http://stackoverflow.com/questions/14127343
148
+ def self.escape_glob(*parts)
149
+ path = cleanpath(join(*parts))
150
+ path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x }
151
+ end
152
+
153
+ # This function does not switch to backslashes for windows
154
+ # This is because only forwardslashes should be used with dir (even for windows)
155
+ def self.escape_glob_dir(*parts)
156
+ path = Pathname.new(join(*parts)).cleanpath.to_s
157
+ path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x }
158
+ end
159
+
160
+ def self.relative_path_from(from, to)
161
+ Pathname.new(cleanpath(to)).relative_path_from(Pathname.new(cleanpath(from)))
162
+ end
163
+
164
+ # Retrieves the "home directory" of the current user while trying to ascertain the existence
165
+ # of said directory. The path returned uses / for all separators (the ruby standard format).
166
+ # If the home directory doesn't exist or an error is otherwise encountered, nil is returned.
167
+ #
168
+ # If a set of path elements is provided, they are appended as-is to the home path if the
169
+ # homepath exists.
170
+ #
171
+ # If an optional block is provided, the joined path is passed to that block if the home path is
172
+ # valid and the result of the block is returned instead.
173
+ #
174
+ # Home-path discovery is performed once. If a path is discovered, that value is memoized so
175
+ # that subsequent calls to home_dir don't bounce around.
176
+ #
177
+ # See self.all_homes.
178
+ def self.home(*args)
179
+ @@home_dir ||= self.all_homes { |p| break p }
180
+ if @@home_dir
181
+ path = File.join(@@home_dir, *args)
182
+ block_given? ? (yield path) : path
183
+ end
184
+ end
185
+
186
+ # See self.home. This method performs a similar operation except that it yields all the different
187
+ # possible values of 'HOME' that one could have on this platform. Hence, on windows, if
188
+ # HOMEDRIVE\HOMEPATH and USERPROFILE are different, the provided block will be called twice.
189
+ # This method goes out and checks the existence of each location at the time of the call.
190
+ #
191
+ # The return is a list of all the returned values from each block invocation or a list of paths
192
+ # if no block is provided.
193
+ def self.all_homes(*args)
194
+ paths = []
195
+ if ChefConfig.windows?
196
+ # By default, Ruby uses the the following environment variables to determine Dir.home:
197
+ # HOME
198
+ # HOMEDRIVE HOMEPATH
199
+ # USERPROFILE
200
+ # Ruby only checks to see if the variable is specified - not if the directory actually exists.
201
+ # On Windows, HOMEDRIVE HOMEPATH can point to a different location (such as an unavailable network mounted drive)
202
+ # while USERPROFILE points to the location where the user application settings and profile are stored. HOME
203
+ # is not defined as an environment variable (usually). If the home path actually uses UNC, then the prefix is
204
+ # HOMESHARE instead of HOMEDRIVE.
205
+ #
206
+ # We instead walk down the following and only include paths that actually exist.
207
+ # HOME
208
+ # HOMEDRIVE HOMEPATH
209
+ # HOMESHARE HOMEPATH
210
+ # USERPROFILE
211
+
212
+ paths << ENV["HOME"]
213
+ paths << ENV["HOMEDRIVE"] + ENV["HOMEPATH"] if ENV["HOMEDRIVE"] && ENV["HOMEPATH"]
214
+ paths << ENV["HOMESHARE"] + ENV["HOMEPATH"] if ENV["HOMESHARE"] && ENV["HOMEPATH"]
215
+ paths << ENV["USERPROFILE"]
216
+ end
217
+ paths << Dir.home if ENV["HOME"]
218
+
219
+ # Depending on what environment variables we're using, the slashes can go in any which way.
220
+ # Just change them all to / to keep things consistent.
221
+ # Note: Maybe this is a bad idea on some unixy systems where \ might be a valid character depending on
222
+ # the particular brand of kool-aid you consume. This code assumes that \ and / are both
223
+ # path separators on any system being used.
224
+ paths = paths.map { |home_path| home_path.gsub(path_separator, ::File::SEPARATOR) if home_path }
225
+
226
+ # Filter out duplicate paths and paths that don't exist.
227
+ valid_paths = paths.select { |home_path| home_path && Dir.exists?(home_path.force_encoding("utf-8")) }
228
+ valid_paths = valid_paths.uniq
229
+
230
+ # Join all optional path elements at the end.
231
+ # If a block is provided, invoke it - otherwise just return what we've got.
232
+ joined_paths = valid_paths.map { |home_path| File.join(home_path, *args) }
233
+ if block_given?
234
+ joined_paths.each { |p| yield p }
235
+ else
236
+ joined_paths
237
+ end
238
+ end
239
+
240
+ # Determine if the given path is protected by OS X System Integrity Protection.
241
+ def self.is_sip_path?(path, node)
242
+ if node["platform"] == "mac_os_x" and Gem::Version.new(node["platform_version"]) >= Gem::Version.new("10.11")
243
+ # todo: parse rootless.conf for this?
244
+ sip_paths = [
245
+ "/System", "/bin", "/sbin", "/usr"
246
+ ]
247
+ sip_paths.each do |sip_path|
248
+ ChefConfig.logger.info("This is a SIP path, checking if it in exceptions list.")
249
+ return true if path.start_with?(sip_path)
250
+ end
251
+ false
252
+ else
253
+ false
254
+ end
255
+ end
256
+
257
+ # Determine if the given path is on the exception list for OS X System Integrity Protection.
258
+ def self.writable_sip_path?(path)
259
+ # todo: parse rootless.conf for this?
260
+ sip_exceptions = [
261
+ "/System/Library/Caches", "/System/Library/Extensions",
262
+ "/System/Library/Speech", "/System/Library/User Template",
263
+ "/usr/libexec/cups", "/usr/local", "/usr/share/man"
264
+ ]
265
+ sip_exceptions.each do |exception_path|
266
+ return true if path.start_with?(exception_path)
267
+ end
268
+ ChefConfig.logger.error("Cannot write to a SIP Path on OS X 10.11+")
269
+ false
270
+ end
271
+ end
272
+ end