chef-config 14.9.13 → 14.10.9

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,43 +1,43 @@
1
- #
2
- # Copyright:: Copyright 2016, Chef Software Inc.
3
- # License:: Apache License, Version 2.0
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
-
17
- require "chef-config/path_helper"
18
-
19
- module ChefConfig
20
- module Mixin
21
- module DotD
22
- # Find available configuration files in a `.d/` style include directory.
23
- #
24
- # @api internal
25
- # @param path [String] Base .d/ path to load from.
26
- # @return [Array<String>]
27
- def find_dot_d(path)
28
- Dir["#{PathHelper.escape_glob_dir(path)}/*.rb"].select { |entry| File.file?(entry) }.sort
29
- end
30
-
31
- # Load configuration from a `.d/` style include directory.
32
- #
33
- # @api internal
34
- # @param path [String] Base .d/ path to load from.
35
- # @return [void]
36
- def load_dot_d(path)
37
- find_dot_d(path).each do |conf|
38
- apply_config(IO.read(conf), conf)
39
- end
40
- end
41
- end
42
- end
43
- end
1
+ #
2
+ # Copyright:: Copyright 2016, Chef Software Inc.
3
+ # License:: Apache License, Version 2.0
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ require "chef-config/path_helper"
18
+
19
+ module ChefConfig
20
+ module Mixin
21
+ module DotD
22
+ # Find available configuration files in a `.d/` style include directory.
23
+ #
24
+ # @api internal
25
+ # @param path [String] Base .d/ path to load from.
26
+ # @return [Array<String>]
27
+ def find_dot_d(path)
28
+ Dir["#{PathHelper.escape_glob_dir(path)}/*.rb"].select { |entry| File.file?(entry) }.sort
29
+ end
30
+
31
+ # Load configuration from a `.d/` style include directory.
32
+ #
33
+ # @api internal
34
+ # @param path [String] Base .d/ path to load from.
35
+ # @return [void]
36
+ def load_dot_d(path)
37
+ find_dot_d(path).each do |conf|
38
+ apply_config(IO.read(conf), conf)
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
@@ -1,41 +1,41 @@
1
- #
2
- # Copyright:: Copyright 2016, Chef Software Inc.
3
- # License:: Apache License, Version 2.0
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
-
17
- require "fuzzyurl"
18
-
19
- module ChefConfig
20
- module Mixin
21
- module FuzzyHostnameMatcher
22
-
23
- def fuzzy_hostname_match_any?(hostname, matches)
24
- if (!hostname.nil?) && (!matches.nil?)
25
- return matches.to_s.split(/\s*,\s*/).compact.any? do |m|
26
- fuzzy_hostname_match?(hostname, m)
27
- end
28
- end
29
-
30
- false
31
- end
32
-
33
- def fuzzy_hostname_match?(hostname, match)
34
- # Do greedy matching by adding wildcard if it is not specified
35
- match = "*" + match if !match.start_with?("*")
36
- Fuzzyurl.matches?(Fuzzyurl.mask(hostname: match), hostname)
37
- end
38
-
39
- end
40
- end
41
- end
1
+ #
2
+ # Copyright:: Copyright 2016, Chef Software Inc.
3
+ # License:: Apache License, Version 2.0
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ require "fuzzyurl"
18
+
19
+ module ChefConfig
20
+ module Mixin
21
+ module FuzzyHostnameMatcher
22
+
23
+ def fuzzy_hostname_match_any?(hostname, matches)
24
+ if (!hostname.nil?) && (!matches.nil?)
25
+ return matches.to_s.split(/\s*,\s*/).compact.any? do |m|
26
+ fuzzy_hostname_match?(hostname, m)
27
+ end
28
+ end
29
+
30
+ false
31
+ end
32
+
33
+ def fuzzy_hostname_match?(hostname, match)
34
+ # Do greedy matching by adding wildcard if it is not specified
35
+ match = "*" + match if !match.start_with?("*")
36
+ Fuzzyurl.matches?(Fuzzyurl.mask(hostname: match), hostname)
37
+ end
38
+
39
+ end
40
+ end
41
+ end
@@ -1,322 +1,322 @@
1
- #
2
- # Author:: Bryan McLellan <btm@loftninjas.org>
3
- # Copyright:: Copyright 2014-2018, 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.trace("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
- # This is the INVERSE of Pathname#cleanpath, it converts forward
132
- # slashes to backwhacks for Windows. Since the Ruby API and the
133
- # Windows APIs all consume forward slashes, this helper function
134
- # should only be used for *DISPLAY* logic to send strings back
135
- # to the user with backwhacks. Internally, filename paths should
136
- # generally be stored with forward slashes for consistency. It is
137
- # not necessary or desired to blindly convert pathnames to have
138
- # backwhacks on Windows.
139
- #
140
- # Generally, if the user isn't going to be seeing it, you should be
141
- # using Pathname#cleanpath intead of this function.
142
- def self.cleanpath(path)
143
- path = Pathname.new(path).cleanpath.to_s
144
- # ensure all forward slashes are backslashes
145
- if ChefConfig.windows?
146
- path = path.gsub(File::SEPARATOR, path_separator)
147
- end
148
- path
149
- end
150
-
151
- def self.paths_eql?(path1, path2)
152
- canonical_path(path1) == canonical_path(path2)
153
- end
154
-
155
- # @deprecated this method is deprecated. Please use escape_glob_dirs
156
- # Paths which may contain glob-reserved characters need
157
- # to be escaped before globbing can be done.
158
- # http://stackoverflow.com/questions/14127343
159
- def self.escape_glob(*parts)
160
- path = cleanpath(join(*parts))
161
- path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x }
162
- end
163
-
164
- # This function does not switch to backslashes for windows
165
- # This is because only forwardslashes should be used with dir (even for windows)
166
- def self.escape_glob_dir(*parts)
167
- path = Pathname.new(join(*parts)).cleanpath.to_s
168
- path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x }
169
- end
170
-
171
- def self.relative_path_from(from, to)
172
- Pathname.new(cleanpath(to)).relative_path_from(Pathname.new(cleanpath(from)))
173
- end
174
-
175
- # Set the project-specific home directory environment variable.
176
- #
177
- # This can be used to allow per-tool home directory aliases like $KNIFE_HOME.
178
- #
179
- # @param [env_var] Key for an environment variable to use.
180
- # @return [nil]
181
- def self.per_tool_home_environment=(env_var)
182
- @@per_tool_home_environment = env_var
183
- # Reset this in case .home was already called.
184
- @@home_dir = nil
185
- end
186
-
187
- # Retrieves the "home directory" of the current user while trying to ascertain the existence
188
- # of said directory. The path returned uses / for all separators (the ruby standard format).
189
- # If the home directory doesn't exist or an error is otherwise encountered, nil is returned.
190
- #
191
- # If a set of path elements is provided, they are appended as-is to the home path if the
192
- # homepath exists.
193
- #
194
- # If an optional block is provided, the joined path is passed to that block if the home path is
195
- # valid and the result of the block is returned instead.
196
- #
197
- # Home-path discovery is performed once. If a path is discovered, that value is memoized so
198
- # that subsequent calls to home_dir don't bounce around.
199
- #
200
- # @see all_homes
201
- # @param args [Array<String>] Path components to look for under the home directory.
202
- # @return [String]
203
- def self.home(*args)
204
- @@home_dir ||= all_homes { |p| break p }
205
- if @@home_dir
206
- path = File.join(@@home_dir, *args)
207
- block_given? ? (yield path) : path
208
- end
209
- end
210
-
211
- # See self.home. This method performs a similar operation except that it yields all the different
212
- # possible values of 'HOME' that one could have on this platform. Hence, on windows, if
213
- # HOMEDRIVE\HOMEPATH and USERPROFILE are different, the provided block will be called twice.
214
- # This method goes out and checks the existence of each location at the time of the call.
215
- #
216
- # The return is a list of all the returned values from each block invocation or a list of paths
217
- # if no block is provided.
218
- def self.all_homes(*args)
219
- paths = []
220
- paths << ENV[@@per_tool_home_environment] if defined?(@@per_tool_home_environment) && @@per_tool_home_environment && ENV[@@per_tool_home_environment]
221
- paths << ENV["CHEF_HOME"] if ENV["CHEF_HOME"]
222
- if ChefConfig.windows?
223
- # By default, Ruby uses the the following environment variables to determine Dir.home:
224
- # HOME
225
- # HOMEDRIVE HOMEPATH
226
- # USERPROFILE
227
- # Ruby only checks to see if the variable is specified - not if the directory actually exists.
228
- # On Windows, HOMEDRIVE HOMEPATH can point to a different location (such as an unavailable network mounted drive)
229
- # while USERPROFILE points to the location where the user application settings and profile are stored. HOME
230
- # is not defined as an environment variable (usually). If the home path actually uses UNC, then the prefix is
231
- # HOMESHARE instead of HOMEDRIVE.
232
- #
233
- # We instead walk down the following and only include paths that actually exist.
234
- # HOME
235
- # HOMEDRIVE HOMEPATH
236
- # HOMESHARE HOMEPATH
237
- # USERPROFILE
238
-
239
- paths << ENV["HOME"]
240
- paths << ENV["HOMEDRIVE"] + ENV["HOMEPATH"] if ENV["HOMEDRIVE"] && ENV["HOMEPATH"]
241
- paths << ENV["HOMESHARE"] + ENV["HOMEPATH"] if ENV["HOMESHARE"] && ENV["HOMEPATH"]
242
- paths << ENV["USERPROFILE"]
243
- end
244
- paths << Dir.home if ENV["HOME"]
245
-
246
- # Depending on what environment variables we're using, the slashes can go in any which way.
247
- # Just change them all to / to keep things consistent.
248
- # Note: Maybe this is a bad idea on some unixy systems where \ might be a valid character depending on
249
- # the particular brand of kool-aid you consume. This code assumes that \ and / are both
250
- # path separators on any system being used.
251
- paths = paths.map { |home_path| home_path.gsub(path_separator, ::File::SEPARATOR) if home_path }
252
-
253
- # Filter out duplicate paths and paths that don't exist.
254
- valid_paths = paths.select { |home_path| home_path && Dir.exist?(home_path.force_encoding("utf-8")) }
255
- valid_paths = valid_paths.uniq
256
-
257
- # Join all optional path elements at the end.
258
- # If a block is provided, invoke it - otherwise just return what we've got.
259
- joined_paths = valid_paths.map { |home_path| File.join(home_path, *args) }
260
- if block_given?
261
- joined_paths.each { |p| yield p }
262
- else
263
- joined_paths
264
- end
265
- end
266
-
267
- # Determine if the given path is protected by OS X System Integrity Protection.
268
- def self.is_sip_path?(path, node)
269
- if node["platform"] == "mac_os_x" && Gem::Version.new(node["platform_version"]) >= Gem::Version.new("10.11")
270
- # @todo: parse rootless.conf for this?
271
- sip_paths = [
272
- "/System", "/bin", "/sbin", "/usr"
273
- ]
274
- sip_paths.each do |sip_path|
275
- ChefConfig.logger.info("This is a SIP path, checking if it in exceptions list.")
276
- return true if path.start_with?(sip_path)
277
- end
278
- false
279
- else
280
- false
281
- end
282
- end
283
-
284
- # Determine if the given path is on the exception list for OS X System Integrity Protection.
285
- def self.writable_sip_path?(path)
286
- # todo: parse rootless.conf for this?
287
- sip_exceptions = [
288
- "/System/Library/Caches", "/System/Library/Extensions",
289
- "/System/Library/Speech", "/System/Library/User Template",
290
- "/usr/libexec/cups", "/usr/local", "/usr/share/man"
291
- ]
292
- sip_exceptions.each do |exception_path|
293
- return true if path.start_with?(exception_path)
294
- end
295
- ChefConfig.logger.error("Cannot write to a SIP Path on OS X 10.11+")
296
- false
297
- end
298
-
299
- # Splits a string into an array of tokens as commands and arguments
300
- #
301
- # str = 'command with "some arguments"'
302
- # split_args(str) => ["command", "with", "\"some arguments\""]
303
- #
304
- def self.split_args(line)
305
- cmd_args = []
306
- field = ""
307
- line.scan(/\s*(?>([^\s\\"]+|"([^"]*)"|'([^']*)')|(\S))(\s|\z)?/m) do |word, within_dq, within_sq, esc, sep|
308
-
309
- # Append the string with Word & Escape Character
310
- field << (word || esc.gsub(/\\(.)/, '\\1'))
311
-
312
- # Re-build the field when any whitespace character or
313
- # End of string is encountered
314
- if sep
315
- cmd_args << field
316
- field = ""
317
- end
318
- end
319
- cmd_args
320
- end
321
- end
322
- end
1
+ #
2
+ # Author:: Bryan McLellan <btm@loftninjas.org>
3
+ # Copyright:: Copyright 2014-2018, 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.trace("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
+ # This is the INVERSE of Pathname#cleanpath, it converts forward
132
+ # slashes to backwhacks for Windows. Since the Ruby API and the
133
+ # Windows APIs all consume forward slashes, this helper function
134
+ # should only be used for *DISPLAY* logic to send strings back
135
+ # to the user with backwhacks. Internally, filename paths should
136
+ # generally be stored with forward slashes for consistency. It is
137
+ # not necessary or desired to blindly convert pathnames to have
138
+ # backwhacks on Windows.
139
+ #
140
+ # Generally, if the user isn't going to be seeing it, you should be
141
+ # using Pathname#cleanpath intead of this function.
142
+ def self.cleanpath(path)
143
+ path = Pathname.new(path).cleanpath.to_s
144
+ # ensure all forward slashes are backslashes
145
+ if ChefConfig.windows?
146
+ path = path.gsub(File::SEPARATOR, path_separator)
147
+ end
148
+ path
149
+ end
150
+
151
+ def self.paths_eql?(path1, path2)
152
+ canonical_path(path1) == canonical_path(path2)
153
+ end
154
+
155
+ # @deprecated this method is deprecated. Please use escape_glob_dirs
156
+ # Paths which may contain glob-reserved characters need
157
+ # to be escaped before globbing can be done.
158
+ # http://stackoverflow.com/questions/14127343
159
+ def self.escape_glob(*parts)
160
+ path = cleanpath(join(*parts))
161
+ path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x }
162
+ end
163
+
164
+ # This function does not switch to backslashes for windows
165
+ # This is because only forwardslashes should be used with dir (even for windows)
166
+ def self.escape_glob_dir(*parts)
167
+ path = Pathname.new(join(*parts)).cleanpath.to_s
168
+ path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x }
169
+ end
170
+
171
+ def self.relative_path_from(from, to)
172
+ Pathname.new(cleanpath(to)).relative_path_from(Pathname.new(cleanpath(from)))
173
+ end
174
+
175
+ # Set the project-specific home directory environment variable.
176
+ #
177
+ # This can be used to allow per-tool home directory aliases like $KNIFE_HOME.
178
+ #
179
+ # @param [env_var] Key for an environment variable to use.
180
+ # @return [nil]
181
+ def self.per_tool_home_environment=(env_var)
182
+ @@per_tool_home_environment = env_var
183
+ # Reset this in case .home was already called.
184
+ @@home_dir = nil
185
+ end
186
+
187
+ # Retrieves the "home directory" of the current user while trying to ascertain the existence
188
+ # of said directory. The path returned uses / for all separators (the ruby standard format).
189
+ # If the home directory doesn't exist or an error is otherwise encountered, nil is returned.
190
+ #
191
+ # If a set of path elements is provided, they are appended as-is to the home path if the
192
+ # homepath exists.
193
+ #
194
+ # If an optional block is provided, the joined path is passed to that block if the home path is
195
+ # valid and the result of the block is returned instead.
196
+ #
197
+ # Home-path discovery is performed once. If a path is discovered, that value is memoized so
198
+ # that subsequent calls to home_dir don't bounce around.
199
+ #
200
+ # @see all_homes
201
+ # @param args [Array<String>] Path components to look for under the home directory.
202
+ # @return [String]
203
+ def self.home(*args)
204
+ @@home_dir ||= all_homes { |p| break p }
205
+ if @@home_dir
206
+ path = File.join(@@home_dir, *args)
207
+ block_given? ? (yield path) : path
208
+ end
209
+ end
210
+
211
+ # See self.home. This method performs a similar operation except that it yields all the different
212
+ # possible values of 'HOME' that one could have on this platform. Hence, on windows, if
213
+ # HOMEDRIVE\HOMEPATH and USERPROFILE are different, the provided block will be called twice.
214
+ # This method goes out and checks the existence of each location at the time of the call.
215
+ #
216
+ # The return is a list of all the returned values from each block invocation or a list of paths
217
+ # if no block is provided.
218
+ def self.all_homes(*args)
219
+ paths = []
220
+ paths << ENV[@@per_tool_home_environment] if defined?(@@per_tool_home_environment) && @@per_tool_home_environment && ENV[@@per_tool_home_environment]
221
+ paths << ENV["CHEF_HOME"] if ENV["CHEF_HOME"]
222
+ if ChefConfig.windows?
223
+ # By default, Ruby uses the the following environment variables to determine Dir.home:
224
+ # HOME
225
+ # HOMEDRIVE HOMEPATH
226
+ # USERPROFILE
227
+ # Ruby only checks to see if the variable is specified - not if the directory actually exists.
228
+ # On Windows, HOMEDRIVE HOMEPATH can point to a different location (such as an unavailable network mounted drive)
229
+ # while USERPROFILE points to the location where the user application settings and profile are stored. HOME
230
+ # is not defined as an environment variable (usually). If the home path actually uses UNC, then the prefix is
231
+ # HOMESHARE instead of HOMEDRIVE.
232
+ #
233
+ # We instead walk down the following and only include paths that actually exist.
234
+ # HOME
235
+ # HOMEDRIVE HOMEPATH
236
+ # HOMESHARE HOMEPATH
237
+ # USERPROFILE
238
+
239
+ paths << ENV["HOME"]
240
+ paths << ENV["HOMEDRIVE"] + ENV["HOMEPATH"] if ENV["HOMEDRIVE"] && ENV["HOMEPATH"]
241
+ paths << ENV["HOMESHARE"] + ENV["HOMEPATH"] if ENV["HOMESHARE"] && ENV["HOMEPATH"]
242
+ paths << ENV["USERPROFILE"]
243
+ end
244
+ paths << Dir.home if ENV["HOME"]
245
+
246
+ # Depending on what environment variables we're using, the slashes can go in any which way.
247
+ # Just change them all to / to keep things consistent.
248
+ # Note: Maybe this is a bad idea on some unixy systems where \ might be a valid character depending on
249
+ # the particular brand of kool-aid you consume. This code assumes that \ and / are both
250
+ # path separators on any system being used.
251
+ paths = paths.map { |home_path| home_path.gsub(path_separator, ::File::SEPARATOR) if home_path }
252
+
253
+ # Filter out duplicate paths and paths that don't exist.
254
+ valid_paths = paths.select { |home_path| home_path && Dir.exist?(home_path.force_encoding("utf-8")) }
255
+ valid_paths = valid_paths.uniq
256
+
257
+ # Join all optional path elements at the end.
258
+ # If a block is provided, invoke it - otherwise just return what we've got.
259
+ joined_paths = valid_paths.map { |home_path| File.join(home_path, *args) }
260
+ if block_given?
261
+ joined_paths.each { |p| yield p }
262
+ else
263
+ joined_paths
264
+ end
265
+ end
266
+
267
+ # Determine if the given path is protected by OS X System Integrity Protection.
268
+ def self.is_sip_path?(path, node)
269
+ if node["platform"] == "mac_os_x" && Gem::Version.new(node["platform_version"]) >= Gem::Version.new("10.11")
270
+ # @todo: parse rootless.conf for this?
271
+ sip_paths = [
272
+ "/System", "/bin", "/sbin", "/usr"
273
+ ]
274
+ sip_paths.each do |sip_path|
275
+ ChefConfig.logger.info("This is a SIP path, checking if it in exceptions list.")
276
+ return true if path.start_with?(sip_path)
277
+ end
278
+ false
279
+ else
280
+ false
281
+ end
282
+ end
283
+
284
+ # Determine if the given path is on the exception list for OS X System Integrity Protection.
285
+ def self.writable_sip_path?(path)
286
+ # todo: parse rootless.conf for this?
287
+ sip_exceptions = [
288
+ "/System/Library/Caches", "/System/Library/Extensions",
289
+ "/System/Library/Speech", "/System/Library/User Template",
290
+ "/usr/libexec/cups", "/usr/local", "/usr/share/man"
291
+ ]
292
+ sip_exceptions.each do |exception_path|
293
+ return true if path.start_with?(exception_path)
294
+ end
295
+ ChefConfig.logger.error("Cannot write to a SIP Path on OS X 10.11+")
296
+ false
297
+ end
298
+
299
+ # Splits a string into an array of tokens as commands and arguments
300
+ #
301
+ # str = 'command with "some arguments"'
302
+ # split_args(str) => ["command", "with", "\"some arguments\""]
303
+ #
304
+ def self.split_args(line)
305
+ cmd_args = []
306
+ field = ""
307
+ line.scan(/\s*(?>([^\s\\"]+|"([^"]*)"|'([^']*)')|(\S))(\s|\z)?/m) do |word, within_dq, within_sq, esc, sep|
308
+
309
+ # Append the string with Word & Escape Character
310
+ field << (word || esc.gsub(/\\(.)/, '\\1'))
311
+
312
+ # Re-build the field when any whitespace character or
313
+ # End of string is encountered
314
+ if sep
315
+ cmd_args << field
316
+ field = ""
317
+ end
318
+ end
319
+ cmd_args
320
+ end
321
+ end
322
+ end