1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use "time"

use @ponyint_o_rdonly[I32]()
use @ponyint_o_rdwr[I32]()
use @ponyint_o_creat[I32]()
use @ponyint_o_trunc[I32]()
use @ponyint_o_directory[I32]()
use @ponyint_o_cloexec[I32]()
use @ponyint_at_removedir[I32]()
use @openat[I32](fd: I32, path: Pointer[U8] tag, flags: I32, ...)
  if linux or bsd
use @unlinkat[I32](fd: I32, target: Pointer[U8] tag, flags: I32)
use @futimes[I32](fildes: I32, tv: Pointer[(ILong, ILong, ILong, ILong)])
  if not windows
use @renameat[I32](fd: I32, from: Pointer[U8] tag, tofd: I32, to_path: Pointer[U8] tag)
  if linux or bsd
use @symlinkat[I32](source: Pointer[U8] tag, fd: I32, dst: Pointer[U8] tag) if linux or bsd
use @futimesat[I32](fd: I32, path: Pointer[U8] tag,
 timeval: Pointer[(ILong, ILong, ILong, ILong)]) if linux or bsd
use @fchownat[I32](fd: I32, path: Pointer[U8] tag, uid: U32, gid: U32, flags: I32) if linux or bsd
use @fchmodat[I32](fd: I32, path: Pointer[U8] tag, mode: U32, flag: I32) if linux or bsd
use @mkdirat[I32](fd: I32, path: Pointer[U8] tag, mode: U32)
use @fdopendir[Pointer[_DirectoryHandle]](fd: I32) if posix
use @opendir[Pointer[_DirectoryHandle]](name: Pointer[U8] tag) if posix
use @closedir[I32](dir: Pointer[_DirectoryHandle] tag) if posix
use @ponyint_unix_readdir[Pointer[U8] iso^](dir: Pointer[None] tag)
use @ponyint_windows_find_data[Pointer[_DirectoryEntry]]()
  if windows
use @ponyint_windows_find_data_free[None](data: Pointer[_DirectoryEntry])
  if windows
use @ponyint_windows_readdir[Pointer[U8] iso^](data: Pointer[_DirectoryEntry])
  if windows
use @FindFirstFileA[Pointer[_DirectoryHandle]](file_name: Pointer[U8] tag, data: Pointer[_DirectoryEntry])
  if windows
use @FindNextFileA[Bool](handle: Pointer[None] tag, data: Pointer[_DirectoryEntry])
  if windows
use @FindClose[Bool](handle: Pointer[_DirectoryHandle] tag) if windows

primitive _DirectoryHandle
primitive _DirectoryEntry

