robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
29.0 KiB1022 linesraw
1const s:testdir = expand("<script>:h")
2const s:runtimedir = simplify(s:testdir . '/../../../runtime')
3const s:netrw_path = s:runtimedir . '/pack/dist/opt/netrw/autoload/netrw.vim'
4const s:netrw_test_path = s:testdir . '/samples/netrw.vim'
5const s:testScript =<< trim END
6
7" Testing functions: {{{1
8function! TestNetrwCaptureRemotePath(dirname)
9  call s:RemotePathAnalysis(a:dirname)
10  return {"method": s:method, "user": s:user, "machine": s:machine, "port": s:port, "path": s:path, "fname": s:fname}
11endfunction
12
13" Test directory creation via s:NetrwMakeDir()
14" Precondition: inputsave() and inputrestore() must be disabled in s:NetrwMakeDir
15
16function s:test_inputsave()
17    if exists("s:inputguards_disabled") && s:inputguards_disabled
18        return
19    endif
20    call inputsave()
21endfunction
22
23function s:test_inputrestore()
24    if exists("s:inputguards_disabled") && s:inputguards_disabled
25        return
26    endif
27    call inputrestore()
28endfunction
29
30function s:test_input(prompt, text = v:null, completion = v:null)  " Nvim: use v:null instead of v:none
31
32    if exists("s:inputdefaults_disabled") && s:inputdefaults_disabled || a:text == v:null
33        return input(a:prompt)
34    elseif a:completion == v:null
35        return input(a:prompt, a:text)
36    endif
37
38    return input(a:prompt, a:text, a:completion)
39endfunction
40
41function Test_NetrwMakeDir(parentdir = $HOME, dirname = "NetrwMakeDir", symlink = 0) abort
42    if a:symlink
43        " Plainly delegate, this device is necessary because feedkeys() can't
44        " access script functions directly.
45        call s:NetrwMakeDir('')
46        " wipe out the test buffer
47        bw
48        " reenable the guards
49        let s:inputguards_disabled = 0
50    else
51        " Use feedkeys() to simulate user input (directory name)
52        new
53        let b:netrw_curdir = a:parentdir
54        let s:inputguards_disabled = 1
55        call feedkeys($"\<Cmd>call Test_NetrwMakeDir('{a:parentdir}', '{a:dirname}', 1)\<CR>{a:dirname}\<CR>", "x")
56    endif
57endfunction
58
59" Test file copy operations via s:NetrwMarkFileCopy()
60function Test_NetrwMarkFileCopy(source_dir, target_dir, marked_files) abort
61    " set up
62    new
63    let b:netrw_curdir= a:source_dir
64    let s:netrwmftgt = a:target_dir
65    let s:netrwmarkfilelist_{bufnr("%")} = a:marked_files
66    let s:netrwmftgt_islocal = 1
67    " delegate
68    call s:NetrwMarkFileCopy(1)
69    " wipe out the test buffer
70    bw
71endfunction
72
73" Corner case: copy into the same dir triggers a user prompt
74function Test_NetrwMarkFileCopy_SameDir(dir = $HOME, symlink = 0) abort
75    const filename = "filename.txt"
76    const file = netrw#fs#PathJoin(a:dir, filename)
77
78    const newfilename = "newfilename.txt"
79    const newfile = netrw#fs#PathJoin(a:dir, newfilename)
80
81    if a:symlink
82        " Plainly delegate, this device is necessary because feedkeys() can't
83        " access script functions directly.
84        " set up
85        new
86        let b:netrw_curdir = a:dir
87        let s:netrwmftgt = a:dir
88        let s:netrwmarkfilelist_{bufnr("%")} = [filename]
89        let s:netrwmftgt_islocal = 1
90
91        " delegate
92        call s:NetrwMarkFileCopy(1)
93
94        " validate
95        call assert_equalfile(file, newfile, "File copy in same dir failed")
96
97        " tear down
98        call delete(file)
99        call delete(newfile)
100        " wipe out the test buffer
101        bw
102        " reenable the guards
103        let s:inputguards_disabled = 0
104        let s:inputdefaults_disabled = 0
105    else
106        " Use feedkeys() to simulate user input (directory name)
107        let s:inputguards_disabled = 1
108        let s:inputdefaults_disabled = 1
109
110        call writefile([$"NetrwMarkFileCopy test file"], file)
111
112        call feedkeys($"\<Cmd>call Test_NetrwMarkFileCopy_SameDir('{a:dir}', 1)\<CR>{newfilename}\<CR>", "x")
113    endif
114endfunction
115
116" Test file copy operations via s:NetrwMarkFileMove()
117function Test_NetrwMarkFileMove(source_dir, target_dir, marked_files) abort
118    " set up
119    new
120    let b:netrw_curdir= a:source_dir
121    let s:netrwmftgt = a:target_dir
122    let s:netrwmarkfilelist_{bufnr("%")} = a:marked_files
123    let s:netrwmftgt_islocal = 1
124    " delegate
125    call s:NetrwMarkFileMove(1)
126    " wipe out the test buffer
127    bw
128endfunction
129
130" Test how netrw fixes paths according with settings
131" (g:netrw_keepdir, g:netrw_cygwin, tree style ...)
132function Test_NetrwFile(fname) abort
133    return s:NetrwFile(a:fname)
134endfunction
135
136function Test_NetrwLcd(newdir) abort
137    return s:NetrwLcd(a:newdir)
138endfunction
139
140" Test hostname validation
141function Test_NetrwValidateHostname(hostname) abort
142    return s:NetrwValidateHostname(a:hostname)
143endfunction
144
145" Test unmarking all files via s:NetrwUnMarkFile()
146function Test_NetrwUnMarkFile()
147    " set up: init global and buffer-local mark lists
148    new
149
150    " initializing the global mark list, the loop handles the buffer-local
151    let s:netrwmarkfilelist = ['test_file']
152
153    " making sure every buffer has a mark list and match pattern
154    let ibuf = 1
155    while ibuf <= bufnr('$')
156        let s:netrwmarkfilelist_{ibuf} = ['test_mark']
157        let s:netrwmarkfilemtch_{ibuf} = 'test_mark'
158        let ibuf = ibuf + 1
159    endwhile
160
161    call s:NetrwUnMarkFile(1)
162
163    call assert_false(exists('s:netrwmarkfilelist'), 'Global list should be wiped')
164    call assert_false(exists('s:netrwmarkfilelist_' . bufnr('$')), 'Last buffer-local list should be wiped')
165    call assert_false(exists('s:netrwmarkfilemtch_' . bufnr('$')), 'Last buffer-local match str should be wiped')
166    call assert_false(exists('s:netrwmarkfilelist_1'), 'First buffer-local list should be wiped')
167    call assert_false(exists('s:netrwmarkfilemtch_1'), 'First buffer-local match str should be wiped')
168
169    " wipe out the test buffer
170    bw
171endfunction
172
173function Test_MakeBookmark(netrw_curdir, fname)
174  new
175  let b:netrw_curdir = a:netrw_curdir
176  call s:MakeBookmark(a:fname)
177  bw
178endfunction
179
180" Test the markings match pattern rebuilt by s:NetrwMarkFile() when unmarking an entry
181function Test_NetrwMarkFile_match_pattern_rebuild()
182  new
183  let curbufnr = bufnr("%")
184
185  call s:NetrwMarkFile(1, 'fname_dir/')
186  call s:NetrwMarkFile(1, 'fname_file')
187  let match_pattern = s:netrwmarkfilemtch_{curbufnr}
188
189  " Assert match pattern after marking and unmarking a directory entry
190  call s:NetrwMarkFile(1, 'dir/')
191  call s:NetrwMarkFile(1, 'dir/')
192  let rebuilt_match_pattern = s:netrwmarkfilemtch_{curbufnr}
193  call assert_equal(match_pattern, rebuilt_match_pattern)
194
195  " Assert match pattern after marking and unmarking a file entry
196  call s:NetrwMarkFile(1, 'file')
197  call s:NetrwMarkFile(1, 'file')
198  let rebuilt_match_pattern = s:netrwmarkfilemtch_{curbufnr}
199  call assert_equal(match_pattern, rebuilt_match_pattern)
200
201  bw
202endfunction
203
204" Test the "home" directory used for bookmarks and history
205function Test_NetrwHome() abort
206    return s:NetrwHome()
207endfunction
208" }}}
209END
210
211"make copy of netrw script and add function to print local variables"
212func s:appendDebugToNetrw(netrw_path, netrw_test_path)
213
214  " load the netrw script
215  execute "split" a:netrw_test_path
216  execute "read" a:netrw_path
217
218  " replace input guards for convenient testing versions
219  %substitute@call inputsave()@call s:test_inputsave()@g
220  %substitute@call inputrestore()@call s:test_inputrestore()@g
221  %substitute@\<input(@s:test_input(@g
222
223  call cursor(1,1)
224  let pos = search("Settings Restoration:")-1
225  " insert the test functions before the end guard
226  call assert_false(append(pos, s:testScript))
227
228  " save the modified script content
229  write
230  bwipe!
231
232endfunction
233
234func SetUp()
235
236  " prepare modified netrw script
237  call s:appendDebugToNetrw(s:netrw_path, s:netrw_test_path)
238
239  " source the modified script
240  exe "source" s:netrw_test_path
241
242  " Rig the package. The modified script guard prevents loading it again.
243  let &runtimepath=s:runtimedir
244  let &packpath=s:runtimedir
245  packadd netrw
246
247  " use proper path
248  if has('win32')
249    let $HOME = substitute($HOME, '/', '\\', 'g')
250  endif
251
252endfunction
253
254func TearDown()
255  " cleanup
256  call delete(s:netrw_test_path)
257endfunction
258
259func SetShell(shell)
260    " select different shells
261    if a:shell == "default"
262        set shell& shellcmdflag& shellxquote& shellpipe& shellredir&
263        if has("win32")
264          " Nvim: default 'shell' is "sh" due to $SHELL being set in Makefile,
265          " but here 'shell' should be cmd.exe.
266          set shell=cmd.exe shellcmdflag=/s\ /c
267        endif
268    elseif a:shell == "powershell" " help dos-powershell
269        " powershell desktop is windows only
270        if !has("win32")
271            throw 'Skipped: powershell desktop is missing'
272        endif
273        set shell=powershell shellcmdflag=-NoProfile\ -Command shellxquote=\"
274        set shellpipe=2>&1\ \|\ Out-File\ -Encoding\ default shellredir=2>&1\ \|\ Out-File\ -Encoding\ default
275    elseif a:shell == "pwsh" " help dos-powershell
276        " powershell core works crossplatform
277        if !executable("pwsh")
278            throw 'Skipped: powershell core is missing'
279        endif
280        set shell=pwsh shellcmdflag=-NoProfile\ -c shellpipe=>%s\ 2>&1 shellredir=>%s\ 2>&1
281        if has("win32")
282            set shellxquote=\"
283        else
284            set shellxquote=
285        endif
286    else
287        call assert_report("Trying to select an unknown shell")
288    endif
289    " Nvim: 'shellxquote' needs to be empty for the tests for work.
290    set shellxquote=
291endfunc
292
293func s:combine
294  \( usernames
295  \, methods
296  \, hosts
297  \, ports
298  \, dirs
299  \, files)
300  for username in a:usernames
301    for method in a:methods
302      for host in a:hosts
303        for port in a:ports
304          for dir in a:dirs
305            for file in a:files
306               " --- Build a full remote path ---
307
308              let port_str = empty(port) ? "" : ':' . port
309              let remote = printf('%s://%s@%s%s/%s%s', method, username, host, port_str, dir, file)
310
311              let result = TestNetrwCaptureRemotePath(remote)
312
313              call assert_equal(result.method, method)
314              call assert_equal(result.user, username)
315              call assert_equal(result.machine, host)
316              call assert_equal(result.port, port)
317              call assert_equal(result.path, dir . file)
318            endfor
319          endfor
320        endfor
321      endfor
322    endfor
323  endfor
324endfunction
325
326
327func Test_netrw_lcd_failure()
328  CheckUnix
329  CheckNotRoot
330  let dirname = getcwd() .. '/Xnetrw_noaccess'
331  call mkdir(dirname)
332  call assert_true(setfperm(dirname, 'r--------'))
333  try
334    for prevdir in [1, 0]
335      new
336      try
337        let cwd = getcwd()
338        if prevdir
339          let w:netrw_prvdir = cwd
340        else
341          unlet! w:netrw_prvdir
342        endif
343        setlocal modifiable noreadonly number
344        let msg = execute('call assert_equal(-1, Test_NetrwLcd(dirname))')
345        call assert_match('unable to change directory to <' .. dirname .. '>', msg)
346        call assert_equal(cwd, getcwd())
347        if prevdir
348          call assert_equal(cwd, w:netrw_prvdir)
349          call assert_true(&l:modifiable)
350        else
351          call assert_false(&l:modifiable)
352          call assert_true(&l:readonly)
353          call assert_false(&l:number)
354        endif
355      finally
356        bwipe!
357      endtry
358    endfor
359  finally
360    call setfperm(dirname, 'rwx------')
361    call delete(dirname, 'd')
362  endtry
363endfunc
364
365func Test_netrw_parse_remote_simple()
366  let result = TestNetrwCaptureRemotePath('scp://user@localhost:2222/test.txt')
367  call assert_equal(result.method, 'scp')
368  call assert_equal(result.user, 'user')
369  call assert_equal(result.machine, 'localhost')
370  call assert_equal(result.port, '2222')
371  call assert_equal(result.path, 'test.txt')
372endfunction
373
374"testing different combinations"
375func Test_netrw_parse_regular_usernames()
376
377  " --- sample data for combinations ---"
378  let usernames = ["root", "toor", "user01", "skillIssue"]
379  let methods = ["scp", "ssh", "ftp", "sftp"]
380  let hosts = ["localhost", "server.com", "fit-workspaces.ksi.fit.cvut.cz", "192.168.1.42"]
381  let ports = ["", "22","420", "443", "2222", "1234"]
382  let dirs = ["", "somefolder/", "path/to/the/bottom/of/the/world/please/send/help/"]
383  let files = ["test.txt", "tttt.vim", "Makefile"]
384
385  call s:combine(usernames, methods, hosts, ports, dirs, files)
386
387endfunc
388
389"Host myserver
390"    HostName 192.168.1.42
391"    User alice
392func Test_netrw_parse_ssh_config_entries()
393  let result = TestNetrwCaptureRemotePath('scp://myserver//etc/nginx/nginx.conf')
394  call assert_equal(result.method, 'scp')
395  call assert_equal(result.user, '')
396  call assert_equal(result.machine, 'myserver')
397  call assert_equal(result.port, '')
398  call assert_equal(result.path, '/etc/nginx/nginx.conf')
399endfunction
400
401"username containing special-chars"
402func Test_netrw_parse_special_char_user()
403  let result = TestNetrwCaptureRemotePath('scp://user-01@localhost:2222/test.txt')
404  call assert_equal(result.method, 'scp')
405  call assert_equal(result.user, 'user-01')
406  call assert_equal(result.machine, 'localhost')
407  call assert_equal(result.port, '2222')
408  call assert_equal(result.path, 'test.txt')
409endfunction
410
411" Note: Test_netrw_a_empty_buffer_fastpath_wipe() should run before
412"       any other tests that open a netrw buffer (e.g, :Explore).
413func Test_netrw_a_empty_buffer_fastpath_wipe()
414  " SetUp() may have opened some buffers
415  let previous = bufnr('$')
416  let g:netrw_fastbrowse=0
417  call setline(1, 'foobar')
418  let  bufnr = bufnr('%')
419  tabnew
420  Explore
421  call search('README.txt', 'W')
422  exe ":norm \<cr>"
423  call assert_equal(previous + 2, bufnr('$'))
424  call assert_true(bufexists(bufnr))
425  bw
426
427  unlet! netrw_fastbrowse
428endfunction
429
430" Test UNC paths on windows
431func Test_netrw_check_UNC_paths()
432  CheckMSWindows
433
434  let test_paths = [
435  \ '\\Server2\Share\Test\Foo.txt',
436  \ '//Server2/Share/Test/Foo.txt',
437  \ '\\Server2\Share\Test\',
438  \ '//Server2/Share/Test/',
439  \ '\\wsl.localhost\Ubuntu\home\user\_vimrc',
440  \ '//wsl.localhost/Ubuntu/home/user/_vimrc',
441  \ '\\wsl.localhost\Ubuntu\home\user',
442  \ '//wsl.localhost/Ubuntu/home/user']
443
444  " The paths must be interpreted as absolute ones
445  for path in test_paths
446    call assert_equal(
447    \   path,
448    \   Test_NetrwFile(path),
449    \   $"UNC path: {path} misinterpreted")
450  endfor
451
452endfunction
453
454" ---------------------------------
455" Testing file management functions
456" ---------------------------------
457
458" Browser directory creation
459func s:netrw_mkdir()
460
461  " create a testdir in the fake $HOME
462  call Test_NetrwMakeDir($HOME, "NetrwMakeDir")
463
464  " Check the test directory was created
465  let test_dir = netrw#fs#PathJoin($HOME, "NetrwMakeDir")
466  call WaitForAssert({-> assert_true(
467  \     isdirectory(test_dir),
468  \     "Unable to create a dir via s:NetrwMakeDir()")
469  \ })
470
471  " remove the test directory
472  call delete(test_dir, 'd')
473endfunc
474
475func Test_netrw_mkdir_default()
476  call SetShell('default')
477  call s:netrw_mkdir()
478endfunc
479
480func Test_netrw_mkdir_powershell()
481  call SetShell('powershell')
482  call s:netrw_mkdir()
483endfunc
484
485func Test_netrw_mkdir_pwsh()
486  call SetShell('pwsh')
487  call s:netrw_mkdir()
488endfunc
489
490func s:netrw_filecopy(count = 1)
491  " setup
492  let marked_files = []
493  let home = expand('$HOME')
494  let source_dir = netrw#fs#PathJoin(home, "src")
495  let target_dir = netrw#fs#PathJoin(home, "target")
496
497  call mkdir(source_dir, "R")
498  call mkdir(target_dir, "R")
499
500  for i in range(a:count)
501    call add(marked_files, $"testfile{i}.txt")
502    call writefile(
503    \   [$"NetrwMarkFileCopy test file {i}"],
504    \   netrw#fs#PathJoin(source_dir, marked_files[-1]))
505  endfor
506
507  " delegate
508  call Test_NetrwMarkFileCopy(source_dir, target_dir, marked_files)
509
510  " verify
511  for file in marked_files
512    call assert_equalfile(
513    \   netrw#fs#PathJoin(source_dir, file),
514    \   netrw#fs#PathJoin(target_dir, file),
515    \   "File copy failed for " . file)
516  endfor
517endfunc
518
519" Browser file copy
520func s:test_netrw_filecopy()
521
522  " if shellslash is available, check both settings
523  if exists('+shellslash')
524    set shellslash&
525    call s:netrw_filecopy(1)
526    call s:netrw_filecopy(10)
527    set shellslash!
528  endif
529
530  call s:netrw_filecopy(1)
531  call s:netrw_filecopy(10)
532
533endfunc
534
535func Test_netrw_filecopy_default()
536  call SetShell('default')
537  call s:test_netrw_filecopy()
538endfunc
539
540func Test_netrw_filecopy_powershell()
541  call SetShell('powershell')
542  call s:test_netrw_filecopy()
543endfunc
544
545func Test_netrw_filecopy_pwsh()
546  call SetShell('pwsh')
547  call s:test_netrw_filecopy()
548endfunc
549
550" Browser recursive directory copy
551func s:netrw_dircopy(count = 1)
552
553  " setup
554  let marked_dirname = "test_dir"
555  let home = expand('$HOME')
556  let marked_dir = netrw#fs#PathJoin(home, marked_dirname)
557  let target_dir = netrw#fs#PathJoin(home, "target")
558
559  call mkdir(marked_dir, "R")
560  call mkdir(target_dir, "R")
561
562  let dir_content = []
563  for i in range(a:count)
564    call add(dir_content, $"testfile{i}.txt")
565    call writefile(
566    \   [$"NetrwMarkFileCopy test dir content {i}"],
567    \   netrw#fs#PathJoin(marked_dir, dir_content[-1]))
568  endfor
569
570  " delegate
571  call Test_NetrwMarkFileCopy(home, target_dir, [marked_dirname])
572
573  " verify
574  for file in dir_content
575    call assert_equalfile(
576    \   netrw#fs#PathJoin(marked_dir, file),
577    \   netrw#fs#PathJoin(target_dir, marked_dirname, file),
578    \   "File copy failed for " . file)
579  endfor
580
581endfunc
582
583func s:test_netrw_dircopy()
584
585  " if shellslash is available, check both settings
586  if exists('+shellslash')
587    set shellslash&
588    call s:netrw_dircopy(10)
589    set shellslash!
590  endif
591
592  call s:netrw_dircopy(10)
593
594endfunc
595
596func Test_netrw_dircopy_default()
597  call SetShell('default')
598  call s:test_netrw_dircopy()
599endfunc
600
601func Test_netrw_dircopy_powershell()
602  call SetShell('powershell')
603  call s:test_netrw_dircopy()
604endfunc
605
606func Test_netrw_dircopy_pwsh()
607  call SetShell('pwsh')
608  call s:test_netrw_dircopy()
609endfunc
610
611" Copy file into the same directory with a different name
612func Test_netrw_dircopy_rename_default()
613  call SetShell('default')
614  call Test_NetrwMarkFileCopy_SameDir()
615endfunc
616
617func Test_netrw_dircopy_rename_powershell()
618  call SetShell('powershell')
619  call Test_NetrwMarkFileCopy_SameDir()
620endfunc
621
622func Test_netrw_dircopy_rename_pwsh()
623  call SetShell('pwsh')
624  call Test_NetrwMarkFileCopy_SameDir()
625endfunc
626
627" Browser file move
628func s:netrw_filemove(count = 1)
629  " setup
630  let marked_files = []
631  let source_dir = netrw#fs#PathJoin($HOME, "src")
632  let target_dir = netrw#fs#PathJoin($HOME, "target")
633
634  call mkdir(source_dir, "R")
635  call mkdir(target_dir, "R")
636
637  for i in range(a:count)
638    call add(marked_files, $"testfile{i}.txt")
639    call writefile(
640    \   [$"NetrwMarkFileMove test file {i}"],
641    \   netrw#fs#PathJoin(source_dir, marked_files[-1]))
642  endfor
643
644  " delegate
645  call Test_NetrwMarkFileMove(source_dir, target_dir, marked_files)
646
647  " verify
648  for i in range(a:count)
649    call assert_equal(
650    \   [$"NetrwMarkFileMove test file {i}"],
651    \   readfile(netrw#fs#PathJoin(target_dir, $"testfile{i}.txt")),
652    \   $"File move failed for testfile{i}.txt")
653  endfor
654endfunc
655
656func s:test_netrw_filemove()
657
658  " if shellslash is available, check both settings
659  if exists('+shellslash')
660    set shellslash&
661    call s:netrw_filemove(10)
662    set shellslash!
663  endif
664
665  call s:netrw_filemove(10)
666
667endfunc
668
669func Test_netrw_filemove_default()
670  call SetShell('default')
671  call s:test_netrw_filemove()
672endfunc
673
674func Test_netrw_filemove_powershell()
675  call SetShell('powershell')
676  call s:test_netrw_filemove()
677endfunc
678
679func Test_netrw_filemove_pwsh()
680  call SetShell('pwsh')
681  call s:test_netrw_filemove()
682endfunc
683
684func Test_netrw_reject_evil_hostname()
685  let msg = execute(':e scp://x;touch RCE;x/dir/')
686  let msg = split(msg, "\n")[-1]
687  call assert_match('Rejecting invalid hostname', msg)
688endfunc
689
690func Test_netrw_hostname()
691  let valid_hostnames = [
692  \   'localhost',
693  \   '_gateway',
694  \   '127.0.0.1',
695  \   '::1',
696  \   '0:0:0:0:0:0:0:1',
697  \   'user@localhost',
698  \   'usuario@127.0.0.1',
699  \   'utilisateur@::1',
700  \   'benutzer@0:0:0:0:0:0:0:1',
701  \   'localhost:22',
702  \   '127.0.0.1:80',
703  \   '[::1]:443',
704  \   '[0:0:0:0:0:0:0:1]:5432',
705  \   'user@localhost:22',
706  \   'usuario@127.0.0.1:80',
707  \   'utilisateur@[::1]:443',
708  \   'benutzer@[0:0:0:0:0:0:0:1]:5432']
709
710  for hostname in valid_hostnames
711    call assert_true(Test_NetrwValidateHostname(hostname), $"Valid hostname {hostname} was rejected")
712  endfor
713endfunc
714
715func Test_netrw_FileUrlEdit_pipe_injection()
716  CheckUnix
717  CheckExecutable id
718  let fname = 'Xtestfile'
719  let url = 'file:///tmp/file.md%7C!id>'..fname
720  sil call netrw#FileUrlEdit(url)
721  call assert_false(filereadable(fname), 'Command injection via pipe in file URL')
722endfunc
723
724" The remote filename after '.' was allowed to contain shell metacharacters
725" and rode unescaped into the tempfile name passed to sftp/file_cmd, giving a
726" shell injection on :e sftp://host/foo.txt;<cmd>.
727func Test_netrw_tempfile_suffix_injection()
728  CheckUnix
729  CheckExecutable id
730  let save_sftp = g:netrw_sftp_cmd
731  let save_file = exists('g:netrw_file_cmd') ? g:netrw_file_cmd : v:null
732  let g:netrw_sftp_cmd = 'true'
733  let g:netrw_file_cmd = 'true'
734  let fname = 'Xrce_marker'
735  try
736    call delete(fname)
737    sil! call netrw#NetRead(2, 'sftp://localhost/foo.txt;id>'..fname)
738    call assert_false(filereadable(fname), 'Command injection via sftp:// tempfile suffix')
739
740    call delete(fname)
741    sil! call netrw#NetRead(2, 'file://localhost/foo.txt;id>'..fname)
742    call assert_false(filereadable(fname), 'Command injection via file:// tempfile suffix')
743  finally
744    call delete(fname)
745    let g:netrw_sftp_cmd = save_sftp
746    if save_file is v:null
747      unlet! g:netrw_file_cmd
748    else
749      let g:netrw_file_cmd = save_file
750    endif
751  endtry
752endfunc
753
754func Test_netrw_RFC2396()
755  let fname = 'a%20b'
756  call assert_equal('a b', netrw#RFC2396(fname))
757endfunc
758
759func Test_netrw_Home_tilde()
760  Explore ~
761  call assert_match('Netrw Directory Listing', getline(2))
762  bw!
763endfunc
764
765func Test_netrw_unmark_all()
766  call Test_NetrwUnMarkFile()
767endfunc
768
769" Creating a bookmark from a marked file should use b:netrw_curdir as head directory
770func Test_netrw_bookmark_marked_file()
771  let save_keepdir = g:netrw_keepdir
772  let save_workdir = getcwd()
773  let save_bookmarklist = exists('g:netrw_bookmarklist') ? g:netrw_bookmarklist : v:null
774
775  " Make sure Vim's working directory diverge from Netrw's
776  let g:netrw_keepdir = 1
777  let g:netrw_bookmarklist = []
778  let test_workdir = getcwd() . '/Xtest_workdir'
779  let test_netrw_curdir = test_workdir . '/Xtest_netrw_curdir'
780  call mkdir(test_netrw_curdir, 'p')
781  call writefile([], test_netrw_curdir . '/test_file')
782
783  execute 'cd ' . test_workdir
784  call Test_MakeBookmark(test_netrw_curdir, 'test_file')
785
786  " Bookmark paths should be absolute and normalized to prevent duplicates on win32
787  let expected_path = netrw#fs#AbsPath(test_netrw_curdir . '/test_file')
788  if has('win32')
789    let expected_path = substitute(expected_path, '\\', '/', 'ge')
790  endif
791  let expected_path = simplify(expected_path)
792
793  call assert_equal(1, len(g:netrw_bookmarklist))
794  call assert_equal(expected_path, g:netrw_bookmarklist[0])
795  call assert_true(isabsolutepath(g:netrw_bookmarklist[0]), 'Bookmark paths should be absolute')
796
797  " Tear down
798  execute 'cd ' . save_workdir
799  call delete(test_workdir, 'rf')
800
801  let g:netrw_keepdir = save_keepdir
802  if save_bookmarklist is v:null
803    unlet! g:netrw_bookmarklist
804  else
805    let g:netrw_bookmarklist = save_bookmarklist
806  endif
807
808  bw!
809endfunc
810
811" Typing gb or mB without a count should prompt
812" for a bookmark number through an inputlist().
813" Expected dialog output (gb): # | Goto Bookmark:
814"                               1| /foo/bar/baz
815"
816" Expected dialog output (mB): # | Delete Bookmark:
817"                               1| /foo/bar/baz
818func Test_netrw_bookmark_goto_delete_prompt()
819  let save_home = g:netrw_home
820  let save_bookmarklist = exists('g:netrw_bookmarklist') ? g:netrw_bookmarklist : v:null
821
822  let g:netrw_home = getcwd()
823  let g:netrw_bookmarklist = ['/foo/bar/baz']
824  Explore .
825
826  " Inject 'q' to cancel the inputlist() prompt
827  call feedkeys('q', 't')
828  let dialog_out = execute('normal gb')
829  call assert_match('Goto Bookmark:', dialog_out)
830
831  call feedkeys('q', 't')
832  let dialog_out = execute('normal mB')
833  call assert_match('Delete Bookmark:', dialog_out)
834
835  " Tear down
836  call delete(g:netrw_home . '/.netrwbook')
837  call delete(g:netrw_home . '/.netrwhist')
838  let g:netrw_home = save_home
839  if save_bookmarklist is v:null
840    unlet! g:netrw_bookmarklist
841  else
842    let g:netrw_bookmarklist = save_bookmarklist
843  endif
844
845  bw!
846endfunc
847
848func Test_netrw_markings_match_pattern_rebuild()
849  call Test_NetrwMarkFile_match_pattern_rebuild()
850endfunc
851
852func Test_netrw_mf_command_injection()
853  CheckUnix
854  CheckExecutable touch
855  let path = tempname()
856  let fname = 'x" . execute("silent! !touch poc") . "'
857  call mkdir(path, 'R')
858  let _cwd = getcwd()
859  exe "cd " path
860  call writefile([], fname)
861  Explore .
862  call search('^x')
863  :norm mf
864  :norm mf
865  call assert_false(filereadable('poc'), 'Command injection via mf command')
866  exe "cd " _cwd
867  bw!
868endfunc
869
870function Test_netrw_NetrwMaps_CR_dirname()
871  CheckNotMSWindows
872
873  let tmpdir = tempname() . '/evil<CR>:let g:netrw_pwn=1<CR>'
874  call mkdir(tmpdir, 'pR')
875  call assert_true(isdirectory(tmpdir))
876  exe ":Explore " tmpdir
877  " Fire D
878  " If the commands are injected successfully,
879  " this fails with
880  "  Vim(let):E488: Trailing characters: \ @ command line script
881  call feedkeys("D\<C-c>\<C-c>", "xt")
882  call assert_false(exists("g:netrw_pwn"))
883
884  unlet! g:netrw_pwn
885  bw!
886endfunction
887
888func Test_netrw_injection()
889  let g:netrw_home       = getcwd()
890  let savefile           = g:netrw_home . '/.netrwhist'
891  let g:netrw_dirhistmax = 10
892  let g:netrw_dirhistcnt = 1
893  let g:netrw_dirhist_1  = "x'|let g:injected = 1|let y='z"
894  call delete(savefile)
895  try
896    call netrw#Call('NetrwBookHistSave')
897    call assert_true(filereadable(savefile), savefile . ' must be written')
898    unlet g:netrw_dirhist_1
899    execute 'source ' . fnameescape(savefile)
900    call assert_false(exists("g:injected"), 'injected statement must not execute')
901    call assert_equal("x'|let g:injected = 1|let y='z", g:netrw_dirhist_1, 'dirname must round-trip')
902  finally
903    call delete(savefile)
904    unlet! g:netrw_home g:netrw_dirhistmax g:netrw_dirhistcnt g:netrw_dirhist_1 g:injected
905  endtry
906endfunc
907
908" Deleting a file whose name contains an Ex command separator must not let the
909" name inject commands into the :execute in s:NetrwLocalRmFile().
910func Test_netrw_local_rm_injection()
911  CheckUnix
912  let dir   = getcwd() . '/Xnetrwrm'
913  let fname = "x|let g:injected = 1"
914  call mkdir(dir, 'pR')
915  call writefile([], dir . '/' . fname)
916  try
917    call netrw#Call('NetrwLocalRmFile', dir, fname, 1)
918    call assert_false(exists('g:injected'), 'filename must not inject Ex commands')
919    " The file is removed before the sink, so its absence also confirms the
920    " vulnerable code path was actually exercised (not skipped on an error).
921    call assert_false(filereadable(dir . '/' . fname), 'crafted file must be deleted')
922  finally
923    call delete(dir . '/' . fname)
924    unlet! g:injected
925  endtry
926endfunc
927
928func Test_netrw_forward_slashes()
929  Explore
930  call assert_notmatch('\\', b:netrw_curdir)
931  bw!
932  Explore .
933  call assert_notmatch('\\', b:netrw_curdir)
934  bw!
935endfunc
936
937" Selecting a file whose name is a single backslash
938func Test_netrw_open_backslash_file()
939  CheckUnix
940
941  let dir   = getcwd() . '/Xbslash'
942  let fname = dir . '/\'
943  call mkdir(dir, 'pR')
944  call writefile(['backslash file content'], fname)
945  call assert_true(filereadable(fname))
946
947  " list the directory and move onto the '\' entry
948  exe 'Explore ' . dir
949  call assert_true(search('^\\$', 'w') > 0)
950
951  " open it
952  exe "normal \<CR>"
953
954  call assert_equal('\', expand('%:t'))
955  call assert_equal(['backslash file content'], getline(1, '$'))
956
957  bw!
958endfunc
959
960" :Explore without a [dir] argument should open the dir of the current file
961func Test_netrw_open_no_dir_arg()
962  let dir = tempname()
963  call mkdir(dir, 'pR')
964  call writefile([], dir . '/foo')
965  exe 'edit ' . dir . '/foo'
966  Explore
967  call assert_equal(fnamemodify(dir, ':p'), fnamemodify(b:netrw_curdir, ':p'))
968  bw!
969endfunc
970
971func Test_netrw_home_setting()
972  let save_home = get(g:, 'netrw_home', '')
973  let dir = fnamemodify('XnetrwHome', ':p')
974  let vimdir = fnamemodify('XvimDir', ':p')
975  let subdir = fnamemodify('XnetrwHomeParent/XnetrwHome', ':p')
976  if has('win32')
977    let dir = substitute(dir, '/', '\\', 'g')
978    let vimdir = substitute(vimdir, '/', '\\', 'g')
979    let subdir = substitute(subdir, '/', '\\', 'g')
980  endif
981  let save_myvimdir = getenv('MYVIMDIR')
982  let $MYVIMDIR = vimdir
983
984  unlet! g:netrw_home
985  if has('nvim')
986    let expected = netrw#fs#PathJoin(stdpath('state'), 'netrw')
987    if has('win32')
988      let expected = substitute(expected, '/', '\\', 'g')
989    endif
990    call assert_equal(expected, Test_NetrwHome())
991  else
992    " without the setting $MYVIMDIR is used
993    call assert_equal(vimdir, Test_NetrwHome())
994  endif
995
996  let g:netrw_home = dir
997  call assert_equal(dir, Test_NetrwHome())
998  call assert_true(isdirectory(dir))
999
1000  let g:netrw_home = subdir
1001  call assert_equal(subdir, Test_NetrwHome())
1002  call assert_true(isdirectory(subdir))
1003
1004  " the value is expanded
1005  let $NETRW_TEST_HOME = dir
1006  let g:netrw_home = '$NETRW_TEST_HOME'
1007  call assert_equal(dir, Test_NetrwHome())
1008
1009  call delete(dir, 'd')
1010  call delete(vimdir, 'd')
1011  call delete(subdir, 'd')
1012  call delete(fnamemodify(subdir, ':h'), 'd')
1013  unlet $NETRW_TEST_HOME
1014  call setenv('MYVIMDIR', save_myvimdir)
1015  if empty(save_home)
1016    unlet! g:netrw_home
1017  else
1018    let g:netrw_home = save_home
1019  endif
1020endfunc
1021
1022" vim:ts=8 sts=2 sw=2 et