Initial Commit
[packages] / xemacs-packages / tramp / lisp / tramp-smb.el
1 ;;; tramp-smb.el --- Tramp access functions for SMB servers
2
3 ;; Copyright (C) 2002-2015 Free Software Foundation, Inc.
4
5 ;; Author: Michael Albinus <michael.albinus@gmx.de>
6 ;; Keywords: comm, processes
7 ;; Package: tramp
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; Access functions for SMB servers like SAMBA or M$ Windows from Tramp.
27
28 ;;; Code:
29
30 (require 'tramp)
31
32 ;; Pacify byte-compiler.
33 (eval-when-compile
34   (require 'cl))
35
36 ;; Define SMB method ...
37 ;;;###tramp-autoload
38 (defconst tramp-smb-method "smb"
39   "Method to connect SAMBA and M$ SMB servers.")
40
41 ;; ... and add it to the method list.
42 ;;;###tramp-autoload
43 (unless (memq system-type '(cygwin windows-nt))
44   (add-to-list 'tramp-methods
45     `(,tramp-smb-method
46       ;; We define an empty command, because `tramp-smb-call-winexe'
47       ;; opens already the powershell.  Used in `tramp-handle-shell-command'.
48       (tramp-remote-shell "")
49       ;; This is just a guess.  We don't know whether the share "C$"
50       ;; is available for public use, and whether the user has write
51       ;; access.
52       (tramp-tmpdir "/C$/Temp"))))
53
54 ;; Add a default for `tramp-default-method-alist'. Rule: If there is
55 ;; a domain in USER, it must be the SMB method.
56 ;;;###tramp-autoload
57 (add-to-list 'tramp-default-method-alist
58              `(nil ,tramp-prefix-domain-regexp ,tramp-smb-method))
59
60 ;; Add a default for `tramp-default-user-alist'. Rule: For the SMB method,
61 ;; the anonymous user is chosen.
62 ;;;###tramp-autoload
63 (add-to-list 'tramp-default-user-alist
64              `(,(concat "\\`" tramp-smb-method "\\'") nil nil))
65
66 ;; Add completion function for SMB method.
67 ;;;###tramp-autoload
68 (eval-after-load 'tramp
69   '(tramp-set-completion-function
70     tramp-smb-method
71     '((tramp-parse-netrc "~/.netrc"))))
72
73 ;;;###tramp-autoload
74 (defcustom tramp-smb-program "smbclient"
75   "Name of SMB client to run."
76   :group 'tramp
77   :type 'string)
78
79 ;;;###tramp-autoload
80 (defcustom tramp-smb-acl-program "smbcacls"
81   "Name of SMB acls to run."
82   :group 'tramp
83   :type 'string
84   :version "24.4")
85
86 ;;;###tramp-autoload
87 (defcustom tramp-smb-conf "/dev/null"
88   "Path of the smb.conf file.
89 If it is nil, no smb.conf will be added to the `tramp-smb-program'
90 call, letting the SMB client use the default one."
91   :group 'tramp
92   :type '(choice (const nil) (file :must-match t)))
93
94 (defvar tramp-smb-version nil
95   "Version string of the SMB client.")
96
97 (defconst tramp-smb-server-version
98   "Domain=\\[[^]]*\\] OS=\\[[^]]*\\] Server=\\[[^]]*\\]"
99   "Regexp of SMB server identification.")
100
101 (defconst tramp-smb-prompt "^\\(smb:\\|PS\\) .+> \\|^\\s-+Server\\s-+Comment$"
102   "Regexp used as prompt in smbclient or powershell.")
103
104 (defconst tramp-smb-wrong-passwd-regexp
105   (regexp-opt
106    '("NT_STATUS_LOGON_FAILURE"
107      "NT_STATUS_WRONG_PASSWORD"))
108   "Regexp for login error strings of SMB servers.")
109
110 (defconst tramp-smb-errors
111   (mapconcat
112    'identity
113    `(;; Connection error / timeout / unknown command.
114      "Connection\\( to \\S-+\\)? failed"
115      "Read from server failed, maybe it closed the connection"
116      "Call timed out: server did not respond"
117      "\\S-+: command not found"
118      "Server doesn't support UNIX CIFS calls"
119      ,(regexp-opt
120        '(;; Samba.
121          "ERRDOS"
122          "ERRHRD"
123          "ERRSRV"
124          "ERRbadfile"
125          "ERRbadpw"
126          "ERRfilexists"
127          "ERRnoaccess"
128          "ERRnomem"
129          "ERRnosuchshare"
130          ;; Windows 4.0 (Windows NT), Windows 5.0 (Windows 2000),
131          ;; Windows 5.1 (Windows XP), Windows 5.2 (Windows Server 2003),
132          ;; Windows 6.0 (Windows Vista), Windows 6.1 (Windows 7).
133          "NT_STATUS_ACCESS_DENIED"
134          "NT_STATUS_ACCOUNT_LOCKED_OUT"
135          "NT_STATUS_BAD_NETWORK_NAME"
136          "NT_STATUS_CANNOT_DELETE"
137          "NT_STATUS_CONNECTION_REFUSED"
138          "NT_STATUS_DIRECTORY_NOT_EMPTY"
139          "NT_STATUS_DUPLICATE_NAME"
140          "NT_STATUS_FILE_IS_A_DIRECTORY"
141          "NT_STATUS_HOST_UNREACHABLE"
142          "NT_STATUS_IMAGE_ALREADY_LOADED"
143          "NT_STATUS_INVALID_LEVEL"
144          "NT_STATUS_IO_TIMEOUT"
145          "NT_STATUS_LOGON_FAILURE"
146          "NT_STATUS_NETWORK_ACCESS_DENIED"
147          "NT_STATUS_NOT_IMPLEMENTED"
148          "NT_STATUS_NO_LOGON_SERVERS"
149          "NT_STATUS_NO_SUCH_FILE"
150          "NT_STATUS_NO_SUCH_USER"
151          "NT_STATUS_OBJECT_NAME_COLLISION"
152          "NT_STATUS_OBJECT_NAME_INVALID"
153          "NT_STATUS_OBJECT_NAME_NOT_FOUND"
154          "NT_STATUS_SHARING_VIOLATION"
155          "NT_STATUS_TRUSTED_RELATIONSHIP_FAILURE"
156          "NT_STATUS_UNSUCCESSFUL"
157          "NT_STATUS_WRONG_PASSWORD")))
158    "\\|")
159   "Regexp for possible error strings of SMB servers.
160 Used instead of analyzing error codes of commands.")
161
162 (defconst tramp-smb-actions-with-share
163   '((tramp-smb-prompt tramp-action-succeed)
164     (tramp-password-prompt-regexp tramp-action-password)
165     (tramp-wrong-passwd-regexp tramp-action-permission-denied)
166     (tramp-smb-errors tramp-action-permission-denied)
167     (tramp-process-alive-regexp tramp-action-process-alive))
168   "List of pattern/action pairs.
169 This list is used for login to SMB servers.
170
171 See `tramp-actions-before-shell' for more info.")
172
173 (defconst tramp-smb-actions-without-share
174   '((tramp-password-prompt-regexp tramp-action-password)
175     (tramp-wrong-passwd-regexp tramp-action-permission-denied)
176     (tramp-smb-errors tramp-action-permission-denied)
177     (tramp-process-alive-regexp tramp-action-out-of-band))
178   "List of pattern/action pairs.
179 This list is used for login to SMB servers.
180
181 See `tramp-actions-before-shell' for more info.")
182
183 (defconst tramp-smb-actions-with-tar
184   '((tramp-password-prompt-regexp tramp-action-password)
185     (tramp-wrong-passwd-regexp tramp-action-permission-denied)
186     (tramp-smb-errors tramp-action-permission-denied)
187     (tramp-process-alive-regexp tramp-smb-action-with-tar))
188   "List of pattern/action pairs.
189 This list is used for tar-like copy of directories.
190
191 See `tramp-actions-before-shell' for more info.")
192
193 (defconst tramp-smb-actions-get-acl
194   '((tramp-password-prompt-regexp tramp-action-password)
195     (tramp-wrong-passwd-regexp tramp-action-permission-denied)
196     (tramp-smb-errors tramp-action-permission-denied)
197     (tramp-process-alive-regexp tramp-smb-action-get-acl))
198   "List of pattern/action pairs.
199 This list is used for smbcacls actions.
200
201 See `tramp-actions-before-shell' for more info.")
202
203 (defconst tramp-smb-actions-set-acl
204   '((tramp-password-prompt-regexp tramp-action-password)
205     (tramp-wrong-passwd-regexp tramp-action-permission-denied)
206     (tramp-smb-errors tramp-action-permission-denied)
207     (tramp-process-alive-regexp tramp-smb-action-set-acl))
208   "List of pattern/action pairs.
209 This list is used for smbcacls actions.
210
211 See `tramp-actions-before-shell' for more info.")
212
213 ;; New handlers should be added here.
214 (defconst tramp-smb-file-name-handler-alist
215   '(;; `access-file' performed by default handler.
216     (add-name-to-file . tramp-smb-handle-add-name-to-file)
217     ;; `byte-compiler-base-file-name' performed by default handler.
218     (copy-directory . tramp-smb-handle-copy-directory)
219     (copy-file . tramp-smb-handle-copy-file)
220     (delete-directory . tramp-smb-handle-delete-directory)
221     (delete-file . tramp-smb-handle-delete-file)
222     ;; `diff-latest-backup-file' performed by default handler.
223     (directory-file-name . tramp-handle-directory-file-name)
224     (directory-files . tramp-smb-handle-directory-files)
225     (directory-files-and-attributes
226      . tramp-handle-directory-files-and-attributes)
227     (dired-call-process . ignore)
228     (dired-compress-file . ignore)
229     (dired-uncache . tramp-handle-dired-uncache)
230     (expand-file-name . tramp-smb-handle-expand-file-name)
231     (file-accessible-directory-p . tramp-smb-handle-file-directory-p)
232     (file-acl . tramp-smb-handle-file-acl)
233     (file-attributes . tramp-smb-handle-file-attributes)
234     (file-directory-p .  tramp-smb-handle-file-directory-p)
235     (file-file-equal-p . tramp-handle-file-equal-p)
236     (file-executable-p . tramp-handle-file-exists-p)
237     (file-exists-p . tramp-handle-file-exists-p)
238     (file-in-directory-p . tramp-handle-file-in-directory-p)
239     (file-local-copy . tramp-smb-handle-file-local-copy)
240     (file-modes . tramp-handle-file-modes)
241     (file-name-all-completions . tramp-smb-handle-file-name-all-completions)
242     (file-name-as-directory . tramp-handle-file-name-as-directory)
243     (file-name-completion . tramp-handle-file-name-completion)
244     (file-name-directory . tramp-handle-file-name-directory)
245     (file-name-nondirectory . tramp-handle-file-name-nondirectory)
246     ;; `file-name-sans-versions' performed by default handler.
247     (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
248     (file-notify-add-watch . tramp-handle-file-notify-add-watch)
249     (file-notify-rm-watch . tramp-handle-file-notify-rm-watch)
250     (file-notify-valid-p . tramp-handle-file-notify-valid-p)
251     (file-ownership-preserved-p . ignore)
252     (file-readable-p . tramp-handle-file-exists-p)
253     (file-regular-p . tramp-handle-file-regular-p)
254     (file-remote-p . tramp-handle-file-remote-p)
255     ;; `file-selinux-context' performed by default handler.
256     (file-symlink-p . tramp-handle-file-symlink-p)
257     ;; `file-truename' performed by default handler.
258     (file-writable-p . tramp-smb-handle-file-writable-p)
259     (find-backup-file-name . tramp-handle-find-backup-file-name)
260     ;; `find-file-noselect' performed by default handler.
261     ;; `get-file-buffer' performed by default handler.
262     (insert-directory . tramp-smb-handle-insert-directory)
263     (insert-file-contents . tramp-handle-insert-file-contents)
264     (load . tramp-handle-load)
265     (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
266     (make-directory . tramp-smb-handle-make-directory)
267     (make-directory-internal . tramp-smb-handle-make-directory-internal)
268     (make-symbolic-link . tramp-smb-handle-make-symbolic-link)
269     (process-file . tramp-smb-handle-process-file)
270     (rename-file . tramp-smb-handle-rename-file)
271     (set-file-acl . tramp-smb-handle-set-file-acl)
272     (set-file-modes . tramp-smb-handle-set-file-modes)
273     (set-file-selinux-context . ignore)
274     (set-file-times . ignore)
275     (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
276     (shell-command . tramp-handle-shell-command)
277     (start-file-process . tramp-smb-handle-start-file-process)
278     (substitute-in-file-name . tramp-smb-handle-substitute-in-file-name)
279     (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
280     (vc-registered . ignore)
281     (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
282     (write-region . tramp-smb-handle-write-region))
283   "Alist of handler functions for Tramp SMB method.
284 Operations not mentioned here will be handled by the default Emacs primitives.")
285
286 ;; Options for remote processes via winexe.
287 ;;;###tramp-autoload
288 (defcustom tramp-smb-winexe-program "winexe"
289   "Name of winexe client to run.
290 If it isn't found in the local $PATH, the absolute path of winexe
291 shall be given.  This is needed for remote processes."
292   :group 'tramp
293   :type 'string
294   :version "24.3")
295
296 ;;;###tramp-autoload
297 (defcustom tramp-smb-winexe-shell-command "powershell.exe"
298   "Shell to be used for processes on remote machines.
299 This must be Powershell V2 compatible."
300   :group 'tramp
301   :type 'string
302   :version "24.3")
303
304 ;;;###tramp-autoload
305 (defcustom tramp-smb-winexe-shell-command-switch "-file -"
306   "Command switch used together with `tramp-smb-winexe-shell-command'.
307 This can be used to disable echo etc."
308   :group 'tramp
309   :type 'string
310   :version "24.3")
311
312 ;; It must be a `defsubst' in order to push the whole code into
313 ;; tramp-loaddefs.el.  Otherwise, there would be recursive autoloading.
314 ;;;###tramp-autoload
315 (defsubst tramp-smb-file-name-p (filename)
316   "Check if it's a filename for SMB servers."
317   (string= (tramp-file-name-method (tramp-dissect-file-name filename))
318            tramp-smb-method))
319
320 ;;;###tramp-autoload
321 (defun tramp-smb-file-name-handler (operation &rest args)
322   "Invoke the SMB related OPERATION.
323 First arg specifies the OPERATION, second arg is a list of arguments to
324 pass to the OPERATION."
325   (let ((fn (assoc operation tramp-smb-file-name-handler-alist)))
326     (if fn
327         (save-match-data (apply (cdr fn) args))
328       (tramp-run-real-handler operation args))))
329
330 ;;;###tramp-autoload
331 (unless (memq system-type '(cygwin windows-nt))
332   (add-to-list 'tramp-foreign-file-name-handler-alist
333                (cons 'tramp-smb-file-name-p 'tramp-smb-file-name-handler)))
334
335
336 ;; File name primitives.
337
338 (defun tramp-smb-handle-add-name-to-file
339   (filename newname &optional ok-if-already-exists)
340   "Like `add-name-to-file' for Tramp files."
341   (unless (tramp-equal-remote filename newname)
342     (with-parsed-tramp-file-name
343         (if (tramp-tramp-file-p filename) filename newname) nil
344       (tramp-error
345        v 'file-error
346        "add-name-to-file: %s"
347        "only implemented for same method, same user, same host")))
348   (with-parsed-tramp-file-name filename v1
349     (with-parsed-tramp-file-name newname v2
350       (when (file-directory-p filename)
351         (tramp-error
352          v2 'file-error
353          "add-name-to-file: %s must not be a directory" filename))
354       (when (and (not ok-if-already-exists)
355                  (file-exists-p newname)
356                  (not (numberp ok-if-already-exists))
357                  (y-or-n-p
358                   (format
359                    "File %s already exists; make it a new name anyway? "
360                    newname)))
361         (tramp-error
362          v2 'file-error
363          "add-name-to-file: file %s already exists" newname))
364       ;; We must also flush the cache of the directory, because
365       ;; `file-attributes' reads the values from there.
366       (tramp-flush-file-property v2 (file-name-directory v2-localname))
367       (tramp-flush-file-property v2 v2-localname)
368       (unless
369           (tramp-smb-send-command
370            v1
371            (format
372             "%s \"%s\" \"%s\""
373             (if (tramp-smb-get-cifs-capabilities v1) "link" "hardlink")
374             (tramp-smb-get-localname v1)
375             (tramp-smb-get-localname v2)))
376         (tramp-error
377          v2 'file-error
378          "error with add-name-to-file, see buffer `%s' for details"
379          (buffer-name))))))
380
381 (defun tramp-smb-action-with-tar (proc vec)
382   "Untar from connection buffer."
383   (if (not (memq (process-status proc) '(run open)))
384       (throw 'tramp-action 'process-died)
385
386     (with-current-buffer (tramp-get-connection-buffer vec)
387       (goto-char (point-min))
388       (when (search-forward-regexp tramp-smb-server-version nil t)
389         ;; There might be a hidden password prompt.
390         (widen)
391         (forward-line)
392         (tramp-message vec 6 (buffer-substring (point-min) (point)))
393         (delete-region (point-min) (point))
394         (throw 'tramp-action 'ok)))))
395
396 (defun tramp-smb-handle-copy-directory
397   (dirname newname &optional keep-date parents copy-contents)
398   "Like `copy-directory' for Tramp files."
399   (if copy-contents
400       ;; We must do it file-wise.
401       (tramp-run-real-handler
402        'copy-directory (list dirname newname keep-date parents copy-contents))
403
404     (setq dirname (expand-file-name dirname)
405           newname (expand-file-name newname))
406     (let ((t1 (tramp-tramp-file-p dirname))
407           (t2 (tramp-tramp-file-p newname)))
408       (with-parsed-tramp-file-name (if t1 dirname newname) nil
409         (with-tramp-progress-reporter
410             v 0 (format "Copying %s to %s" dirname newname)
411           (cond
412            ;; We must use a local temporary directory.
413            ((and t1 t2)
414             (let ((tmpdir
415                    (make-temp-name
416                     (expand-file-name
417                      tramp-temp-name-prefix
418                      (tramp-compat-temporary-file-directory)))))
419               (unwind-protect
420                   (progn
421                     (make-directory tmpdir)
422                     (tramp-compat-copy-directory
423                      dirname tmpdir keep-date 'parents)
424                     (tramp-compat-copy-directory
425                      (expand-file-name (file-name-nondirectory dirname) tmpdir)
426                      newname keep-date parents))
427                 (tramp-compat-delete-directory tmpdir 'recursive))))
428
429            ;; We can copy recursively.
430            ((or t1 t2)
431             (when (and (file-directory-p newname)
432                        (not (string-equal (file-name-nondirectory dirname)
433                                           (file-name-nondirectory newname))))
434               (setq newname
435                     (expand-file-name
436                      (file-name-nondirectory dirname) newname))
437               (if t2 (setq v (tramp-dissect-file-name newname))))
438             (if (not (file-directory-p newname))
439                 (make-directory newname parents))
440
441             (setq tramp-current-method (tramp-file-name-method v)
442                   tramp-current-user (tramp-file-name-user v)
443                   tramp-current-host (tramp-file-name-real-host v))
444
445             (let* ((real-user (tramp-file-name-real-user v))
446                    (real-host (tramp-file-name-real-host v))
447                    (domain    (tramp-file-name-domain v))
448                    (port      (tramp-file-name-port v))
449                    (share     (tramp-smb-get-share v))
450                    (localname (file-name-as-directory
451                                (tramp-compat-replace-regexp-in-string
452                                 "\\\\" "/" (tramp-smb-get-localname v))))
453                    (tmpdir    (make-temp-name
454                                (expand-file-name
455                                 tramp-temp-name-prefix
456                                 (tramp-compat-temporary-file-directory))))
457                    (args      (list (concat "//" real-host "/" share) "-E")))
458
459               (if (not (zerop (length real-user)))
460                   (setq args (append args (list "-U" real-user)))
461                 (setq args (append args (list "-N"))))
462
463               (when domain (setq args (append args (list "-W" domain))))
464               (when port   (setq args (append args (list "-p" port))))
465               (when tramp-smb-conf
466                 (setq args (append args (list "-s" tramp-smb-conf))))
467               (setq args
468                     (if t1
469                         ;; Source is remote.
470                         (append args
471                                 (list "-D" (shell-quote-argument localname)
472                                       "-c" (shell-quote-argument "tar qc - *")
473                                       "|" "tar" "xfC" "-"
474                                       (shell-quote-argument tmpdir)))
475                       ;; Target is remote.
476                       (append (list "tar" "cfC" "-"
477                                     (shell-quote-argument dirname) "." "|")
478                               args
479                               (list "-D" (shell-quote-argument localname)
480                                     "-c" (shell-quote-argument "tar qx -")))))
481
482               (unwind-protect
483                   (with-temp-buffer
484                     ;; Set the transfer process properties.
485                     (tramp-set-connection-property
486                      v "process-name" (buffer-name (current-buffer)))
487                     (tramp-set-connection-property
488                      v "process-buffer" (current-buffer))
489
490                     (when t1
491                       ;; The smbclient tar command creates always
492                       ;; complete paths.  We must emulate the
493                       ;; directory structure, and symlink to the real
494                       ;; target.
495                       (make-directory
496                        (expand-file-name
497                         ".." (concat tmpdir localname)) 'parents)
498                       (make-symbolic-link
499                        newname (directory-file-name (concat tmpdir localname))))
500
501                     ;; Use an asynchronous processes.  By this,
502                     ;; password can be handled.
503                     (let* ((default-directory tmpdir)
504                            (p (apply
505                                'start-process
506                                (tramp-get-connection-name v)
507                                (tramp-get-connection-buffer v)
508                                tramp-smb-program args)))
509
510                       (tramp-message
511                        v 6 "%s" (mapconcat 'identity (process-command p) " "))
512                       (tramp-set-connection-property p "vector" v)
513                       (tramp-compat-set-process-query-on-exit-flag p nil)
514                       (tramp-process-actions p v nil tramp-smb-actions-with-tar)
515
516                       (while (memq (process-status p) '(run open))
517                         (sit-for 0.1))
518                       (tramp-message v 6 "\n%s" (buffer-string))))
519
520                 ;; Reset the transfer process properties.
521                 (tramp-set-connection-property v "process-name" nil)
522                 (tramp-set-connection-property v "process-buffer" nil)
523                 (when t1 (tramp-compat-delete-directory tmpdir 'recurse))))
524
525             ;; Handle KEEP-DATE argument.
526             (when keep-date
527               (set-file-times newname (nth 5 (file-attributes dirname))))
528
529             ;; Set the mode.
530             (unless keep-date
531               (set-file-modes newname (tramp-default-file-modes dirname)))
532
533             ;; When newname did exist, we have wrong cached values.
534             (when t2
535               (with-parsed-tramp-file-name newname nil
536                 (tramp-flush-file-property v (file-name-directory localname))
537                 (tramp-flush-file-property v localname))))
538
539            ;; We must do it file-wise.
540            (t
541             (tramp-run-real-handler
542              'copy-directory (list dirname newname keep-date parents)))))))))
543
544 (defun tramp-smb-handle-copy-file
545   (filename newname &optional ok-if-already-exists keep-date
546             _preserve-uid-gid _preserve-extended-attributes)
547   "Like `copy-file' for Tramp files.
548 KEEP-DATE has no effect in case NEWNAME resides on an SMB server.
549 PRESERVE-UID-GID and PRESERVE-EXTENDED-ATTRIBUTES are completely ignored."
550   (setq filename (expand-file-name filename)
551         newname (expand-file-name newname))
552   (with-tramp-progress-reporter
553       (tramp-dissect-file-name
554        (if (tramp-tramp-file-p filename) filename newname))
555       0 (format "Copying %s to %s" filename newname)
556
557     (if (file-directory-p filename)
558         (tramp-compat-copy-directory filename newname keep-date t t)
559
560       (let ((tmpfile (file-local-copy filename)))
561         (if tmpfile
562             ;; Remote filename.
563             (condition-case err
564                 (rename-file tmpfile newname ok-if-already-exists)
565               ((error quit)
566                (delete-file tmpfile)
567                (signal (car err) (cdr err))))
568
569           ;; Remote newname.
570           (when (file-directory-p newname)
571             (setq newname
572                   (expand-file-name (file-name-nondirectory filename) newname)))
573
574           (with-parsed-tramp-file-name newname nil
575             (when (and (not ok-if-already-exists)
576                        (file-exists-p newname))
577               (tramp-error v 'file-already-exists newname))
578
579             ;; We must also flush the cache of the directory, because
580             ;; `file-attributes' reads the values from there.
581             (tramp-flush-file-property v (file-name-directory localname))
582             (tramp-flush-file-property v localname)
583             (unless (tramp-smb-get-share v)
584               (tramp-error
585                v 'file-error "Target `%s' must contain a share name" newname))
586             (unless (tramp-smb-send-command
587                      v (format "put \"%s\" \"%s\""
588                                filename (tramp-smb-get-localname v)))
589               (tramp-error
590                v 'file-error "Cannot copy `%s' to `%s'" filename newname))))))
591
592     ;; KEEP-DATE handling.
593     (when keep-date
594       (set-file-times newname (nth 5 (file-attributes filename))))))
595
596 (defun tramp-smb-handle-delete-directory (directory &optional recursive)
597   "Like `delete-directory' for Tramp files."
598   (setq directory (directory-file-name (expand-file-name directory)))
599   (when (file-exists-p directory)
600     (if recursive
601         (mapc
602          (lambda (file)
603            (if (file-directory-p file)
604                (tramp-compat-delete-directory file recursive)
605              (delete-file file)))
606          ;; We do not want to delete "." and "..".
607          (directory-files
608           directory 'full "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*")))
609
610     (with-parsed-tramp-file-name directory nil
611       ;; We must also flush the cache of the directory, because
612       ;; `file-attributes' reads the values from there.
613       (tramp-flush-file-property v (file-name-directory localname))
614       (tramp-flush-directory-property v localname)
615       (unless (tramp-smb-send-command
616                v (format
617                   "%s \"%s\""
618                   (if (tramp-smb-get-cifs-capabilities v) "posix_rmdir" "rmdir")
619                   (tramp-smb-get-localname v)))
620         ;; Error.
621         (with-current-buffer (tramp-get-connection-buffer v)
622           (goto-char (point-min))
623           (search-forward-regexp tramp-smb-errors nil t)
624           (tramp-error
625            v 'file-error "%s `%s'" (match-string 0) directory))))))
626
627 (defun tramp-smb-handle-delete-file (filename &optional _trash)
628   "Like `delete-file' for Tramp files."
629   (setq filename (expand-file-name filename))
630   (when (file-exists-p filename)
631     (with-parsed-tramp-file-name filename nil
632       ;; We must also flush the cache of the directory, because
633       ;; `file-attributes' reads the values from there.
634       (tramp-flush-file-property v (file-name-directory localname))
635       (tramp-flush-file-property v localname)
636       (unless (tramp-smb-send-command
637                v (format
638                   "%s \"%s\""
639                   (if (tramp-smb-get-cifs-capabilities v) "posix_unlink" "rm")
640                   (tramp-smb-get-localname v)))
641         ;; Error.
642         (with-current-buffer (tramp-get-connection-buffer v)
643           (goto-char (point-min))
644           (search-forward-regexp tramp-smb-errors nil t)
645           (tramp-error
646            v 'file-error "%s `%s'" (match-string 0) filename))))))
647
648 (defun tramp-smb-handle-directory-files
649   (directory &optional full match nosort)
650   "Like `directory-files' for Tramp files."
651   (let ((result (mapcar 'directory-file-name
652                         (file-name-all-completions "" directory))))
653     ;; Discriminate with regexp.
654     (when match
655       (setq result
656             (delete nil
657                     (mapcar (lambda (x) (when (string-match match x) x))
658                             result))))
659     ;; Append directory.
660     (when full
661       (setq result
662             (mapcar
663              (lambda (x) (format "%s/%s" directory x))
664              result)))
665     ;; Sort them if necessary.
666     (unless nosort (setq result (sort result 'string-lessp)))
667     ;; Remove double entries.
668     (tramp-compat-delete-dups result)))
669
670 (defun tramp-smb-handle-expand-file-name (name &optional dir)
671   "Like `expand-file-name' for Tramp files."
672   ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
673   (setq dir (or dir default-directory "/"))
674   ;; Unless NAME is absolute, concat DIR and NAME.
675   (unless (file-name-absolute-p name)
676     (setq name (concat (file-name-as-directory dir) name)))
677   ;; If NAME is not a Tramp file, run the real handler.
678   (if (not (tramp-tramp-file-p name))
679       (tramp-run-real-handler 'expand-file-name (list name nil))
680     ;; Dissect NAME.
681     (with-parsed-tramp-file-name name nil
682       ;; Tilde expansion if necessary.  We use the user name as share,
683       ;; which is often the case in domains.
684       (when (string-match "\\`/?~\\([^/]*\\)" localname)
685         (setq localname
686               (replace-match
687                (if (zerop (length (match-string 1 localname)))
688                    (tramp-file-name-real-user v)
689                  (match-string 1 localname))
690                nil nil localname)))
691       ;; Make the file name absolute.
692       (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
693         (setq localname (concat "/" localname)))
694       ;; No tilde characters in file name, do normal
695       ;; `expand-file-name' (this does "/./" and "/../").
696       (tramp-make-tramp-file-name
697        method user host
698        (tramp-run-real-handler 'expand-file-name (list localname))))))
699
700 (defun tramp-smb-action-get-acl (proc vec)
701   "Read ACL data from connection buffer."
702   (when (not (memq (process-status proc) '(run open)))
703     ;; Accept pending output.
704     (while (tramp-accept-process-output proc 0.1))
705     (with-current-buffer (tramp-get-connection-buffer vec)
706       ;; There might be a hidden password prompt.
707       (widen)
708       (tramp-message vec 10 "\n%s" (buffer-string))
709       (goto-char (point-min))
710       (while (and (not (eobp)) (not (looking-at "^REVISION:")))
711         (forward-line)
712         (delete-region (point-min) (point)))
713       (while (and (not (eobp)) (looking-at "^.+:.+"))
714         (forward-line))
715       (delete-region (point) (point-max))
716       (throw 'tramp-action 'ok))))
717
718 (defun tramp-smb-handle-file-acl (filename)
719   "Like `file-acl' for Tramp files."
720   (with-parsed-tramp-file-name filename nil
721     (with-tramp-file-property v localname "file-acl"
722       (when (executable-find tramp-smb-acl-program)
723
724         (setq tramp-current-method (tramp-file-name-method v)
725               tramp-current-user (tramp-file-name-user v)
726               tramp-current-host (tramp-file-name-real-host v))
727
728         (let* ((real-user (tramp-file-name-real-user v))
729                (real-host (tramp-file-name-real-host v))
730                (domain    (tramp-file-name-domain v))
731                (port      (tramp-file-name-port v))
732                (share     (tramp-smb-get-share v))
733                (localname (tramp-compat-replace-regexp-in-string
734                            "\\\\" "/" (tramp-smb-get-localname v)))
735                (args      (list (concat "//" real-host "/" share) "-E")))
736
737           (if (not (zerop (length real-user)))
738               (setq args (append args (list "-U" real-user)))
739             (setq args (append args (list "-N"))))
740
741           (when domain (setq args (append args (list "-W" domain))))
742           (when port   (setq args (append args (list "-p" port))))
743           (when tramp-smb-conf
744             (setq args (append args (list "-s" tramp-smb-conf))))
745           (setq
746            args
747            (append args (list (shell-quote-argument localname) "2>/dev/null")))
748
749           (unwind-protect
750               (with-temp-buffer
751                 ;; Set the transfer process properties.
752                 (tramp-set-connection-property
753                  v "process-name" (buffer-name (current-buffer)))
754                 (tramp-set-connection-property
755                  v "process-buffer" (current-buffer))
756
757                 ;; Use an asynchronous processes.  By this, password
758                 ;; can be handled.
759                 (let ((p (apply
760                           'start-process
761                           (tramp-get-connection-name v)
762                           (tramp-get-connection-buffer v)
763                           tramp-smb-acl-program args)))
764
765                   (tramp-message
766                    v 6 "%s" (mapconcat 'identity (process-command p) " "))
767                   (tramp-set-connection-property p "vector" v)
768                   (tramp-compat-set-process-query-on-exit-flag p nil)
769                   (tramp-process-actions p v nil tramp-smb-actions-get-acl)
770                   (when (> (point-max) (point-min))
771                     (tramp-compat-funcall
772                      'substring-no-properties (buffer-string)))))
773
774             ;; Reset the transfer process properties.
775             (tramp-set-connection-property v "process-name" nil)
776             (tramp-set-connection-property v "process-buffer" nil)))))))
777
778 (defun tramp-smb-handle-file-attributes (filename &optional id-format)
779   "Like `file-attributes' for Tramp files."
780   (unless id-format (setq id-format 'integer))
781   (ignore-errors
782     (with-parsed-tramp-file-name filename nil
783       (with-tramp-file-property
784           v localname (format "file-attributes-%s" id-format)
785         (if (tramp-smb-get-stat-capability v)
786             (tramp-smb-do-file-attributes-with-stat v id-format)
787           ;; Reading just the filename entry via "dir localname" is not
788           ;; possible, because when filename is a directory, some
789           ;; smbclient versions return the content of the directory, and
790           ;; other versions don't.  Therefore, the whole content of the
791           ;; upper directory is retrieved, and the entry of the filename
792           ;; is extracted from.
793           (let* ((entries (tramp-smb-get-file-entries
794                            (file-name-directory filename)))
795                  (entry (assoc (file-name-nondirectory filename) entries))
796                  (uid (if (equal id-format 'string) "nobody" -1))
797                  (gid (if (equal id-format 'string) "nogroup" -1))
798                  (inode (tramp-get-inode v))
799                  (device (tramp-get-device v)))
800
801             ;; Check result.
802             (when entry
803               (list (and (string-match "d" (nth 1 entry))
804                          t)        ;0 file type
805                     -1             ;1 link count
806                     uid            ;2 uid
807                     gid            ;3 gid
808                     '(0 0)         ;4 atime
809                     (nth 3 entry)  ;5 mtime
810                     '(0 0)         ;6 ctime
811                     (nth 2 entry)  ;7 size
812                     (nth 1 entry)  ;8 mode
813                     nil            ;9 gid weird
814                     inode          ;10 inode number
815                     device)))))))) ;11 file system number
816
817 (defun tramp-smb-do-file-attributes-with-stat (vec &optional id-format)
818   "Implement `file-attributes' for Tramp files using stat command."
819   (tramp-message
820    vec 5 "file attributes with stat: %s" (tramp-file-name-localname vec))
821   (with-current-buffer (tramp-get-connection-buffer vec)
822     (let* (size id link uid gid atime mtime ctime mode inode)
823       (when (tramp-smb-send-command
824              vec (format "stat \"%s\"" (tramp-smb-get-localname vec)))
825
826         ;; Loop the listing.
827         (goto-char (point-min))
828         (unless (re-search-forward tramp-smb-errors nil t)
829           (while (not (eobp))
830             (cond
831              ((looking-at
832                "Size:\\s-+\\([0-9]+\\)\\s-+Blocks:\\s-+[0-9]+\\s-+\\(\\w+\\)")
833               (setq size (string-to-number (match-string 1))
834                     id (if (string-equal "directory" (match-string 2)) t
835                          (if (string-equal "symbolic" (match-string 2)) ""))))
836              ((looking-at
837                "Inode:\\s-+\\([0-9]+\\)\\s-+Links:\\s-+\\([0-9]+\\)")
838               (setq inode (string-to-number (match-string 1))
839                     link (string-to-number (match-string 2))))
840              ((looking-at
841                "Access:\\s-+([0-9]+/\\(\\S-+\\))\\s-+Uid:\\s-+\\([0-9]+\\)\\s-+Gid:\\s-+\\([0-9]+\\)")
842               (setq mode (match-string 1)
843                     uid (if (equal id-format 'string) (match-string 2)
844                           (string-to-number (match-string 2)))
845                     gid (if (equal id-format 'string) (match-string 3)
846                           (string-to-number (match-string 3)))))
847              ((looking-at
848                "Access:\\s-+\\([0-9]+\\)-\\([0-9]+\\)-\\([0-9]+\\)\\s-+\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)")
849               (setq atime
850                     (encode-time
851                      (string-to-number (match-string 6)) ;; sec
852                      (string-to-number (match-string 5)) ;; min
853                      (string-to-number (match-string 4)) ;; hour
854                      (string-to-number (match-string 3)) ;; day
855                      (string-to-number (match-string 2)) ;; month
856                      (string-to-number (match-string 1))))) ;; year
857              ((looking-at
858                "Modify:\\s-+\\([0-9]+\\)-\\([0-9]+\\)-\\([0-9]+\\)\\s-+\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)")
859               (setq mtime
860                     (encode-time
861                      (string-to-number (match-string 6)) ;; sec
862                      (string-to-number (match-string 5)) ;; min
863                      (string-to-number (match-string 4)) ;; hour
864                      (string-to-number (match-string 3)) ;; day
865                      (string-to-number (match-string 2)) ;; month
866                      (string-to-number (match-string 1))))) ;; year
867              ((looking-at
868                "Change:\\s-+\\([0-9]+\\)-\\([0-9]+\\)-\\([0-9]+\\)\\s-+\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)")
869               (setq ctime
870                     (encode-time
871                      (string-to-number (match-string 6)) ;; sec
872                      (string-to-number (match-string 5)) ;; min
873                      (string-to-number (match-string 4)) ;; hour
874                      (string-to-number (match-string 3)) ;; day
875                      (string-to-number (match-string 2)) ;; month
876                      (string-to-number (match-string 1)))))) ;; year
877             (forward-line))
878           ;; Return the result.
879           (list id link uid gid atime mtime ctime size mode nil inode
880                 (tramp-get-device vec)))))))
881
882 (defun tramp-smb-handle-file-directory-p (filename)
883   "Like `file-directory-p' for Tramp files."
884   (and (file-exists-p filename)
885        (eq ?d (aref (nth 8 (file-attributes filename)) 0))))
886
887 (defun tramp-smb-handle-file-local-copy (filename)
888   "Like `file-local-copy' for Tramp files."
889   (with-parsed-tramp-file-name filename nil
890     (unless (file-exists-p filename)
891       (tramp-error
892        v 'file-error
893        "Cannot make local copy of non-existing file `%s'" filename))
894     (let ((tmpfile (tramp-compat-make-temp-file filename)))
895       (with-tramp-progress-reporter
896           v 3 (format "Fetching %s to tmp file %s" filename tmpfile)
897         (unless (tramp-smb-send-command
898                  v (format "get \"%s\" \"%s\""
899                            (tramp-smb-get-localname v) tmpfile))
900           ;; Oops, an error.  We shall cleanup.
901           (delete-file tmpfile)
902           (tramp-error
903            v 'file-error "Cannot make local copy of file `%s'" filename)))
904       tmpfile)))
905
906 ;; This function should return "foo/" for directories and "bar" for
907 ;; files.
908 (defun tramp-smb-handle-file-name-all-completions (filename directory)
909   "Like `file-name-all-completions' for Tramp files."
910   (all-completions
911    filename
912    (with-parsed-tramp-file-name directory nil
913      (with-tramp-file-property v localname "file-name-all-completions"
914        (save-match-data
915          (let ((entries (tramp-smb-get-file-entries directory)))
916            (mapcar
917             (lambda (x)
918               (list
919                (if (string-match "d" (nth 1 x))
920                    (file-name-as-directory (nth 0 x))
921                  (nth 0 x))))
922             entries)))))))
923
924 (defun tramp-smb-handle-file-writable-p (filename)
925   "Like `file-writable-p' for Tramp files."
926   (if (file-exists-p filename)
927       (string-match "w" (or (nth 8 (file-attributes filename)) ""))
928     (let ((dir (file-name-directory filename)))
929       (and (file-exists-p dir)
930            (file-writable-p dir)))))
931
932 (defun tramp-smb-handle-insert-directory
933   (filename switches &optional wildcard full-directory-p)
934   "Like `insert-directory' for Tramp files."
935   (setq filename (expand-file-name filename))
936   (unless switches (setq switches ""))
937   ;; Mark trailing "/".
938   (when (and (zerop (length (file-name-nondirectory filename)))
939              (not full-directory-p))
940     (setq switches (concat switches "F")))
941   (if full-directory-p
942       ;; Called from `dired-add-entry'.
943       (setq filename (file-name-as-directory filename))
944     (setq filename (directory-file-name filename)))
945   (with-parsed-tramp-file-name filename nil
946     (with-tramp-progress-reporter v 0 (format "Opening directory %s" filename)
947       (save-match-data
948         (let ((base (file-name-nondirectory filename))
949               ;; We should not destroy the cache entry.
950               (entries (copy-sequence
951                         (tramp-smb-get-file-entries
952                          (file-name-directory filename)))))
953
954           (when wildcard
955             (string-match "\\." base)
956             (setq base (replace-match "\\\\." nil nil base))
957             (string-match "\\*" base)
958             (setq base (replace-match ".*" nil nil base))
959             (string-match "\\?" base)
960             (setq base (replace-match ".?" nil nil base)))
961
962           ;; Filter entries.
963           (setq entries
964                 (delq
965                  nil
966                  (if (or wildcard (zerop (length base)))
967                      ;; Check for matching entries.
968                      (mapcar
969                       (lambda (x)
970                         (when (string-match
971                                (format "^%s" base) (nth 0 x))
972                           x))
973                       entries)
974                    ;; We just need the only and only entry FILENAME.
975                    (list (assoc base entries)))))
976
977           ;; Sort entries.
978           (setq entries
979                 (sort
980                  entries
981                  (lambda (x y)
982                    (if (string-match "t" switches)
983                        ;; Sort by date.
984                        (time-less-p (nth 3 y) (nth 3 x))
985                      ;; Sort by name.
986                      (string-lessp (nth 0 x) (nth 0 y))))))
987
988           ;; Handle "-F" switch.
989           (when (string-match "F" switches)
990             (mapc
991              (lambda (x)
992                (when (not (zerop (length (car x))))
993                  (cond
994                   ((char-equal ?d (string-to-char (nth 1 x)))
995                    (setcar x (concat (car x) "/")))
996                   ((char-equal ?x (string-to-char (nth 1 x)))
997                    (setcar x (concat (car x) "*"))))))
998              entries))
999
1000           ;; Print entries.
1001           (mapc
1002            (lambda (x)
1003              (when (not (zerop (length (nth 0 x))))
1004                (when (string-match "l" switches)
1005                  (let ((attr
1006                         (when (tramp-smb-get-stat-capability v)
1007                           (ignore-errors
1008                             (file-attributes filename 'string)))))
1009                    (insert
1010                     (format
1011                      "%10s %3d %-8s %-8s %8s %s "
1012                      (or (nth 8 attr) (nth 1 x)) ; mode
1013                      (or (nth 1 attr) 1) ; inode
1014                      (or (nth 2 attr) "nobody") ; uid
1015                      (or (nth 3 attr) "nogroup") ; gid
1016                      (or (nth 7 attr) (nth 2 x)) ; size
1017                      (format-time-string
1018                       (if (time-less-p (time-subtract (current-time) (nth 3 x))
1019                            tramp-half-a-year)
1020                           "%b %e %R"
1021                         "%b %e  %Y")
1022                       (nth 3 x)))))) ; date
1023
1024                ;; We mark the file name.  The inserted name could be
1025                ;; from somewhere else, so we use the relative file name
1026                ;; of `default-directory'.
1027                (let ((start (point)))
1028                  (insert
1029                   (format
1030                    "%s\n"
1031                    (file-relative-name
1032                     (expand-file-name
1033                      (nth 0 x) (file-name-directory filename))
1034                     (when full-directory-p (file-name-directory filename)))))
1035                  (put-text-property start (1- (point)) 'dired-filename t))
1036                (forward-line)
1037                (beginning-of-line)))
1038            entries))))))
1039
1040 (defun tramp-smb-handle-make-directory (dir &optional parents)
1041   "Like `make-directory' for Tramp files."
1042   (setq dir (directory-file-name (expand-file-name dir)))
1043   (unless (file-name-absolute-p dir)
1044     (setq dir (expand-file-name dir default-directory)))
1045   (with-parsed-tramp-file-name dir nil
1046     (save-match-data
1047       (let* ((ldir (file-name-directory dir)))
1048         ;; Make missing directory parts.
1049         (when (and parents
1050                    (tramp-smb-get-share v)
1051                    (not (file-directory-p ldir)))
1052           (make-directory ldir parents))
1053         ;; Just do it.
1054         (when (file-directory-p ldir)
1055           (make-directory-internal dir))
1056         (unless (file-directory-p dir)
1057           (tramp-error v 'file-error "Couldn't make directory %s" dir))))))
1058
1059 (defun tramp-smb-handle-make-directory-internal (directory)
1060   "Like `make-directory-internal' for Tramp files."
1061   (setq directory (directory-file-name (expand-file-name directory)))
1062   (unless (file-name-absolute-p directory)
1063     (setq directory (expand-file-name directory default-directory)))
1064   (with-parsed-tramp-file-name directory nil
1065     (save-match-data
1066       (let* ((file (tramp-smb-get-localname v)))
1067         (when (file-directory-p (file-name-directory directory))
1068           (tramp-smb-send-command
1069            v
1070            (if (tramp-smb-get-cifs-capabilities v)
1071                (format
1072                 "posix_mkdir \"%s\" %s"
1073                 file (tramp-compat-decimal-to-octal (default-file-modes)))
1074              (format "mkdir \"%s\"" file)))
1075           ;; We must also flush the cache of the directory, because
1076           ;; `file-attributes' reads the values from there.
1077           (tramp-flush-file-property v (file-name-directory localname))
1078           (tramp-flush-file-property v localname))
1079         (unless (file-directory-p directory)
1080           (tramp-error
1081            v 'file-error "Couldn't make directory %s" directory))))))
1082
1083 (defun tramp-smb-handle-make-symbolic-link
1084   (filename linkname &optional ok-if-already-exists)
1085   "Like `make-symbolic-link' for Tramp files.
1086 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
1087 the symlink.  If LINKNAME is a Tramp file, only the localname component is
1088 used as the target of the symlink.
1089
1090 If LINKNAME is a Tramp file and the localname component is relative, then
1091 it is expanded first, before the localname component is taken.  Note that
1092 this can give surprising results if the user/host for the source and
1093 target of the symlink differ."
1094   (unless (tramp-equal-remote filename linkname)
1095     (with-parsed-tramp-file-name
1096         (if (tramp-tramp-file-p filename) filename linkname) nil
1097       (tramp-error
1098        v 'file-error
1099        "make-symbolic-link: %s"
1100        "only implemented for same method, same user, same host")))
1101   (with-parsed-tramp-file-name filename v1
1102     (with-parsed-tramp-file-name linkname v2
1103       (when (file-directory-p filename)
1104         (tramp-error
1105          v2 'file-error
1106          "make-symbolic-link: %s must not be a directory" filename))
1107       (when (and (not ok-if-already-exists)
1108                  (file-exists-p linkname)
1109                  (not (numberp ok-if-already-exists))
1110                  (y-or-n-p
1111                   (format
1112                    "File %s already exists; make it a new name anyway? "
1113                    linkname)))
1114         (tramp-error
1115          v2 'file-error
1116          "make-symbolic-link: file %s already exists" linkname))
1117       (unless (tramp-smb-get-cifs-capabilities v1)
1118         (tramp-error v2 'file-error "make-symbolic-link not supported"))
1119       ;; We must also flush the cache of the directory, because
1120       ;; `file-attributes' reads the values from there.
1121       (tramp-flush-file-property v2 (file-name-directory v2-localname))
1122       (tramp-flush-file-property v2 v2-localname)
1123       (unless
1124           (tramp-smb-send-command
1125            v1
1126            (format
1127             "symlink \"%s\" \"%s\""
1128             (tramp-smb-get-localname v1)
1129             (tramp-smb-get-localname v2)))
1130         (tramp-error
1131          v2 'file-error
1132          "error with make-symbolic-link, see buffer `%s' for details"
1133          (buffer-name))))))
1134
1135 (defun tramp-smb-handle-process-file
1136   (program &optional infile destination display &rest args)
1137   "Like `process-file' for Tramp files."
1138   ;; The implementation is not complete yet.
1139   (when (and (numberp destination) (zerop destination))
1140     (error "Implementation does not handle immediate return"))
1141
1142   (with-parsed-tramp-file-name default-directory nil
1143     (let* ((name (file-name-nondirectory program))
1144            (name1 name)
1145            (i 0)
1146            input tmpinput outbuf command ret)
1147
1148       ;; Determine input.
1149       (when infile
1150         (setq infile (expand-file-name infile))
1151         (if (tramp-equal-remote default-directory infile)
1152             ;; INFILE is on the same remote host.
1153             (setq input (with-parsed-tramp-file-name infile nil localname))
1154           ;; INFILE must be copied to remote host.
1155           (setq input (tramp-make-tramp-temp-file v)
1156                 tmpinput (tramp-make-tramp-file-name method user host input))
1157           (copy-file infile tmpinput t))
1158         ;; Transform input into a filename powershell does understand.
1159         (setq input (format "//%s%s" host input)))
1160
1161       ;; Determine output.
1162       (cond
1163        ;; Just a buffer.
1164        ((bufferp destination)
1165         (setq outbuf destination))
1166        ;; A buffer name.
1167        ((stringp destination)
1168         (setq outbuf (get-buffer-create destination)))
1169        ;; (REAL-DESTINATION ERROR-DESTINATION)
1170        ((consp destination)
1171         ;; output.
1172         (cond
1173          ((bufferp (car destination))
1174           (setq outbuf (car destination)))
1175          ((stringp (car destination))
1176           (setq outbuf (get-buffer-create (car destination))))
1177          ((car destination)
1178           (setq outbuf (current-buffer))))
1179         ;; stderr.
1180         (tramp-message v 2 "%s" "STDERR not supported"))
1181        ;; 't
1182        (destination
1183         (setq outbuf (current-buffer))))
1184
1185       ;; Construct command.
1186       (setq command (mapconcat 'identity (cons program args) " ")
1187             command (if input
1188                         (format
1189                          "get-content %s | & %s"
1190                          (tramp-smb-shell-quote-argument input) command)
1191                       (format "& %s" command)))
1192
1193       (while (get-process name1)
1194         ;; NAME must be unique as process name.
1195         (setq i (1+ i)
1196               name1 (format "%s<%d>" name i)))
1197
1198       ;; Set the new process properties.
1199       (tramp-set-connection-property v "process-name" name1)
1200       (tramp-set-connection-property
1201        v "process-buffer"
1202        (or outbuf (generate-new-buffer tramp-temp-buffer-name)))
1203
1204       ;; Call it.
1205       (condition-case nil
1206           (with-current-buffer (tramp-get-connection-buffer v)
1207             ;; Preserve buffer contents.
1208             (narrow-to-region (point-max) (point-max))
1209             (tramp-smb-call-winexe v)
1210             (when (tramp-smb-get-share v)
1211               (tramp-smb-send-command
1212                v (format "cd \"//%s%s\"" host (file-name-directory localname))))
1213             (tramp-smb-send-command v command)
1214             ;; Preserve command output.
1215             (narrow-to-region (point-max) (point-max))
1216             (let ((p (tramp-get-connection-process v)))
1217               (tramp-smb-send-command v "exit $lasterrorcode")
1218               (while (memq (process-status p) '(run open))
1219                 (sleep-for 0.1)
1220                 (setq ret (process-exit-status p))))
1221             (delete-region (point-min) (point-max))
1222             (widen))
1223
1224         ;; When the user did interrupt, we should do it also.  We use
1225         ;; return code -1 as marker.
1226         (quit
1227          (setq ret -1))
1228         ;; Handle errors.
1229         (error
1230          (setq ret 1)))
1231
1232       ;; We should redisplay the output.
1233       (when (and display outbuf (get-buffer-window outbuf t)) (redisplay))
1234
1235       ;; Cleanup.  We remove all file cache values for the connection,
1236       ;; because the remote process could have changed them.
1237       (tramp-set-connection-property v "process-name" nil)
1238       (tramp-set-connection-property v "process-buffer" nil)
1239       (when tmpinput (delete-file tmpinput))
1240       (unless outbuf
1241         (kill-buffer (tramp-get-connection-property v "process-buffer" nil)))
1242
1243       ;; `process-file-side-effects' has been introduced with GNU
1244       ;; Emacs 23.2.  If set to nil, no remote file will be changed
1245       ;; by `program'.  If it doesn't exist, we assume its default
1246       ;; value t.
1247       (unless (and (boundp 'process-file-side-effects)
1248                    (not (symbol-value 'process-file-side-effects)))
1249         (tramp-flush-directory-property v ""))
1250
1251       ;; Return exit status.
1252       (if (equal ret -1)
1253           (keyboard-quit)
1254         ret))))
1255
1256 (defun tramp-smb-handle-rename-file
1257   (filename newname &optional ok-if-already-exists)
1258   "Like `rename-file' for Tramp files."
1259   (setq filename (expand-file-name filename)
1260         newname (expand-file-name newname))
1261
1262   (when (and (not ok-if-already-exists)
1263              (file-exists-p newname))
1264     (tramp-error
1265      (tramp-dissect-file-name
1266       (if (tramp-tramp-file-p filename) filename newname))
1267      'file-already-exists newname))
1268
1269   (with-tramp-progress-reporter
1270       (tramp-dissect-file-name
1271        (if (tramp-tramp-file-p filename) filename newname))
1272       0 (format "Renaming %s to %s" filename newname)
1273
1274     (if (and (not (file-exists-p newname))
1275              (tramp-equal-remote filename newname)
1276              (string-equal
1277               (tramp-smb-get-share (tramp-dissect-file-name filename))
1278               (tramp-smb-get-share (tramp-dissect-file-name newname))))
1279         ;; We can rename directly.
1280         (with-parsed-tramp-file-name filename v1
1281           (with-parsed-tramp-file-name newname v2
1282
1283             ;; We must also flush the cache of the directory, because
1284             ;; `file-attributes' reads the values from there.
1285             (tramp-flush-file-property v1 (file-name-directory v1-localname))
1286             (tramp-flush-file-property v1 v1-localname)
1287             (tramp-flush-file-property v2 (file-name-directory v2-localname))
1288             (tramp-flush-file-property v2 v2-localname)
1289             (unless (tramp-smb-get-share v2)
1290               (tramp-error
1291                v2 'file-error "Target `%s' must contain a share name" newname))
1292             (unless (tramp-smb-send-command
1293                      v2 (format "rename \"%s\" \"%s\""
1294                                 (tramp-smb-get-localname v1)
1295                                 (tramp-smb-get-localname v2)))
1296               (tramp-error v2 'file-error "Cannot rename `%s'" filename))))
1297
1298       ;; We must rename via copy.
1299       (tramp-compat-copy-file filename newname ok-if-already-exists t t t)
1300       (if (file-directory-p filename)
1301           (tramp-compat-delete-directory filename 'recursive)
1302         (delete-file filename)))))
1303
1304 (defun tramp-smb-action-set-acl (proc vec)
1305   "Read ACL data from connection buffer."
1306   (when (not (memq (process-status proc) '(run open)))
1307     ;; Accept pending output.
1308     (while (tramp-accept-process-output proc 0.1))
1309     (with-current-buffer (tramp-get-connection-buffer vec)
1310       (tramp-message vec 10 "\n%s" (buffer-string))
1311       (throw 'tramp-action 'ok))))
1312
1313 (defun tramp-smb-handle-set-file-acl (filename acl-string)
1314   "Like `set-file-acl' for Tramp files."
1315   (ignore-errors
1316     (with-parsed-tramp-file-name filename nil
1317       (when (and (stringp acl-string) (executable-find tramp-smb-acl-program))
1318         (setq tramp-current-method (tramp-file-name-method v)
1319               tramp-current-user (tramp-file-name-user v)
1320               tramp-current-host (tramp-file-name-real-host v))
1321         (tramp-set-file-property v localname "file-acl" 'undef)
1322
1323         (let* ((real-user (tramp-file-name-real-user v))
1324                (real-host (tramp-file-name-real-host v))
1325                (domain    (tramp-file-name-domain v))
1326                (port      (tramp-file-name-port v))
1327                (share     (tramp-smb-get-share v))
1328                (localname (tramp-compat-replace-regexp-in-string
1329                            "\\\\" "/" (tramp-smb-get-localname v)))
1330                (args      (list (concat "//" real-host "/" share) "-E" "-S"
1331                                 (tramp-compat-replace-regexp-in-string
1332                                  "\n" "," acl-string))))
1333
1334           (if (not (zerop (length real-user)))
1335               (setq args (append args (list "-U" real-user)))
1336             (setq args (append args (list "-N"))))
1337
1338           (when domain (setq args (append args (list "-W" domain))))
1339           (when port   (setq args (append args (list "-p" port))))
1340           (when tramp-smb-conf
1341             (setq args (append args (list "-s" tramp-smb-conf))))
1342           (setq
1343            args
1344            (append args (list (shell-quote-argument localname)
1345                               "&&" "echo" "tramp_exit_status" "0"
1346                               "||" "echo" "tramp_exit_status" "1")))
1347
1348           (unwind-protect
1349               (with-temp-buffer
1350                 ;; Set the transfer process properties.
1351                 (tramp-set-connection-property
1352                  v "process-name" (buffer-name (current-buffer)))
1353                 (tramp-set-connection-property
1354                  v "process-buffer" (current-buffer))
1355
1356                 ;; Use an asynchronous processes.  By this, password can
1357                 ;; be handled.
1358                 (let ((p (apply
1359                           'start-process
1360                           (tramp-get-connection-name v)
1361                           (tramp-get-connection-buffer v)
1362                           tramp-smb-acl-program args)))
1363
1364                   (tramp-message
1365                    v 6 "%s" (mapconcat 'identity (process-command p) " "))
1366                   (tramp-set-connection-property p "vector" v)
1367                   (tramp-compat-set-process-query-on-exit-flag p nil)
1368                   (tramp-process-actions p v nil tramp-smb-actions-set-acl)
1369                   (goto-char (point-max))
1370                   (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
1371                     (tramp-error
1372                      v 'file-error
1373                      "Couldn't find exit status of `%s'" tramp-smb-acl-program))
1374                   (skip-chars-forward "^ ")
1375                   (when (zerop (read (current-buffer)))
1376                     ;; Success.
1377                     (tramp-set-file-property v localname "file-acl" acl-string)
1378                     t)))
1379
1380             ;; Reset the transfer process properties.
1381             (tramp-set-connection-property v "process-name" nil)
1382             (tramp-set-connection-property v "process-buffer" nil)))))))
1383
1384 (defun tramp-smb-handle-set-file-modes (filename mode)
1385   "Like `set-file-modes' for Tramp files."
1386   (with-parsed-tramp-file-name filename nil
1387     (when (tramp-smb-get-cifs-capabilities v)
1388       (tramp-flush-file-property v localname)
1389       (unless (tramp-smb-send-command
1390                v (format "chmod \"%s\" %s"
1391                          (tramp-smb-get-localname v)
1392                          (tramp-compat-decimal-to-octal mode)))
1393         (tramp-error
1394          v 'file-error "Error while changing file's mode %s" filename)))))
1395
1396 ;; We use BUFFER also as connection buffer during setup. Because of
1397 ;; this, its original contents must be saved, and restored once
1398 ;; connection has been setup.
1399 (defun tramp-smb-handle-start-file-process (name buffer program &rest args)
1400   "Like `start-file-process' for Tramp files."
1401   (with-parsed-tramp-file-name default-directory nil
1402     (let ((command (mapconcat 'identity (cons program args) " "))
1403           (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
1404           (name1 name)
1405           (i 0))
1406       (unwind-protect
1407           (save-excursion
1408             (save-restriction
1409               (unless buffer
1410                 ;; BUFFER can be nil.  We use a temporary buffer.
1411                 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
1412               (while (get-process name1)
1413                 ;; NAME must be unique as process name.
1414                 (setq i (1+ i)
1415                       name1 (format "%s<%d>" name i)))
1416               ;; Set the new process properties.
1417               (tramp-set-connection-property v "process-name" name1)
1418               (tramp-set-connection-property v "process-buffer" buffer)
1419               ;; Activate narrowing in order to save BUFFER contents.
1420               (with-current-buffer (tramp-get-connection-buffer v)
1421                 (let ((buffer-undo-list t))
1422                   (narrow-to-region (point-max) (point-max))
1423                   (tramp-smb-call-winexe v)
1424                   (when (tramp-smb-get-share v)
1425                     (tramp-smb-send-command
1426                      v (format
1427                         "cd \"//%s%s\""
1428                         host (file-name-directory localname))))
1429                   (tramp-message v 6 "(%s); exit" command)
1430                   (tramp-send-string v command)))
1431               ;; Return value.
1432               (tramp-get-connection-process v)))
1433
1434         ;; Save exit.
1435         (with-current-buffer (tramp-get-connection-buffer v)
1436           (if (string-match tramp-temp-buffer-name (buffer-name))
1437               (progn
1438                 (set-process-buffer (tramp-get-connection-process v) nil)
1439                 (kill-buffer (current-buffer)))
1440             (set-buffer-modified-p bmp)))
1441         (tramp-set-connection-property v "process-name" nil)
1442         (tramp-set-connection-property v "process-buffer" nil)))))
1443
1444 (defun tramp-smb-handle-substitute-in-file-name (filename)
1445   "Like `handle-substitute-in-file-name' for Tramp files.
1446 \"//\" substitutes only in the local filename part.  Catches
1447 errors for shares like \"C$/\", which are common in Microsoft Windows."
1448   (with-parsed-tramp-file-name filename nil
1449     ;; Ignore in LOCALNAME everything before "//".
1450     (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
1451       (setq filename
1452             (concat (file-remote-p filename)
1453                     (replace-match "\\1" nil nil localname)))))
1454   (condition-case nil
1455       (tramp-run-real-handler 'substitute-in-file-name (list filename))
1456     (error filename)))
1457
1458 (defun tramp-smb-handle-write-region
1459   (start end filename &optional append visit lockname confirm)
1460   "Like `write-region' for Tramp files."
1461   (setq filename (expand-file-name filename))
1462   (with-parsed-tramp-file-name filename nil
1463     ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
1464     (when (and (not (featurep 'xemacs))
1465                confirm (file-exists-p filename))
1466       (unless (y-or-n-p (format "File %s exists; overwrite anyway? "
1467                                 filename))
1468         (tramp-error v 'file-error "File not overwritten")))
1469     ;; We must also flush the cache of the directory, because
1470     ;; `file-attributes' reads the values from there.
1471     (tramp-flush-file-property v (file-name-directory localname))
1472     (tramp-flush-file-property v localname)
1473     (let ((curbuf (current-buffer))
1474           (tmpfile (tramp-compat-make-temp-file filename)))
1475       (when (and append (file-exists-p filename))
1476         (copy-file filename tmpfile 'ok))
1477       ;; We say `no-message' here because we don't want the visited file
1478       ;; modtime data to be clobbered from the temp file.  We call
1479       ;; `set-visited-file-modtime' ourselves later on.
1480       (tramp-run-real-handler
1481        'write-region
1482        (if confirm ; don't pass this arg unless defined for backward compat.
1483            (list start end tmpfile append 'no-message lockname confirm)
1484          (list start end tmpfile append 'no-message lockname)))
1485
1486       (with-tramp-progress-reporter
1487           v 3 (format "Moving tmp file %s to %s" tmpfile filename)
1488         (unwind-protect
1489             (unless (tramp-smb-send-command
1490                      v (format "put %s \"%s\""
1491                                tmpfile (tramp-smb-get-localname v)))
1492               (tramp-error v 'file-error "Cannot write `%s'" filename))
1493           (delete-file tmpfile)))
1494
1495       (unless (equal curbuf (current-buffer))
1496         (tramp-error
1497          v 'file-error
1498          "Buffer has changed from `%s' to `%s'" curbuf (current-buffer)))
1499       (when (eq visit t)
1500         (set-visited-file-modtime)))))
1501
1502
1503 ;; Internal file name functions.
1504
1505 (defun tramp-smb-get-share (vec)
1506   "Returns the share name of LOCALNAME."
1507   (save-match-data
1508     (let ((localname (tramp-file-name-localname vec)))
1509       (when (string-match "^/?\\([^/]+\\)/" localname)
1510         (match-string 1 localname)))))
1511
1512 (defun tramp-smb-get-localname (vec)
1513   "Returns the file name of LOCALNAME.
1514 If VEC has no cifs capabilities, exchange \"/\" by \"\\\\\"."
1515   (save-match-data
1516     (let ((localname (tramp-file-name-localname vec)))
1517       (setq
1518        localname
1519        (if (string-match "^/?[^/]+\\(/.*\\)" localname)
1520            ;; There is a share, separated by "/".
1521            (if (not (tramp-smb-get-cifs-capabilities vec))
1522                (mapconcat
1523                 (lambda (x) (if (equal x ?/) "\\" (char-to-string x)))
1524                 (match-string 1 localname) "")
1525              (match-string 1 localname))
1526          ;; There is just a share.
1527          (if (string-match "^/?\\([^/]+\\)$" localname)
1528              (match-string 1 localname)
1529            "")))
1530
1531       ;; Sometimes we have discarded `substitute-in-file-name'.
1532       (when (string-match "\\(\\$\\$\\)\\(/\\|$\\)" localname)
1533         (setq localname (replace-match "$" nil nil localname 1)))
1534
1535       localname)))
1536
1537 ;; Share names of a host are cached. It is very unlikely that the
1538 ;; shares do change during connection.
1539 (defun tramp-smb-get-file-entries (directory)
1540   "Read entries which match DIRECTORY.
1541 Either the shares are listed, or the `dir' command is executed.
1542 Result is a list of (LOCALNAME MODE SIZE MONTH DAY TIME YEAR)."
1543   (with-parsed-tramp-file-name (file-name-as-directory directory) nil
1544     (setq localname (or localname "/"))
1545     (with-tramp-file-property v localname "file-entries"
1546       (with-current-buffer (tramp-get-connection-buffer v)
1547         (let* ((share (tramp-smb-get-share v))
1548                (cache (tramp-get-connection-property v "share-cache" nil))
1549                res entry)
1550
1551           (if (and (not share) cache)
1552               ;; Return cached shares.
1553               (setq res cache)
1554
1555             ;; Read entries.
1556             (if share
1557                 (tramp-smb-send-command
1558                  v (format "dir \"%s*\"" (tramp-smb-get-localname v)))
1559               ;; `tramp-smb-maybe-open-connection' lists also the share names.
1560               (tramp-smb-maybe-open-connection v))
1561
1562             ;; Loop the listing.
1563             (goto-char (point-min))
1564             (if (re-search-forward tramp-smb-errors nil t)
1565                 (tramp-error v 'file-error "%s `%s'" (match-string 0) directory)
1566               (while (not (eobp))
1567                 (setq entry (tramp-smb-read-file-entry share))
1568                 (forward-line)
1569                 (when entry (push entry res))))
1570
1571             ;; Cache share entries.
1572             (unless share
1573               (tramp-set-connection-property v "share-cache" res)))
1574
1575           ;; Add directory itself.
1576           (push '("" "drwxrwxrwx" 0 (0 0)) res)
1577
1578           ;; There's a very strange error (debugged with XEmacs 21.4.14)
1579           ;; If there's no short delay, it returns nil.  No idea about.
1580           (when (featurep 'xemacs) (sleep-for 0.01))
1581
1582           ;; Return entries.
1583           (delq nil res))))))
1584
1585 ;; Return either a share name (if SHARE is nil), or a file name.
1586 ;;
1587 ;; If shares are listed, the following format is expected:
1588 ;;
1589 ;; Disk|                                  - leading spaces
1590 ;; [^|]+|                                 - share name, 14 char
1591 ;; .*                                     - comment
1592 ;;
1593 ;; Entries provided by smbclient DIR aren't fully regular.
1594 ;; They should have the format
1595 ;;
1596 ;; \s-\{2,2}                              - leading spaces
1597 ;; \S-\(.*\S-\)\s-*                       - file name, 30 chars, left bound
1598 ;; \s-+[ADHRSV]*                          - permissions, 7 chars, right bound
1599 ;; \s-                                    - space delimiter
1600 ;; \s-+[0-9]+                             - size, 8 chars, right bound
1601 ;; \s-\{2,2\}                             - space delimiter
1602 ;; \w\{3,3\}                              - weekday
1603 ;; \s-                                    - space delimiter
1604 ;; \w\{3,3\}                              - month
1605 ;; \s-                                    - space delimiter
1606 ;; [ 12][0-9]                             - day
1607 ;; \s-                                    - space delimiter
1608 ;; [0-9]\{2,2\}:[0-9]\{2,2\}:[0-9]\{2,2\} - time
1609 ;; \s-                                    - space delimiter
1610 ;; [0-9]\{4,4\}                           - year
1611 ;;
1612 ;; samba/src/client.c (http://samba.org/doxygen/samba/client_8c-source.html)
1613 ;; has function display_finfo:
1614 ;;
1615 ;;   d_printf("  %-30s%7.7s %8.0f  %s",
1616 ;;            finfo->name,
1617 ;;            attrib_string(finfo->mode),
1618 ;;            (double)finfo->size,
1619 ;;            asctime(LocalTime(&t)));
1620 ;;
1621 ;; in Samba 1.9, there's the following code:
1622 ;;
1623 ;;   DEBUG(0,("  %-30s%7.7s%10d  %s",
1624 ;;         CNV_LANG(finfo->name),
1625 ;;         attrib_string(finfo->mode),
1626 ;;         finfo->size,
1627 ;;         asctime(LocalTime(&t))));
1628 ;;
1629 ;; Problems:
1630 ;; * Modern regexp constructs, like spy groups and counted repetitions, aren't
1631 ;;   available in older Emacsen.
1632 ;; * The length of constructs (file name, size) might exceed the default.
1633 ;; * File names might contain spaces.
1634 ;; * Permissions might be empty.
1635 ;;
1636 ;; So we try to analyze backwards.
1637 (defun tramp-smb-read-file-entry (share)
1638   "Parse entry in SMB output buffer.
1639 If SHARE is result, entries are of type dir. Otherwise, shares are listed.
1640 Result is the list (LOCALNAME MODE SIZE MTIME)."
1641 ;; We are called from `tramp-smb-get-file-entries', which sets the
1642 ;; current buffer.
1643   (let ((line (buffer-substring (point) (point-at-eol)))
1644         localname mode size month day hour min sec year mtime)
1645
1646     (if (not share)
1647
1648         ;; Read share entries.
1649         (when (string-match "^Disk|\\([^|]+\\)|" line)
1650           (setq localname (match-string 1 line)
1651                 mode "dr-xr-xr-x"
1652                 size 0))
1653
1654       ;; Real listing.
1655       (block nil
1656
1657         ;; year.
1658         (if (string-match "\\([0-9]+\\)$" line)
1659             (setq year (string-to-number (match-string 1 line))
1660                   line (substring line 0 -5))
1661           (return))
1662
1663         ;; time.
1664         (if (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)$" line)
1665             (setq hour (string-to-number (match-string 1 line))
1666                   min  (string-to-number (match-string 2 line))
1667                   sec  (string-to-number (match-string 3 line))
1668                   line (substring line 0 -9))
1669           (return))
1670
1671         ;; day.
1672         (if (string-match "\\([0-9]+\\)$" line)
1673             (setq day  (string-to-number (match-string 1 line))
1674                   line (substring line 0 -3))
1675           (return))
1676
1677         ;; month.
1678         (if (string-match "\\(\\w+\\)$" line)
1679             (setq month (match-string 1 line)
1680                   line  (substring line 0 -4))
1681           (return))
1682
1683         ;; weekday.
1684         (if (string-match "\\(\\w+\\)$" line)
1685             (setq line (substring line 0 -5))
1686           (return))
1687
1688         ;; size.
1689         (if (string-match "\\([0-9]+\\)$" line)
1690             (let ((length (- (max 10 (1+ (length (match-string 1 line)))))))
1691               (setq size (string-to-number (match-string 1 line)))
1692               (when (string-match "\\([ADHRSV]+\\)" (substring line length))
1693                 (setq length (+ length (match-end 0))))
1694               (setq line (substring line 0 length)))
1695           (return))
1696
1697         ;; mode: ARCH, DIR, HIDDEN, RONLY, SYSTEM, VOLID.
1698         (if (string-match "\\([ADHRSV]+\\)?$" line)
1699             (setq
1700              mode (or (match-string 1 line) "")
1701              mode (save-match-data (format
1702                     "%s%s"
1703                     (if (string-match "D" mode) "d" "-")
1704                     (mapconcat
1705                      (lambda (_x) "") "    "
1706                      (concat "r" (if (string-match "R" mode) "-" "w") "x"))))
1707              line (substring line 0 -6))
1708           (return))
1709
1710         ;; localname.
1711         (if (string-match "^\\s-+\\(\\S-\\(.*\\S-\\)?\\)\\s-*$" line)
1712             (setq localname (match-string 1 line))
1713           (return))))
1714
1715     (when (and localname mode size)
1716       (setq mtime
1717             (if (and sec min hour day month year)
1718                 (encode-time
1719                  sec min hour day
1720                  (cdr (assoc (downcase month) tramp-parse-time-months))
1721                  year)
1722               '(0 0)))
1723       (list localname mode size mtime))))
1724
1725 (defun tramp-smb-get-cifs-capabilities (vec)
1726   "Check, whether the SMB server supports POSIX commands."
1727   ;; When we are not logged in yet, we return nil.
1728   (if (let ((p (tramp-get-connection-process vec)))
1729         (and p (processp p) (memq (process-status p) '(run open))))
1730       (with-tramp-connection-property
1731           (tramp-get-connection-process vec) "cifs-capabilities"
1732         (save-match-data
1733           (when (tramp-smb-send-command vec "posix")
1734             (with-current-buffer (tramp-get-connection-buffer vec)
1735               (goto-char (point-min))
1736               (when
1737                   (re-search-forward "Server supports CIFS capabilities" nil t)
1738                 (member
1739                  "pathnames"
1740                  (split-string
1741                   (buffer-substring (point) (point-at-eol)) nil t)))))))))
1742
1743 (defun tramp-smb-get-stat-capability (vec)
1744   "Check, whether the SMB server supports the STAT command."
1745   ;; When we are not logged in yet, we return nil.
1746   (if (and (tramp-smb-get-share vec)
1747            (let ((p (tramp-get-connection-process vec)))
1748              (and p (processp p) (memq (process-status p) '(run open)))))
1749       (with-tramp-connection-property
1750           (tramp-get-connection-process vec) "stat-capability"
1751         (tramp-smb-send-command vec "stat \"/\""))))
1752
1753
1754 ;; Connection functions.
1755
1756 (defun tramp-smb-send-command (vec command)
1757   "Send the COMMAND to connection VEC.
1758 Returns nil if there has been an error message from smbclient."
1759   (tramp-smb-maybe-open-connection vec)
1760   (tramp-message vec 6 "%s" command)
1761   (tramp-send-string vec command)
1762   (tramp-smb-wait-for-output vec))
1763
1764 (defun tramp-smb-maybe-open-connection (vec &optional argument)
1765   "Maybe open a connection to HOST, log in as USER, using `tramp-smb-program'.
1766 Does not do anything if a connection is already open, but re-opens the
1767 connection if a previous connection has died for some reason.
1768 If ARGUMENT is non-nil, use it as argument for
1769 `tramp-smb-winexe-program', and suppress any checks."
1770   (tramp-check-proper-method-and-host vec)
1771
1772   (let* ((share (tramp-smb-get-share vec))
1773          (buf (tramp-get-connection-buffer vec))
1774          (p (get-buffer-process buf)))
1775
1776     ;; Check whether we still have the same smbclient version.
1777     ;; Otherwise, we must delete the connection cache, because
1778     ;; capabilities migh have changed.
1779     (unless (or argument (processp p))
1780       (let ((default-directory (tramp-compat-temporary-file-directory))
1781             (command (concat tramp-smb-program " -V")))
1782
1783         (unless tramp-smb-version
1784           (unless (executable-find tramp-smb-program)
1785             (tramp-error
1786              vec 'file-error
1787              "Cannot find command %s in %s" tramp-smb-program exec-path))
1788           (setq tramp-smb-version (shell-command-to-string command))
1789           (tramp-message vec 6 command)
1790           (tramp-message vec 6 "\n%s" tramp-smb-version)
1791           (if (string-match "[ \t\n\r]+\\'" tramp-smb-version)
1792               (setq tramp-smb-version
1793                     (replace-match "" nil nil tramp-smb-version))))
1794
1795         (unless (string-equal
1796                  tramp-smb-version
1797                  (tramp-get-connection-property
1798                   vec "smbclient-version" tramp-smb-version))
1799           (tramp-flush-directory-property vec "")
1800           (tramp-flush-connection-property vec))
1801
1802         (tramp-set-connection-property
1803          vec "smbclient-version" tramp-smb-version)))
1804
1805     ;; If too much time has passed since last command was sent, look
1806     ;; whether there has been an error message; maybe due to
1807     ;; connection timeout.
1808     (with-current-buffer buf
1809       (goto-char (point-min))
1810       (when (and (> (tramp-time-diff
1811                      (current-time)
1812                      (tramp-get-connection-property
1813                       p "last-cmd-time" '(0 0 0)))
1814                     60)
1815                  p (processp p) (memq (process-status p) '(run open))
1816                  (re-search-forward tramp-smb-errors nil t))
1817         (delete-process p)
1818         (setq p nil)))
1819
1820     ;; Check whether it is still the same share.
1821     (unless
1822         (and p (processp p) (memq (process-status p) '(run open))
1823              (or argument
1824                  (string-equal
1825                   share
1826                   (tramp-get-connection-property p "smb-share" ""))))
1827
1828       (save-match-data
1829         ;; There might be unread output from checking for share names.
1830         (when buf (with-current-buffer buf (erase-buffer)))
1831         (when (and p (processp p)) (delete-process p))
1832
1833         (let* ((user      (tramp-file-name-user vec))
1834                (host      (tramp-file-name-host vec))
1835                (real-user (tramp-file-name-real-user vec))
1836                (real-host (tramp-file-name-real-host vec))
1837                (domain    (tramp-file-name-domain vec))
1838                (port      (tramp-file-name-port vec))
1839                args)
1840
1841           (cond
1842            (argument
1843             (setq args (list (concat "//" real-host))))
1844            (share
1845             (setq args (list (concat "//" real-host "/" share))))
1846            (t
1847             (setq args (list "-g" "-L" real-host ))))
1848
1849           (if (not (zerop (length real-user)))
1850               (setq args (append args (list "-U" real-user)))
1851             (setq args (append args (list "-N"))))
1852
1853           (when domain (setq args (append args (list "-W" domain))))
1854           (when port   (setq args (append args (list "-p" port))))
1855           (when tramp-smb-conf
1856             (setq args (append args (list "-s" tramp-smb-conf))))
1857           (when argument
1858             (setq args (append args (list argument))))
1859
1860           ;; OK, let's go.
1861           (with-tramp-progress-reporter
1862               vec 3
1863               (format "Opening connection for //%s%s/%s"
1864                       (if (not (zerop (length user))) (concat user "@") "")
1865                       host (or share ""))
1866
1867             (let* ((coding-system-for-read nil)
1868                    (process-connection-type tramp-process-connection-type)
1869                    (p (let ((default-directory
1870                               (tramp-compat-temporary-file-directory)))
1871                         (apply #'start-process
1872                                (tramp-get-connection-name vec)
1873                                (tramp-get-connection-buffer vec)
1874                                (if argument
1875                                    tramp-smb-winexe-program tramp-smb-program)
1876                                args))))
1877
1878               (tramp-message
1879                vec 6 "%s" (mapconcat 'identity (process-command p) " "))
1880               (tramp-set-connection-property p "vector" vec)
1881               (tramp-compat-set-process-query-on-exit-flag p nil)
1882
1883               ;; Set variables for computing the prompt for reading password.
1884               (setq tramp-current-method tramp-smb-method
1885                     tramp-current-user user
1886                     tramp-current-host host)
1887
1888               (condition-case err
1889                   (let (tramp-message-show-message)
1890                     ;; Play login scenario.
1891                     (tramp-process-actions
1892                      p vec nil
1893                      (if (or argument share)
1894                          tramp-smb-actions-with-share
1895                        tramp-smb-actions-without-share))
1896
1897                     ;; Check server version.
1898                     (unless argument
1899                       (with-current-buffer (tramp-get-connection-buffer vec)
1900                         (goto-char (point-min))
1901                         (search-forward-regexp tramp-smb-server-version nil t)
1902                         (let ((smbserver-version (match-string 0)))
1903                           (unless
1904                               (string-equal
1905                                smbserver-version
1906                                (tramp-get-connection-property
1907                                 vec "smbserver-version" smbserver-version))
1908                             (tramp-flush-directory-property vec "")
1909                             (tramp-flush-connection-property vec))
1910                           (tramp-set-connection-property
1911                            vec "smbserver-version" smbserver-version))))
1912
1913                     ;; Set chunksize to 1.  smbclient reads its input
1914                     ;; character by character; if we send the string
1915                     ;; at once, it is read painfully slow.
1916                     (tramp-set-connection-property p "smb-share" share)
1917                     (tramp-set-connection-property p "chunksize" 1))
1918
1919                 ;; Check for the error reason.  If it was due to wrong
1920                 ;; password, reestablish the connection.  We cannot
1921                 ;; handle this in `tramp-process-actions', because
1922                 ;; smbclient does not ask for the password, again.
1923                 (error
1924                  (with-current-buffer (tramp-get-connection-buffer vec)
1925                    (goto-char (point-min))
1926                    (if (and (boundp 'auth-sources)
1927                             (symbol-value 'auth-sources)
1928                             (search-forward-regexp
1929                              tramp-smb-wrong-passwd-regexp nil t))
1930                        ;; Disable `auth-source' and `password-cache'.
1931                        (let (auth-sources)
1932                          (tramp-message
1933                           vec 3 "Retry connection with new password")
1934                          (tramp-cleanup-connection vec t)
1935                          (tramp-smb-maybe-open-connection vec argument))
1936                      ;; Propagate the error.
1937                      (signal (car err) (cdr err)))))))))))))
1938
1939 ;; We don't use timeouts.  If needed, the caller shall wrap around.
1940 (defun tramp-smb-wait-for-output (vec)
1941   "Wait for output from smbclient command.
1942 Returns nil if an error message has appeared."
1943   (with-current-buffer (tramp-get-connection-buffer vec)
1944     (let ((p (get-buffer-process (current-buffer)))
1945           (found (progn (goto-char (point-min))
1946                         (re-search-forward tramp-smb-prompt nil t)))
1947           (err   (progn (goto-char (point-min))
1948                         (re-search-forward tramp-smb-errors nil t)))
1949           buffer-read-only)
1950
1951       ;; Algorithm: get waiting output.  See if last line contains
1952       ;; `tramp-smb-prompt' sentinel or `tramp-smb-errors' strings.
1953       ;; If not, wait a bit and again get waiting output.
1954       (while (and (not found) (not err) (memq (process-status p) '(run open)))
1955
1956         ;; Accept pending output.
1957         (tramp-accept-process-output p 0.1)
1958
1959         ;; Search for prompt.
1960         (goto-char (point-min))
1961         (setq found (re-search-forward tramp-smb-prompt nil t))
1962
1963         ;; Search for errors.
1964         (goto-char (point-min))
1965         (setq err (re-search-forward tramp-smb-errors nil t)))
1966
1967       ;; When the process is still alive, read pending output.
1968       (while (and (not found) (memq (process-status p) '(run open)))
1969
1970         ;; Accept pending output.
1971         (tramp-accept-process-output p 0.1)
1972
1973         ;; Search for prompt.
1974         (goto-char (point-min))
1975         (setq found (re-search-forward tramp-smb-prompt nil t)))
1976
1977       (tramp-message vec 6 "\n%s" (buffer-string))
1978
1979       ;; Remove prompt.
1980       (when found
1981         (goto-char (point-max))
1982         (re-search-backward tramp-smb-prompt nil t)
1983         (delete-region (point) (point-max)))
1984
1985       ;; Return value is whether no error message has appeared.
1986       (not err))))
1987
1988 (defun tramp-smb-kill-winexe-function ()
1989   "Send SIGKILL to the winexe process."
1990   (ignore-errors
1991     (let ((p (get-buffer-process (current-buffer))))
1992       (when (and p (processp p) (memq (process-status p) '(run open)))
1993         (signal-process (process-id p) 'SIGINT)))))
1994
1995 (defun tramp-smb-call-winexe (vec)
1996   "Apply a remote command, if possible, using `tramp-smb-winexe-program'."
1997
1998   ;; Check for program.
1999   (unless (executable-find tramp-smb-winexe-program)
2000     (tramp-error
2001      vec 'file-error "Cannot find program: %s" tramp-smb-winexe-program))
2002
2003   ;; winexe does not supports ports.
2004   (when (tramp-file-name-port vec)
2005     (tramp-error vec 'file-error "Port not supported for remote processes"))
2006
2007   (tramp-smb-maybe-open-connection
2008    vec
2009    (format
2010     "%s %s"
2011     tramp-smb-winexe-shell-command tramp-smb-winexe-shell-command-switch))
2012
2013   (set (make-local-variable 'kill-buffer-hook)
2014        '(tramp-smb-kill-winexe-function))
2015
2016   ;; Suppress "^M".  Shouldn't we specify utf8?
2017   (set-process-coding-system (tramp-get-connection-process vec) 'raw-text-dos)
2018
2019   ;; Set width to 128.  This avoids mixing prompt and long error messages.
2020   (tramp-smb-send-command vec "$rawui = (Get-Host).UI.RawUI")
2021   (tramp-smb-send-command vec "$bufsize = $rawui.BufferSize")
2022   (tramp-smb-send-command vec "$winsize = $rawui.WindowSize")
2023   (tramp-smb-send-command vec "$bufsize.Width = 128")
2024   (tramp-smb-send-command vec "$winsize.Width = 128")
2025   (tramp-smb-send-command vec "$rawui.BufferSize = $bufsize")
2026   (tramp-smb-send-command vec "$rawui.WindowSize = $winsize"))
2027
2028 (defun tramp-smb-shell-quote-argument (s)
2029   "Similar to `shell-quote-argument', but uses windows cmd syntax."
2030   (let ((system-type 'ms-dos))
2031     (shell-quote-argument s)))
2032
2033 (add-hook 'tramp-unload-hook
2034           (lambda ()
2035             (unload-feature 'tramp-smb 'force)))
2036
2037 (provide 'tramp-smb)
2038
2039 ;;; TODO:
2040
2041 ;; * Return more comprehensive file permission string.
2042 ;; * Try to remove the inclusion of dummy "" directory.  Seems to be at
2043 ;;   several places, especially in `tramp-smb-handle-insert-directory'.
2044 ;; * Ignore case in file names.
2045
2046 ;;; tramp-smb.el ends here