sys-filesystem 1.1.1 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,462 @@
1
+ require_relative 'filesystem/constants'
2
+ require_relative 'filesystem/structs'
3
+ require_relative 'filesystem/functions'
4
+
5
+ # The Sys module serves as a namespace only.
6
+ module Sys
7
+ # The Filesystem class serves as an abstract base class. Its methods
8
+ # return objects of other types. Do not instantiate.
9
+ class Filesystem
10
+ include Sys::Filesystem::Constants
11
+ include Sys::Filesystem::Structs
12
+ extend Sys::Filesystem::Functions
13
+
14
+ private_class_method :new
15
+
16
+ # Readable versions of constant names
17
+ OPT_NAMES = {
18
+ MNT_RDONLY => 'read-only',
19
+ MNT_SYNCHRONOUS => 'synchronous',
20
+ MNT_NOEXEC => 'noexec',
21
+ MNT_NOSUID => 'nosuid',
22
+ MNT_NODEV => 'nodev',
23
+ MNT_UNION => 'union',
24
+ MNT_ASYNC => 'asynchronous',
25
+ MNT_CPROTECT => 'content-protection',
26
+ MNT_EXPORTED => 'exported',
27
+ MNT_QUARANTINE => 'quarantined',
28
+ MNT_LOCAL => 'local',
29
+ MNT_QUOTA => 'quotas',
30
+ MNT_ROOTFS => 'rootfs',
31
+ MNT_DONTBROWSE => 'nobrowse',
32
+ MNT_IGNORE_OWNERSHIP => 'noowners',
33
+ MNT_AUTOMOUNTED => 'automounted',
34
+ MNT_JOURNALED => 'journaled',
35
+ MNT_NOUSERXATTR => 'nouserxattr',
36
+ MNT_DEFWRITE => 'defwrite',
37
+ MNT_NOATIME => 'noatime'
38
+ }.freeze
39
+
40
+ private_constant :OPT_NAMES
41
+
42
+ # File used to read mount informtion from.
43
+ if File.exist?('/etc/mtab')
44
+ MOUNT_FILE = '/etc/mtab'.freeze
45
+ elsif File.exist?('/etc/mnttab')
46
+ MOUNT_FILE = '/etc/mnttab'.freeze
47
+ elsif File.exist?('/proc/mounts')
48
+ MOUNT_FILE = '/proc/mounts'.freeze
49
+ else
50
+ MOUNT_FILE = 'getmntinfo'.freeze
51
+ end
52
+
53
+ private_constant :MOUNT_FILE
54
+
55
+ # The error raised if any of the Filesystem methods fail.
56
+ class Error < StandardError; end
57
+
58
+ # Stat objects are returned by the Sys::Filesystem.stat method.
59
+ class Stat
60
+ # Read-only filesystem
61
+ RDONLY = 1
62
+
63
+ # Filesystem does not support suid or sgid semantics.
64
+ NOSUID = 2
65
+
66
+ # Filesystem does not truncate file names longer than +name_max+.
67
+ NOTRUNC = 3
68
+
69
+ # The path of the filesystem.
70
+ attr_accessor :path
71
+
72
+ # The preferred system block size.
73
+ attr_accessor :block_size
74
+
75
+ # The fragment size, i.e. fundamental filesystem block size.
76
+ attr_accessor :fragment_size
77
+
78
+ # The total number of +fragment_size+ blocks in the filesystem.
79
+ attr_accessor :blocks
80
+
81
+ # The total number of free blocks in the filesystem.
82
+ attr_accessor :blocks_free
83
+
84
+ # The number of free blocks available to unprivileged processes.
85
+ attr_accessor :blocks_available
86
+
87
+ # The total number of files/inodes that can be created.
88
+ attr_accessor :files
89
+
90
+ # The total number of files/inodes on the filesystem.
91
+ attr_accessor :files_free
92
+
93
+ # The number of free files/inodes available to unprivileged processes.
94
+ attr_accessor :files_available
95
+
96
+ # The filesystem identifier.
97
+ attr_accessor :filesystem_id
98
+
99
+ # A bit mask of flags.
100
+ attr_accessor :flags
101
+
102
+ # The maximum length of a file name permitted on the filesystem.
103
+ attr_accessor :name_max
104
+
105
+ # The filesystem type, e.g. UFS.
106
+ attr_accessor :base_type
107
+
108
+ # The filesystem type
109
+ attr_accessor :filesystem_type
110
+
111
+ # The user that mounted the filesystem
112
+ attr_accessor :owner
113
+
114
+ # Count of sync reads since mount
115
+ attr_accessor :sync_reads
116
+
117
+ # Count of sync writes since mount
118
+ attr_accessor :sync_writes
119
+
120
+ # Count of async reads since mount
121
+ attr_accessor :async_reads
122
+
123
+ # Count of async writes since mount
124
+ attr_accessor :async_writes
125
+
126
+ alias inodes files
127
+ alias inodes_free files_free
128
+ alias inodes_available files_available
129
+
130
+ # Creates a new Sys::Filesystem::Stat object. This is meant for
131
+ # internal use only. Do not instantiate directly.
132
+ #
133
+ def initialize
134
+ @path = nil
135
+ @block_size = nil
136
+ @fragment_size = nil
137
+ @blocks = nil
138
+ @blocks_free = nil
139
+ @blocks_available = nil
140
+ @files = nil
141
+ @files_free = nil
142
+ @files_available = nil
143
+ @filesystem_id = nil
144
+ @flags = nil
145
+ @name_max = nil
146
+ @base_type = nil
147
+ end
148
+
149
+ # Returns the total space on the partition.
150
+ def bytes_total
151
+ blocks * fragment_size
152
+ end
153
+
154
+ # Returns the total amount of free space on the partition.
155
+ def bytes_free
156
+ blocks_free * fragment_size
157
+ end
158
+
159
+ # Returns the amount of free space available to unprivileged processes.
160
+ def bytes_available
161
+ blocks_available * fragment_size
162
+ end
163
+
164
+ # Returns the total amount of used space on the partition.
165
+ def bytes_used
166
+ bytes_total - bytes_free
167
+ end
168
+
169
+ # Returns the percentage of the partition that has been used.
170
+ def percent_used
171
+ 100 - (100.0 * bytes_free.to_f / bytes_total.to_f)
172
+ end
173
+ end
174
+
175
+ # Mount objects are returned by the Sys::Filesystem.mounts method.
176
+ class Mount
177
+ # The name of the mounted resource.
178
+ attr_accessor :name
179
+
180
+ # The mount point/directory.
181
+ attr_accessor :mount_point
182
+
183
+ # The type of filesystem mount, e.g. ufs, nfs, etc.
184
+ attr_accessor :mount_type
185
+
186
+ # A list of comma separated options for the mount, e.g. nosuid, etc.
187
+ attr_accessor :options
188
+
189
+ # The time the filesystem was mounted. May be nil.
190
+ attr_accessor :mount_time
191
+
192
+ # The dump frequency in days. May be nil.
193
+ attr_accessor :dump_frequency
194
+
195
+ # The pass number of the filessytem check. May be nil.
196
+ attr_accessor :pass_number
197
+
198
+ alias fsname name
199
+ alias dir mount_point
200
+ alias opts options
201
+ alias passno pass_number
202
+ alias freq dump_frequency
203
+
204
+ # Creates a Sys::Filesystem::Mount object. This is meant for internal
205
+ # use only. Do no instantiate directly.
206
+ #
207
+ def initialize
208
+ @name = nil
209
+ @mount_point = nil
210
+ @mount_type = nil
211
+ @options = nil
212
+ @mount_time = nil
213
+ @dump_frequency = nil
214
+ @pass_number = nil
215
+ end
216
+ end
217
+
218
+ # Returns a Sys::Filesystem::Stat object containing information about the
219
+ # +path+ on the filesystem.
220
+ #
221
+ # Examples:
222
+ #
223
+ # # path
224
+ # Sys::Filesystem.stat("path")
225
+ #
226
+ # # Pathname
227
+ # pathname = Pathname.new("path")
228
+ # Sys::Filesystem.stat(pathname)
229
+ #
230
+ # # File
231
+ # file = File.open("file", "r")
232
+ # Sys::Filesystem.stat(file)
233
+ #
234
+ # # Dir
235
+ # dir = Dir.open("/")
236
+ # Sys::Filesystem.stat(dir)
237
+ #
238
+ def self.stat(path)
239
+ path = path.path if path.respond_to?(:path) # File, Dir
240
+ path = path.to_s if path.respond_to?(:to_s) # Pathname
241
+
242
+ fs = Statvfs.new
243
+
244
+ if statvfs(path, fs) < 0
245
+ raise Error, "statvfs() function failed: #{strerror(FFI.errno)}"
246
+ end
247
+
248
+ obj = Sys::Filesystem::Stat.new
249
+ obj.path = path
250
+ obj.block_size = fs[:f_bsize]
251
+ obj.fragment_size = fs[:f_frsize]
252
+ obj.blocks = fs[:f_blocks]
253
+ obj.blocks_free = fs[:f_bfree]
254
+ obj.blocks_available = fs[:f_bavail]
255
+ obj.files = fs[:f_files]
256
+ obj.files_free = fs[:f_ffree]
257
+ obj.files_available = fs[:f_favail]
258
+ obj.filesystem_id = fs[:f_fsid]
259
+ obj.flags = fs[:f_flag]
260
+ obj.name_max = fs[:f_namemax]
261
+
262
+ # OSX does things a little differently
263
+ if RbConfig::CONFIG['host_os'] =~ /darwin|osx|mach/i
264
+ obj.block_size /= 256
265
+ end
266
+
267
+ if fs.members.include?(:f_basetype)
268
+ obj.base_type = fs[:f_basetype].to_s
269
+ end
270
+
271
+ # DragonFlyBSD has additional struct members
272
+ if RbConfig::CONFIG['host_os'] =~ /dragonfly/i
273
+ obj.owner = fs[:f_owner]
274
+ obj.filesystem_type = fs[:f_type]
275
+ obj.sync_reads = fs[:f_syncreads]
276
+ obj.async_reads = fs[:f_asyncreads]
277
+ obj.sync_writes = fs[:f_syncwrites]
278
+ obj.async_writes = fs[:f_asyncwrites]
279
+ end
280
+
281
+ obj.freeze
282
+ end
283
+
284
+ # In block form, yields a Sys::Filesystem::Mount object for each mounted
285
+ # filesytem on the host. Otherwise it returns an array of Mount objects.
286
+ #
287
+ # Example:
288
+ #
289
+ # Sys::Filesystem.mounts{ |fs|
290
+ # p fs.name # => '/dev/dsk/c0t0d0s0'
291
+ # p fs.mount_time # => Thu Dec 11 15:07:23 -0700 2008
292
+ # p fs.mount_type # => 'ufs'
293
+ # p fs.mount_point # => '/'
294
+ # p fs.options # => local, noowner, nosuid
295
+ # }
296
+ #
297
+ def self.mounts
298
+ array = block_given? ? nil : []
299
+
300
+ if respond_to?(:getmntinfo, true)
301
+ buf = FFI::MemoryPointer.new(:pointer)
302
+
303
+ num = getmntinfo(buf, 2)
304
+
305
+ if num == 0
306
+ raise Error, "getmntinfo() function failed: #{strerror(FFI.errno)}"
307
+ end
308
+
309
+ ptr = buf.get_pointer(0)
310
+
311
+ num.times do
312
+ mnt = Statfs.new(ptr)
313
+ obj = Sys::Filesystem::Mount.new
314
+ obj.name = mnt[:f_mntfromname].to_s
315
+ obj.mount_point = mnt[:f_mntonname].to_s
316
+ obj.mount_type = mnt[:f_fstypename].to_s
317
+
318
+ string = ''
319
+ flags = mnt[:f_flags] & MNT_VISFLAGMASK
320
+
321
+ OPT_NAMES.each do |key, val|
322
+ if flags & key > 0
323
+ if string.empty?
324
+ string << val
325
+ else
326
+ string << ", #{val}"
327
+ end
328
+ end
329
+ flags &= ~key
330
+ end
331
+
332
+ obj.options = string
333
+
334
+ if block_given?
335
+ yield obj.freeze
336
+ else
337
+ array << obj.freeze
338
+ end
339
+
340
+ ptr += Statfs.size
341
+ end
342
+ else
343
+ begin
344
+ if respond_to?(:setmntent, true)
345
+ method_name = 'setmntent'
346
+ fp = setmntent(MOUNT_FILE, 'r')
347
+ else
348
+ method_name = 'fopen'
349
+ fp = fopen(MOUNT_FILE, 'r')
350
+ end
351
+
352
+ if fp.null?
353
+ raise SystemCallError.new(method_name, FFI.errno)
354
+ end
355
+
356
+ while ptr = getmntent(fp)
357
+ break if ptr.null?
358
+ mt = Mntent.new(ptr)
359
+
360
+ obj = Sys::Filesystem::Mount.new
361
+ obj.name = mt[:mnt_fsname]
362
+ obj.mount_point = mt[:mnt_dir]
363
+ obj.mount_type = mt[:mnt_type]
364
+ obj.options = mt[:mnt_opts]
365
+ obj.mount_time = nil
366
+ obj.dump_frequency = mt[:mnt_freq]
367
+ obj.pass_number = mt[:mnt_passno]
368
+
369
+ if block_given?
370
+ yield obj.freeze
371
+ else
372
+ array << obj.freeze
373
+ end
374
+ end
375
+ ensure
376
+ if fp && !fp.null?
377
+ if respond_to?(:endmntent, true)
378
+ endmntent(fp)
379
+ else
380
+ fclose(fp)
381
+ end
382
+ end
383
+ end
384
+ end
385
+
386
+ array
387
+ end
388
+
389
+ # Returns the mount point of the given +file+, or itself if it cannot
390
+ # be found.
391
+ #
392
+ # Example:
393
+ #
394
+ # Sys::Filesystem.mount_point('/home/some_user') # => /home
395
+ #
396
+ def self.mount_point(file)
397
+ dev = File.stat(file).dev
398
+ val = file
399
+
400
+ mounts.each do |mnt|
401
+ mp = mnt.mount_point
402
+ begin
403
+ if File.stat(mp).dev == dev
404
+ val = mp
405
+ break
406
+ end
407
+ rescue Errno::EACCES
408
+ next
409
+ end
410
+ end
411
+
412
+ val
413
+ end
414
+
415
+ # Attach the filesystem specified by +source+ to the location (a directory
416
+ # or file) specified by the pathname in +target+.
417
+ #
418
+ # Note that the +source+ is often a pathname referring to a device, but
419
+ # can also be the pathname of a directory or file, or a dummy string.
420
+ #
421
+ # By default this method will assume 'ext2' as the filesystem type, but
422
+ # you should update this as needed.
423
+ #
424
+ # Typically requires admin privileges.
425
+ #
426
+ # Example:
427
+ #
428
+ # Sys::Filesystem.mount('/dev/loop0', '/home/you/tmp', 'ext4', Sys::Filesystem::MNT_RDONLY)
429
+ #
430
+ def self.mount(source, target, fstype = 'ext2', flags = 0, data = nil)
431
+ if mount_c(source, target, fstype, flags, data) != 0
432
+ raise Error, "mount() function failed: #{strerror(FFI.errno)}"
433
+ end
434
+
435
+ self
436
+ end
437
+
438
+ # Removes the attachment of the (topmost) filesystem mounted on target.
439
+ # You may also specify bitwise OR'd +flags+ to control the precise behavior.
440
+ # The possible flags on Linux are:
441
+ #
442
+ # * MNT_FORCE - Abort pending requests, may cause data loss.
443
+ # * MNT_DETACH - Lazy umount, waits until the mount point is no longer busy.
444
+ # * MNT_EXPIRE - Mark mount point as expired, but don't actually remove it until
445
+ # a second call MNT_EXPIRE call is made.
446
+ #
447
+ # * UMOUNT_NOFOLLOW - Don't dereference the target if it's a symbolic link.
448
+ #
449
+ # Note that BSD platforms may support different flags. Please see the man
450
+ # pages for details.
451
+ #
452
+ # Typically this method requires admin privileges.
453
+ #
454
+ def self.umount(target, flags = 0)
455
+ if umount_c(target, flags) != 0
456
+ raise Error, "umount function failed: #{strerror(FFI.errno)}"
457
+ end
458
+
459
+ self
460
+ end
461
+ end
462
+ end
@@ -0,0 +1,40 @@
1
+ require 'ffi'
2
+
3
+ module Sys
4
+ class Filesystem
5
+ # Wrapper module for Windows related FFI functions.
6
+ module Functions
7
+ extend FFI::Library
8
+ ffi_lib :kernel32
9
+
10
+ # Make FFI functions private
11
+ module FFI::Library
12
+ def attach_pfunc(*args)
13
+ attach_function(*args)
14
+ private args[0]
15
+ end
16
+ end
17
+
18
+ attach_pfunc :DeleteVolumeMountPointA, [:string], :bool
19
+ attach_pfunc :GetDiskFreeSpaceW, %i[buffer_in pointer pointer pointer pointer], :bool
20
+ attach_pfunc :GetDiskFreeSpaceExW, %i[buffer_in pointer pointer pointer], :bool
21
+ attach_pfunc :GetLogicalDriveStringsA, %i[ulong pointer], :ulong
22
+
23
+ attach_pfunc :GetVolumeInformationA,
24
+ %i[buffer_in pointer ulong pointer pointer pointer pointer ulong],
25
+ :bool
26
+
27
+ attach_pfunc :GetVolumeInformationW,
28
+ %i[buffer_in pointer ulong pointer pointer pointer pointer ulong],
29
+ :bool
30
+
31
+ attach_pfunc :GetVolumeNameForVolumeMountPointW, %i[buffer_in buffer_in ulong], :bool
32
+ attach_pfunc :QueryDosDeviceA, %i[buffer_in buffer_out ulong], :ulong
33
+ attach_pfunc :SetVolumeMountPointW, %i[buffer_in buffer_in], :bool
34
+
35
+ ffi_lib :shlwapi
36
+
37
+ attach_pfunc :PathStripToRootW, [:pointer], :bool
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,10 @@
1
+ # Reopen core Ruby classes here and add some custom methods.
2
+ class String
3
+ # Convenience method for converting strings to UTF-16LE for wide character
4
+ # functions that require it.
5
+ #--
6
+ # TODO: Use a refinement.
7
+ def wincode
8
+ (tr(File::SEPARATOR, File::ALT_SEPARATOR) + 0.chr).encode('UTF-16LE')
9
+ end
10
+ end