aboutsummaryrefslogtreecommitdiff
path: root/runtime/lua/nvim/zip.lua
blob: b6ee634ab7bcc83769499a09a9508778a3d40953 (plain) (blame)
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
local api = vim.api
local uv = vim.uv
local notify = require('vim._core.util').notify

local M = {}

---@return string?, string?
local function unzip()
  local command = vim.fn.exepath('unzip')
  if command == '' then
    return nil, 'unzip executable not found'
  end
  -- Windows searches the current directory before $PATH, so an archive could be opened with an
  -- `unzip` shipped next to it.
  if vim.fn.has('win32') == 1 then
    local dir = uv.fs_realpath(vim.fs.dirname(vim.fs.normalize(command)))
    local cwd = uv.fs_realpath(vim.fn.getcwd())
    if dir and cwd and dir == cwd then
      return nil, 'refusing to run unzip from the current directory'
    end
  end
  return command
end

--- Escape a path so that Info-ZIP matches it literally.
---
--- Info-ZIP matches `*`, `?`, and `[]` in a member selector itself, so this is not shell
--- quoting: passing argv already avoids the shell. For example, unescaped `a[a].txt`
--- silently reads `aa.txt`, and `a?.txt` matches every four-character name. A literal `[`
--- cannot be backslash-escaped, so it is wrapped in a class instead, as is a leading `-`,
--- which would otherwise parse as an option.
--- https://github.com/neovim/neovim/blob/7ba955fe079d4aa2554fea8e7235651fafd40efb/runtime/autoload/zip.vim#L316-L339
---@param value string
---@return string
local function literal_pattern(value)
  return (
    value
      :gsub('\\', '\\\\')
      :gsub('%?', '\\?')
      :gsub('%*', '\\*')
      :gsub('%[', '[[]')
      :gsub('^%-', '[-]')
  )
end

---@param source string
---@return string[]?, string?, boolean?
local function list_archive(source)
  local command, command_err = unzip()
  if not command then
    return nil, command_err, false
  end
  local ok, system = pcall(
    vim.system,
    { command, '-Z1', '--', literal_pattern(source) },
    { text = true }
  )
  if not ok then
    return nil, tostring(system), false
  end
  local result = system:wait()
  if result.code ~= 0 then
    if vim.trim(result.stdout or '') == 'Empty zipfile.' then
      return {}
    end
    return nil, vim.trim(result.stderr or ''), true
  end
  return vim.split(result.stdout or '', '\n', { plain = true, trimempty = true })
end

--- Keep absolute and dot-segment entries visible without treating them as UI navigation.
---@param path string
---@return boolean
local function opaque_path(path)
  if path:sub(1, 1) == '/' or path:match('^%a:[/\\]') then
    return true
  end
  for component in path:gmatch('[^/]+') do
    if component == '.' or component == '..' then
      return true
    end
  end
  return false
end