class Directory
  """
  Operations on a directory.

  The directory-relative functions (open, etc) use the *at interface on FreeBSD
  and Linux. This isn't available on OS X prior to 10.10, so it is not used. On
  FreeBSD, this allows the directory-relative functions to take advantage of
  Capsicum.
  """
  let path: FilePath
    """
    This is the filesystem path locating this directory on the file system
    and an object capability granting access to operate on this directory.
    """

  var _fd: I32 = -1
  // We don't need a file descriptor in Windows. However we do still need to
  // know whether we've disposed of this object, so we use the _fd to indicate
  // this.
  // 0 => not yet disposed of.
  // -1 => disposed of.

  new create(from: FilePath) ? =>
    """
    This will raise an error if the path doesn't exist or it is not a
    directory, or if FileRead or FileStat permission isn't available.
    """
    if not from.caps(FileRead) then
      error
    end

    if not FileInfo(from)?.directory then
      error
    end

    path = from

    ifdef posix then
      _fd =
        @open(from.path.cstring(),
          @ponyint_o_rdonly()
            or @ponyint_o_directory()
            or @ponyint_o_cloexec())

      if _fd == -1 then
        error
      end
    elseif windows then
      _fd = 0
    else
      compile_error "unsupported platform"
    end

    _FileDes.set_rights(_fd, path)?

  new iso _relative(path': FilePath, fd': I32) =>
    """
    Internal constructor. Capsicum rights are already set by inheritence.
    """
    path = path'
    _fd = fd'

  fun entries(): Array[String] iso^ ? =>
    """
    The entries will include everything in the directory, but it is not
    recursive. The path for the entry will be relative to the directory, so it
    will contain no directory separators. The entries will not include "." or
    "..".
    """
    if not path.caps(FileRead) or (_fd == -1) then
      error
    end

    let path' = path.path
    let fd' = _fd

    recover
      let list = Array[String]

      ifdef posix then
        if fd' == -1 then
          error
        end

        let h =
          ifdef linux or bsd then
            let fd =
              @openat(fd', ".".cstring(),
                @ponyint_o_rdonly()
                  or @ponyint_o_directory()
                  or @ponyint_o_cloexec())
            @fdopendir(fd)
          else
            @opendir(path'.cstring())
          end

        if h.is_null() then
          error
        end

        while true do
          let p = @ponyint_unix_readdir(h)
          if p.is_null() then break end
          list.push(recover String.from_cstring(consume p) end)
        end

        @closedir(h)
      elseif windows then
        var find = @ponyint_windows_find_data()
        let search = path' + "\\*"
        let h = @FindFirstFileA(search.cstring(), find)

        if h.usize() == -1 then
          error
        end

        repeat
          let p = @ponyint_windows_readdir(find)

          if not p.is_null() then
            list.push(recover String.from_cstring(consume p) end)
          end
        until not @FindNextFileA(h, find) end

        @FindClose(h)
        @ponyint_windows_find_data_free(find)
      else
        compile_error "unsupported platform"
      end

      consume list
    end

  fun open(target: String): Directory iso^ ? =>
    """
    Open a directory relative to this one. Raises an error if the path is not
    within this directory hierarchy.
    """
    if _fd == -1 then
      error
    end

    let path' = FilePath.from(path, target, path.caps)?

    ifdef linux or bsd then
      let fd' =
        @openat(_fd, target.cstring(),
          @ponyint_o_rdonly()
            or @ponyint_o_directory()
            or @ponyint_o_cloexec())
      _relative(path', fd')
    else
      recover create(path')? end
    end

  fun mkdir(target: String): Bool =>
    """
    Creates a directory relative to this one. Returns false if the path is
    not within this directory hierarchy or if FileMkdir permission is missing.
    """
    if
      not path.caps(FileMkdir) or
      not path.caps(FileLookup) or
      (_fd == -1)
    then
      return false
    end

    try
      let path' = FilePath.from(path, target, path.caps)?

      ifdef linux or bsd then
        var offset: ISize = 0

        repeat
          let element = try
            offset = target.find(Path.sep(), offset)? + 1
            target.substring(0, offset - 1)
          else
            offset = -1
            target
          end

          @mkdirat(_fd, element.cstring(), U32(0x1FF))
        until offset < 0 end

        FileInfo(path')?.directory
      else
        path'.mkdir()
      end
    else
      false
    end

  fun create_file(target: String): File iso^ ? =>
    """
    Open for read/write, creating if it doesn't exist, preserving the contents
    if it does exist.
    """
    if
      not path.caps(FileCreate)
        or not path.caps(FileRead)
        or not path.caps(FileWrite)
        or (_fd == -1)
    then
      error
    end

    let path' = FilePath.from(path, target, path.caps)?

    ifdef linux or bsd then
      let fd' =
        @openat(_fd, target.cstring(),
          @ponyint_o_rdwr()
            or @ponyint_o_creat()
            or @ponyint_o_cloexec(),
          I32(0x1B6))
      recover File._descriptor(fd', path')? end
    else
      recover File(path') end
    end

  fun open_file(target: String): File iso^ ? =>
    """
    Open for read only, failing if it doesn't exist.
    """
    if
      not path.caps(FileRead)
        or (_fd == -1)
    then
      error
    end

    let path' = FilePath.from(path, target, path.caps - FileWrite)?

    ifdef linux or bsd then
      let fd' =
        @openat(_fd, target.cstring(),
          @ponyint_o_rdonly() or @ponyint_o_cloexec(),
          I32(0x1B6))
      recover File._descriptor(fd', path')? end
    else
      recover File.open(path') end
    end

  fun info(): FileInfo ? =>
    """
    Return a FileInfo for this directory. Raise an error if the fd is invalid
    or if we don't have FileStat permission.
    """
    FileInfo._descriptor(_fd, path)?

  fun chmod(mode: FileMode box): Bool =>
    """
    Set the FileMode for this directory.
    """
    _FileDes.chmod(_fd, path, mode)

  fun chown(uid: U32, gid: U32): Bool =>
    """
    Set the owner and group for this directory. Does nothing on Windows.
    """
    _FileDes.chown(_fd, path, uid, gid)

  fun touch(): Bool =>
    """
    Set the last access and modification times of the directory to now.
    """
    _FileDes.touch(_fd, path)

  fun set_time(atime: (I64, I64), mtime: (I64, I64)): Bool =>
    """
    Set the last access and modification times of the directory to the given
    values.
    """
    _FileDes.set_time(_fd, path, atime, mtime)

  fun infoat(target: String): FileInfo ? =>
    """
    Return a FileInfo for some path relative to this directory.
    """
    if
      not path.caps(FileStat)
        or not path.caps(FileLookup)
        or (_fd == -1)
    then
      error
    end

    let path' = FilePath.from(path, target, path.caps)?

    ifdef linux or bsd then
      FileInfo._relative(_fd, path', target)?
    else
      FileInfo(path')?
    end

  fun chmodat(target: String, mode: FileMode box): Bool =>
    """
    Set the FileMode for some path relative to this directory.
    """
    if
      not path.caps(FileChmod)
        or not path.caps(FileLookup)
        or (_fd == -1)
    then
      return false
    end

    try
      let path' = FilePath.from(path, target, path.caps)?

      ifdef linux or bsd then
        0 == @fchmodat(_fd, target.cstring(), mode.u32(), I32(0))
      else
        path'.chmod(mode)
      end
    else
      false
    end

  fun chownat(target: String, uid: U32, gid: U32): Bool =>
    """
    Set the FileMode for some path relative to this directory.
    """
    if
      not path.caps(FileChown)
        or not path.caps(FileLookup)
        or (_fd == -1)
    then
      return false
    end

    try
      let path' = FilePath.from(path, target, path.caps)?

      ifdef linux or bsd then
        0 == @fchownat(_fd, target.cstring(), uid, gid, I32(0))
      else
        path'.chown(uid, gid)
      end
    else
      false
    end

  fun touchat(target: String): Bool =>
    """
    Set the last access and modification times of the directory to now.
    """
    set_time_at(target, Time.now(), Time.now())

  fun set_time_at(
    target: String,
    atime: (I64, I64),
    mtime: (I64, I64))
    : Bool
  =>
    """
    Set the last access and modification times of the directory to the given
    values.
    """
    if
      not path.caps(FileChown)
        or not path.caps(FileLookup)
        or (_fd == -1)
    then
      return false
    end

    try
      let path' = FilePath.from(path, target, path.caps)?

      ifdef linux or bsd then
        var tv: (ILong, ILong, ILong, ILong) =
          ( atime._1.ilong(), atime._2.ilong() / 1000,
            mtime._1.ilong(), mtime._2.ilong() / 1000 )

        0 == @futimesat(_fd, target.cstring(), addressof tv)
      else
        path'.set_time(atime, mtime)
      end
    else
      false
    end

  fun symlink(source: FilePath, link_name: String): Bool =>
    """
    Link the source path to the link_name, where the link_name is relative to
    this directory.
    """
    if
      not path.caps(FileLink)
        or not path.caps(FileLookup)
        or not path.caps(FileCreate)
        or not source.caps(FileLink)
        or (_fd == -1)
    then
      return false
    end

    try
      let path' = FilePath.from(path, link_name, path.caps)?

      ifdef linux or bsd then
        0 == @symlinkat(source.path.cstring(), _fd, link_name.cstring())
      else
        source.symlink(path')
      end
    else
      false
    end

  fun remove(target: String): Bool =>
    """
    Remove the file or directory. The directory contents will be removed as
    well, recursively. Symlinks will be removed but not traversed.
    """
    if
      not path.caps(FileLookup)
        or not path.caps(FileRemove)
        or (_fd == -1)
    then
      return false
    end

    try
      let path' = FilePath.from(path, target, path.caps)?

      ifdef linux or bsd then
        let fi = FileInfo(path')?

        if fi.directory and not fi.symlink then
          let directory = open(target)?

          for entry in directory.entries()?.values() do
            if not directory.remove(entry) then
              return false
            end
          end

          0 == @unlinkat(_fd, target.cstring(), @ponyint_at_removedir())
        else
          0 == @unlinkat(_fd, target.cstring(), 0)
        end
      else
        path'.remove()
      end
    else
      false
    end

  fun rename(source: String, to: Directory box, target: String): Bool =>
    """
    Rename source (which is relative to this directory) to target (which is
    relative to the `to` directory).
    """
    if
      not path.caps(FileLookup)
       or not path.caps(FileRename)
       or not to.path.caps(FileLookup)
       or not to.path.caps(FileCreate)
       or (_fd == -1)
       or (to._fd == -1)
    then
      return false
    end

    try
      let path' = FilePath.from(path, source, path.caps)?
      let path'' = FilePath.from(to.path, target, to.path.caps)?

      ifdef linux or bsd then
        0 == @renameat(_fd, source.cstring(), to._fd, target.cstring())
      else
        path'.rename(path'')
      end
    else
      false
    end

  fun ref dispose() =>
    """
    Close the directory.
    """
    if _fd != -1 then
      ifdef posix then
        @close(_fd)
      end

      _fd = -1
    end

  fun _final() =>
    """
    Close the file descriptor.
    """
    if _fd != -1 then
      ifdef posix then
        @close(_fd)
      end
    end