chef-config 14.1.1 → 14.1.12

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,283 +1,283 @@
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.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
- # Note: 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
- # Retrieves the "home directory" of the current user while trying to ascertain the existence
176
- # of said directory. The path returned uses / for all separators (the ruby standard format).
177
- # If the home directory doesn't exist or an error is otherwise encountered, nil is returned.
178
- #
179
- # If a set of path elements is provided, they are appended as-is to the home path if the
180
- # homepath exists.
181
- #
182
- # If an optional block is provided, the joined path is passed to that block if the home path is
183
- # valid and the result of the block is returned instead.
184
- #
185
- # Home-path discovery is performed once. If a path is discovered, that value is memoized so
186
- # that subsequent calls to home_dir don't bounce around.
187
- #
188
- # See self.all_homes.
189
- def self.home(*args)
190
- @@home_dir ||= all_homes { |p| break p }
191
- if @@home_dir
192
- path = File.join(@@home_dir, *args)
193
- block_given? ? (yield path) : path
194
- end
195
- end
196
-
197
- # See self.home. This method performs a similar operation except that it yields all the different
198
- # possible values of 'HOME' that one could have on this platform. Hence, on windows, if
199
- # HOMEDRIVE\HOMEPATH and USERPROFILE are different, the provided block will be called twice.
200
- # This method goes out and checks the existence of each location at the time of the call.
201
- #
202
- # The return is a list of all the returned values from each block invocation or a list of paths
203
- # if no block is provided.
204
- def self.all_homes(*args)
205
- paths = []
206
- if ChefConfig.windows?
207
- # By default, Ruby uses the the following environment variables to determine Dir.home:
208
- # HOME
209
- # HOMEDRIVE HOMEPATH
210
- # USERPROFILE
211
- # Ruby only checks to see if the variable is specified - not if the directory actually exists.
212
- # On Windows, HOMEDRIVE HOMEPATH can point to a different location (such as an unavailable network mounted drive)
213
- # while USERPROFILE points to the location where the user application settings and profile are stored. HOME
214
- # is not defined as an environment variable (usually). If the home path actually uses UNC, then the prefix is
215
- # HOMESHARE instead of HOMEDRIVE.
216
- #
217
- # We instead walk down the following and only include paths that actually exist.
218
- # HOME
219
- # HOMEDRIVE HOMEPATH
220
- # HOMESHARE HOMEPATH
221
- # USERPROFILE
222
-
223
- paths << ENV["HOME"]
224
- paths << ENV["HOMEDRIVE"] + ENV["HOMEPATH"] if ENV["HOMEDRIVE"] && ENV["HOMEPATH"]
225
- paths << ENV["HOMESHARE"] + ENV["HOMEPATH"] if ENV["HOMESHARE"] && ENV["HOMEPATH"]
226
- paths << ENV["USERPROFILE"]
227
- end
228
- paths << Dir.home if ENV["HOME"]
229
-
230
- # Depending on what environment variables we're using, the slashes can go in any which way.
231
- # Just change them all to / to keep things consistent.
232
- # Note: Maybe this is a bad idea on some unixy systems where \ might be a valid character depending on
233
- # the particular brand of kool-aid you consume. This code assumes that \ and / are both
234
- # path separators on any system being used.
235
- paths = paths.map { |home_path| home_path.gsub(path_separator, ::File::SEPARATOR) if home_path }
236
-
237
- # Filter out duplicate paths and paths that don't exist.
238
- valid_paths = paths.select { |home_path| home_path && Dir.exist?(home_path.force_encoding("utf-8")) }
239
- valid_paths = valid_paths.uniq
240
-
241
- # Join all optional path elements at the end.
242
- # If a block is provided, invoke it - otherwise just return what we've got.
243
- joined_paths = valid_paths.map { |home_path| File.join(home_path, *args) }
244
- if block_given?
245
- joined_paths.each { |p| yield p }
246
- else
247
- joined_paths
248
- end
249
- end
250
-
251
- # Determine if the given path is protected by OS X System Integrity Protection.
252
- def self.is_sip_path?(path, node)
253
- if node["platform"] == "mac_os_x" && Gem::Version.new(node["platform_version"]) >= Gem::Version.new("10.11")
254
- # todo: parse rootless.conf for this?
255
- sip_paths = [
256
- "/System", "/bin", "/sbin", "/usr"
257
- ]
258
- sip_paths.each do |sip_path|
259
- ChefConfig.logger.info("This is a SIP path, checking if it in exceptions list.")
260
- return true if path.start_with?(sip_path)
261
- end
262
- false
263
- else
264
- false
265
- end
266
- end
267
-
268
- # Determine if the given path is on the exception list for OS X System Integrity Protection.
269
- def self.writable_sip_path?(path)
270
- # todo: parse rootless.conf for this?
271
- sip_exceptions = [
272
- "/System/Library/Caches", "/System/Library/Extensions",
273
- "/System/Library/Speech", "/System/Library/User Template",
274
- "/usr/libexec/cups", "/usr/local", "/usr/share/man"
275
- ]
276
- sip_exceptions.each do |exception_path|
277
- return true if path.start_with?(exception_path)
278
- end
279
- ChefConfig.logger.error("Cannot write to a SIP Path on OS X 10.11+")
280
- false
281
- end
282
- end
283
- 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.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
+ # Note: 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
+ # Retrieves the "home directory" of the current user while trying to ascertain the existence
176
+ # of said directory. The path returned uses / for all separators (the ruby standard format).
177
+ # If the home directory doesn't exist or an error is otherwise encountered, nil is returned.
178
+ #
179
+ # If a set of path elements is provided, they are appended as-is to the home path if the
180
+ # homepath exists.
181
+ #
182
+ # If an optional block is provided, the joined path is passed to that block if the home path is
183
+ # valid and the result of the block is returned instead.
184
+ #
185
+ # Home-path discovery is performed once. If a path is discovered, that value is memoized so
186
+ # that subsequent calls to home_dir don't bounce around.
187
+ #
188
+ # See self.all_homes.
189
+ def self.home(*args)
190
+ @@home_dir ||= all_homes { |p| break p }
191
+ if @@home_dir
192
+ path = File.join(@@home_dir, *args)
193
+ block_given? ? (yield path) : path
194
+ end
195
+ end
196
+
197
+ # See self.home. This method performs a similar operation except that it yields all the different
198
+ # possible values of 'HOME' that one could have on this platform. Hence, on windows, if
199
+ # HOMEDRIVE\HOMEPATH and USERPROFILE are different, the provided block will be called twice.
200
+ # This method goes out and checks the existence of each location at the time of the call.
201
+ #
202
+ # The return is a list of all the returned values from each block invocation or a list of paths
203
+ # if no block is provided.
204
+ def self.all_homes(*args)
205
+ paths = []
206
+ if ChefConfig.windows?
207
+ # By default, Ruby uses the the following environment variables to determine Dir.home:
208
+ # HOME
209
+ # HOMEDRIVE HOMEPATH
210
+ # USERPROFILE
211
+ # Ruby only checks to see if the variable is specified - not if the directory actually exists.
212
+ # On Windows, HOMEDRIVE HOMEPATH can point to a different location (such as an unavailable network mounted drive)
213
+ # while USERPROFILE points to the location where the user application settings and profile are stored. HOME
214
+ # is not defined as an environment variable (usually). If the home path actually uses UNC, then the prefix is
215
+ # HOMESHARE instead of HOMEDRIVE.
216
+ #
217
+ # We instead walk down the following and only include paths that actually exist.
218
+ # HOME
219
+ # HOMEDRIVE HOMEPATH
220
+ # HOMESHARE HOMEPATH
221
+ # USERPROFILE
222
+
223
+ paths << ENV["HOME"]
224
+ paths << ENV["HOMEDRIVE"] + ENV["HOMEPATH"] if ENV["HOMEDRIVE"] && ENV["HOMEPATH"]
225
+ paths << ENV["HOMESHARE"] + ENV["HOMEPATH"] if ENV["HOMESHARE"] && ENV["HOMEPATH"]
226
+ paths << ENV["USERPROFILE"]
227
+ end
228
+ paths << Dir.home if ENV["HOME"]
229
+
230
+ # Depending on what environment variables we're using, the slashes can go in any which way.
231
+ # Just change them all to / to keep things consistent.
232
+ # Note: Maybe this is a bad idea on some unixy systems where \ might be a valid character depending on
233
+ # the particular brand of kool-aid you consume. This code assumes that \ and / are both
234
+ # path separators on any system being used.
235
+ paths = paths.map { |home_path| home_path.gsub(path_separator, ::File::SEPARATOR) if home_path }
236
+
237
+ # Filter out duplicate paths and paths that don't exist.
238
+ valid_paths = paths.select { |home_path| home_path && Dir.exist?(home_path.force_encoding("utf-8")) }
239
+ valid_paths = valid_paths.uniq
240
+
241
+ # Join all optional path elements at the end.
242
+ # If a block is provided, invoke it - otherwise just return what we've got.
243
+ joined_paths = valid_paths.map { |home_path| File.join(home_path, *args) }
244
+ if block_given?
245
+ joined_paths.each { |p| yield p }
246
+ else
247
+ joined_paths
248
+ end
249
+ end
250
+
251
+ # Determine if the given path is protected by OS X System Integrity Protection.
252
+ def self.is_sip_path?(path, node)
253
+ if node["platform"] == "mac_os_x" && Gem::Version.new(node["platform_version"]) >= Gem::Version.new("10.11")
254
+ # todo: parse rootless.conf for this?
255
+ sip_paths = [
256
+ "/System", "/bin", "/sbin", "/usr"
257
+ ]
258
+ sip_paths.each do |sip_path|
259
+ ChefConfig.logger.info("This is a SIP path, checking if it in exceptions list.")
260
+ return true if path.start_with?(sip_path)
261
+ end
262
+ false
263
+ else
264
+ false
265
+ end
266
+ end
267
+
268
+ # Determine if the given path is on the exception list for OS X System Integrity Protection.
269
+ def self.writable_sip_path?(path)
270
+ # todo: parse rootless.conf for this?
271
+ sip_exceptions = [
272
+ "/System/Library/Caches", "/System/Library/Extensions",
273
+ "/System/Library/Speech", "/System/Library/User Template",
274
+ "/usr/libexec/cups", "/usr/local", "/usr/share/man"
275
+ ]
276
+ sip_exceptions.each do |exception_path|
277
+ return true if path.start_with?(exception_path)
278
+ end
279
+ ChefConfig.logger.error("Cannot write to a SIP Path on OS X 10.11+")
280
+ false
281
+ end
282
+ end
283
+ end