--- Project the flat archive path list into one navigable directory level.
---@param paths string[] Raw entry paths from the archive.
---@param prefix string Raw archive-directory prefix, including its trailing slash.
---@return nvim.dir.Entry[]
local function entries_at(paths, prefix)
  local entries = {} ---@type nvim.dir.Entry[]
  local seen = {} ---@type table<string,true>
  for _, path in ipairs(paths) do
    if prefix == '' and opaque_path(path) then
      local key = 'opaque:' .. path
      if not seen[key] then
        seen[key] = true
        entries[#entries + 1] = { name = path, dir = false }
      end
    elseif vim.startswith(path, prefix) then
      local rest = path:sub(#prefix + 1)
      local separator = rest:find('/', 1, true)
      local name = separator and rest:sub(1, separator - 1) or rest
      if name ~= '' then
        local dir = separator ~= nil
        local entry_path = ('%s%s%s'):format(prefix, name, dir and '/' or '')
        local key = (dir and 'dir:' or 'file:') .. entry_path
        if not seen[key] then
          seen[key] = true
          entries[#entries + 1] = { name = name, dir = dir }
        end
      end
    end
  end
  return entries
end

---@param source string
---@return boolean?, string?
local function has_magic(source)
  local fd, err = uv.fs_open(source, 'r', 438)
  if not fd then
    return nil, err
  end
  local magic, read_err = uv.fs_read(fd, 2, 0)
  uv.fs_close(fd)
  if not magic then
    return nil, read_err
  end
  return magic == 'PK'
end

---@param buf integer
---@param source string
local function read_normally(buf, source)
  api.nvim_buf_call(buf, function()
    api.nvim_cmd({
      cmd = 'edit',
      args = { source },
      mods = { noautocmd = true, noswapfile = true },
      magic = { file = false, bar = false },
    }, {})
  end)
end

--- Describe an Info-ZIP failure. It reports some conditions only through the exit code, and
--- says nothing on stderr, so the code is preferred where it is meaningful.
---@param code integer
---@param stderr string
---@return string
local function unzip_error(code, stderr)
  if code == 81 then
    return 'unsupported compression or encryption'
  elseif code == 82 then
    return 'incorrect password'
  end
  return stderr ~= '' and stderr or ('unzip exited with %d'):format(code)
end

--- Returned when the empty password `extract_path` supplies is rejected, so a real one is
--- needed. It cannot go in `-P`, which would expose it in the process arguments, and Info-ZIP
--- reads a password from nowhere but a terminal, so it is asked for on a pty.
local ENCRYPTED = 'zip:encrypted'

--- Extract one entry into `dir`, prompting for the archive password on a pty.
---
--- Info-ZIP writes the prompt to the terminal and re-prompts on a wrong password, so the
--- exchange is driven until it extracts, gives up, or the user cancels. The password reaches
--- it over the pty and never appears in the process arguments.
---@param command string
---@param source string
---@param path string
---@param dir string Empty directory to extract into.
---@return string? error
local function extract_with_password(command, source, path, dir)
  local buffered, exited = '', nil ---@type string, integer?
  local ok, job = pcall(vim.fn.jobstart, {
    command,
    '-o',
    '-j',
    '-d',
    dir,
    '--',
    literal_pattern(source),
    literal_pattern(path),
  }, {
    pty = true,
    env = { LC_ALL = 'C' },
    on_stdout = function(_, data)
      buffered = buffered .. table.concat(data, '')
    end,
    on_exit = function(_, code)
      exited = code
    end,
  })
  if not ok or job <= 0 then
    return 'could not start unzip'
  end

  -- Info-ZIP prints the prompt before disabling echo, and disables it with TCSAFLUSH, which
  -- drops a password sent in that window. Echo is still on there, so an echo means "resend".
  local sent = ''
  local function echoed()
    return sent ~= '' and buffered:find(sent .. '\r', 1, true) ~= nil
  end

  local function wanted()
    return exited ~= nil
      or buffered:find('password: ', 1, true) ~= nil
      or buffered:find('reenter: ', 1, true) ~= nil
      or echoed()
  end

  local reenter = false
  while exited == nil do
    local ready, reason = vim.wait(10000, wanted, 50)
    if not ready then
      vim.fn.jobstop(job)
      -- -2 is CTRL-C.
      return reason == -2 and 'cancelled' or 'timed out waiting for unzip'
    end
    if exited ~= nil then
      break
    end
    if echoed() then
      -- Wait for its read(), else the resend is dropped too.
      vim.wait(10)
    else
      local label = reenter and 'Password incorrect, try again: '
        or ('Password for %s: '):format(path)
      sent = vim.fn.inputsecret(label)
      if sent == '' then
        vim.fn.jobstop(job)
        return 'cancelled'
      end
      reenter = true
    end
    buffered = ''
    vim.fn.chansend(job, sent .. '\r')
  end

  if exited ~= 0 then
    return unzip_error(exited, '')
  end
end

---@param command string
---@param source string
---@param path string
---@param target string
---@return string?
local function extract_path(command, source, path, target)
  local file, err = io.open(target, 'wb')
  if not file then
    return err
  end
  local write_err ---@type string?
  -- An empty `-P` inhibits the prompt Info-ZIP would open a terminal for.
  local ok, system = pcall(
    vim.system,
    { command, '-p', '-P', '', '--', literal_pattern(source), literal_pattern(path) },
    {
      stdout = function(pipe_err, data)
        if pipe_err then
          write_err = pipe_err
        elseif data and not write_err then
          local written, file_err = file:write(data)
          if not written then
            write_err = file_err
          end
        end
      end,
    }
  )
  if not ok then
    file:close()
    return tostring(system)
  end
  local result = system:wait()
  file:close()
  if write_err then
    return write_err
  end
  if result.code == 82 then
    return ENCRYPTED
  end
  if result.code ~= 0 then
    return unzip_error(result.code, vim.trim(result.stderr or ''))
  end
end

---@param buf integer
local function set_readonly(buf)
  if not api.nvim_buf_is_valid(buf) then
    return
  end
  api.nvim_set_option_value('swapfile', false, { buf = buf })
  api.nvim_set_option_value('modified', false, { buf = buf })
  api.nvim_set_option_value('buftype', 'nowrite', { buf = buf })
  api.nvim_set_option_value('readonly', true, { buf = buf })
  api.nvim_set_option_value('modifiable', false, { buf = buf })
end

--- Read extracted bytes through Nvim's normal reader to preserve encoding, EOL, and binary behavior.
---@param buf integer Target archive entry buffer.
---@param temp string Temporary file containing the extracted bytes.
local function read_tempfile(buf, temp)
  api.nvim_buf_call(buf, function()
    local name = api.nvim_buf_get_name(buf)
    api.nvim_set_option_value('swapfile', false, { buf = buf })
    api.nvim_cmd({
      cmd = 'file',
      args = { temp },
      mods = { keepalt = true, silent = true },
      magic = { file = false, bar = false },
    }, {})
    api.nvim_cmd({ cmd = 'edit', bang = true, mods = { keepjumps = true, silent = true } }, {})
    api.nvim_cmd({
      cmd = 'file',
      args = { name },
      mods = { keepalt