(find-ls-subdir-switches): New user option.
[emacs.git] / lisp / net / tramp-smb.el
blobcca01d169b62f2b4bfd0667ee1f0c1d8de2b8522
1 ;;; tramp-smb.el --- Tramp access functions for SMB servers -*- coding: iso-8859-1; -*-
3 ;; Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
5 ;; Author: Michael Albinus <Michael.Albinus@alcatel.de>
6 ;; Keywords: comm, processes
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
25 ;;; Commentary:
27 ;; Access functions for SMB servers like SAMBA or M$ Windows from Tramp.
29 ;;; Code:
31 (require 'tramp)
33 ;; Pacify byte-compiler
34 (eval-when-compile
35 (require 'cl)
36 (require 'custom)
37 ;; Emacs 19.34 compatibility hack -- is this needed?
38 (or (>= emacs-major-version 20)
39 (load "cl-seq")))
41 ;; Avoid byte-compiler warnings if the byte-compiler supports this.
42 ;; Currently, XEmacs supports this.
43 (eval-when-compile
44 (when (fboundp 'byte-compiler-options)
45 (let (unused-vars) ; Pacify Emacs byte-compiler
46 (defalias 'warnings 'identity) ; Pacify Emacs byte-compiler
47 (byte-compiler-options (warnings (- unused-vars))))))
49 ;; XEmacs byte-compiler raises warning abouts `last-coding-system-used'.
50 (eval-when-compile
51 (unless (boundp 'last-coding-system-used)
52 (defvar last-coding-system-used nil)))
54 ;; Define SMB method ...
55 (defcustom tramp-smb-method "smb"
56 "*Method to connect SAMBA and M$ SMB servers."
57 :group 'tramp
58 :type 'string)
60 ;; ... and add it to the method list.
61 (add-to-list 'tramp-methods (cons tramp-smb-method nil))
63 ;; Add a default for `tramp-default-method-alist'. Rule: If there is
64 ;; a domain in USER, it must be the SMB method.
65 (add-to-list 'tramp-default-method-alist
66 (list "" "%" tramp-smb-method))
68 ;; Add completion function for SMB method.
69 (tramp-set-completion-function
70 tramp-smb-method
71 '((tramp-parse-netrc "~/.netrc")))
73 (defcustom tramp-smb-program "smbclient"
74 "*Name of SMB client to run."
75 :group 'tramp
76 :type 'string)
78 (defconst tramp-smb-prompt "^smb: \\S-+> \\|^\\s-+Server\\s-+Comment$"
79 "Regexp used as prompt in smbclient.")
81 (defconst tramp-smb-errors
82 (mapconcat
83 'identity
84 '(; Connection error
85 "Connection to \\S-+ failed"
86 ; Samba
87 "ERRDOS"
88 "ERRSRV"
89 "ERRbadfile"
90 "ERRbadpw"
91 "ERRfilexists"
92 "ERRnoaccess"
93 "ERRnomem"
94 "ERRnosuchshare"
95 ; Windows NT 4.0, Windows 5.0 (Windows 2000), Windows 5.1 (Windows XP)
96 "NT_STATUS_ACCESS_DENIED"
97 "NT_STATUS_ACCOUNT_LOCKED_OUT"
98 "NT_STATUS_BAD_NETWORK_NAME"
99 "NT_STATUS_CANNOT_DELETE"
100 "NT_STATUS_LOGON_FAILURE"
101 "NT_STATUS_NETWORK_ACCESS_DENIED"
102 "NT_STATUS_NO_SUCH_FILE"
103 "NT_STATUS_OBJECT_NAME_INVALID"
104 "NT_STATUS_OBJECT_NAME_NOT_FOUND"
105 "NT_STATUS_SHARING_VIOLATION"
106 "NT_STATUS_WRONG_PASSWORD")
107 "\\|")
108 "Regexp for possible error strings of SMB servers.
109 Used instead of analyzing error codes of commands.")
111 (defvar tramp-smb-share nil
112 "Holds the share name for the current buffer.
113 This variable is local to each buffer.")
114 (make-variable-buffer-local 'tramp-smb-share)
116 (defvar tramp-smb-share-cache nil
117 "Caches the share names accessible to host related to the current buffer.
118 This variable is local to each buffer.")
119 (make-variable-buffer-local 'tramp-smb-share-cache)
121 (defvar tramp-smb-inodes nil
122 "Keeps virtual inodes numbers for SMB files.")
124 ;; New handlers should be added here.
125 (defconst tramp-smb-file-name-handler-alist
127 ;; `access-file' performed by default handler
128 (add-name-to-file . tramp-smb-handle-copy-file) ;; we're on Windows, honey.
129 ;; `byte-compiler-base-file-name' performed by default handler
130 (copy-file . tramp-smb-handle-copy-file)
131 (delete-directory . tramp-smb-handle-delete-directory)
132 (delete-file . tramp-smb-handle-delete-file)
133 ;; `diff-latest-backup-file' performed by default handler
134 (directory-file-name . tramp-handle-directory-file-name)
135 (directory-files . tramp-smb-handle-directory-files)
136 (directory-files-and-attributes . tramp-smb-handle-directory-files-and-attributes)
137 (dired-call-process . tramp-smb-not-handled)
138 (dired-compress-file . tramp-smb-not-handled)
139 ;; `dired-uncache' performed by default handler
140 ;; `expand-file-name' not necessary because we cannot expand "~/"
141 (file-accessible-directory-p . tramp-smb-handle-file-directory-p)
142 (file-attributes . tramp-smb-handle-file-attributes)
143 (file-directory-p . tramp-smb-handle-file-directory-p)
144 (file-executable-p . tramp-smb-handle-file-exists-p)
145 (file-exists-p . tramp-smb-handle-file-exists-p)
146 (file-local-copy . tramp-smb-handle-file-local-copy)
147 (file-remote-p . tramp-handle-file-remote-p)
148 (file-modes . tramp-handle-file-modes)
149 (file-name-all-completions . tramp-smb-handle-file-name-all-completions)
150 ;; `file-name-as-directory' performed by default handler
151 (file-name-completion . tramp-handle-file-name-completion)
152 (file-name-directory . tramp-handle-file-name-directory)
153 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
154 ;; `file-name-sans-versions' performed by default handler
155 (file-newer-than-file-p . tramp-smb-handle-file-newer-than-file-p)
156 (file-ownership-preserved-p . tramp-smb-not-handled)
157 (file-readable-p . tramp-smb-handle-file-exists-p)
158 (file-regular-p . tramp-handle-file-regular-p)
159 (file-symlink-p . tramp-smb-not-handled)
160 ;; `file-truename' performed by default handler
161 (file-writable-p . tramp-smb-handle-file-writable-p)
162 (find-backup-file-name . tramp-handle-find-backup-file-name)
163 ;; `find-file-noselect' performed by default handler
164 ;; `get-file-buffer' performed by default handler
165 (insert-directory . tramp-smb-handle-insert-directory)
166 (insert-file-contents . tramp-handle-insert-file-contents)
167 (load . tramp-handle-load)
168 (make-directory . tramp-smb-handle-make-directory)
169 (make-directory-internal . tramp-smb-handle-make-directory-internal)
170 (make-symbolic-link . tramp-smb-not-handled)
171 (rename-file . tramp-smb-handle-rename-file)
172 (set-file-modes . tramp-smb-not-handled)
173 (set-visited-file-modtime . tramp-smb-not-handled)
174 (shell-command . tramp-smb-not-handled)
175 ;; `substitute-in-file-name' performed by default handler
176 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
177 (vc-registered . tramp-smb-not-handled)
178 (verify-visited-file-modtime . tramp-smb-not-handled)
179 (write-region . tramp-smb-handle-write-region)
181 "Alist of handler functions for Tramp SMB method.
182 Operations not mentioned here will be handled by the default Emacs primitives.")
184 (defun tramp-smb-file-name-p (filename)
185 "Check if it's a filename for SMB servers."
186 (let ((v (tramp-dissect-file-name filename)))
187 (string=
188 (tramp-find-method
189 (tramp-file-name-multi-method v)
190 (tramp-file-name-method v)
191 (tramp-file-name-user v)
192 (tramp-file-name-host v))
193 tramp-smb-method)))
195 (defun tramp-smb-file-name-handler (operation &rest args)
196 "Invoke the SMB related OPERATION.
197 First arg specifies the OPERATION, second arg is a list of arguments to
198 pass to the OPERATION."
199 (let ((fn (assoc operation tramp-smb-file-name-handler-alist)))
200 (if fn
201 (if (eq (cdr fn) 'tramp-smb-not-handled)
202 (apply (cdr fn) operation args)
203 (save-match-data (apply (cdr fn) args)))
204 (tramp-run-real-handler operation args))))
206 (add-to-list 'tramp-foreign-file-name-handler-alist
207 (cons 'tramp-smb-file-name-p 'tramp-smb-file-name-handler))
210 ;; File name primitives
212 (defun tramp-smb-not-handled (operation &rest args)
213 "Default handler for all functions which are disrecarded."
214 (tramp-message 10 "Won't be handled: %s %s" operation args)
215 nil)
217 (defun tramp-smb-handle-copy-file
218 (filename newname &optional ok-if-already-exists keep-date)
219 "Like `copy-file' for tramp files.
220 KEEP-DATE is not handled in case NEWNAME resides on an SMB server."
221 (setq filename (expand-file-name filename)
222 newname (expand-file-name newname))
224 (let ((tmpfile (file-local-copy filename)))
226 (if tmpfile
227 ;; remote filename
228 (rename-file tmpfile newname ok-if-already-exists)
230 ;; remote newname
231 (when (file-directory-p newname)
232 (setq newname (expand-file-name
233 (file-name-nondirectory filename) newname)))
234 (when (and (not ok-if-already-exists)
235 (file-exists-p newname))
236 (error "copy-file: file %s already exists" newname))
238 ; (with-parsed-tramp-file-name newname nil
239 (let (user host localname)
240 (with-parsed-tramp-file-name newname l
241 (setq user l-user host l-host localname l-localname))
242 (save-excursion
243 (let ((share (tramp-smb-get-share localname))
244 (file (tramp-smb-get-localname localname t)))
245 (unless share
246 (error "Target `%s' must contain a share name" filename))
247 (tramp-smb-maybe-open-connection user host share)
248 (tramp-message-for-buffer
249 nil tramp-smb-method user host
250 5 "Copying file %s to file %s..." filename newname)
251 (if (tramp-smb-send-command
252 user host (format "put %s \"%s\"" filename file))
253 (tramp-message-for-buffer
254 nil tramp-smb-method user host
255 5 "Copying file %s to file %s...done" filename newname)
256 (error "Cannot copy `%s'" filename))))))))
258 (defun tramp-smb-handle-delete-directory (directory)
259 "Like `delete-directory' for tramp files."
260 (setq directory (directory-file-name (expand-file-name directory)))
261 (unless (file-exists-p directory)
262 (error "Cannot delete non-existing directory `%s'" directory))
263 ; (with-parsed-tramp-file-name directory nil
264 (let (user host localname)
265 (with-parsed-tramp-file-name directory l
266 (setq user l-user host l-host localname l-localname))
267 (save-excursion
268 (let ((share (tramp-smb-get-share localname))
269 (dir (tramp-smb-get-localname (file-name-directory localname) t))
270 (file (file-name-nondirectory localname)))
271 (tramp-smb-maybe-open-connection user host share)
272 (if (and
273 (tramp-smb-send-command user host (format "cd \"%s\"" dir))
274 (tramp-smb-send-command user host (format "rmdir \"%s\"" file)))
275 ;; Go Home
276 (tramp-smb-send-command user host (format "cd \\"))
277 ;; Error
278 (tramp-smb-send-command user host (format "cd \\"))
279 (error "Cannot delete directory `%s'" directory))))))
281 (defun tramp-smb-handle-delete-file (filename)
282 "Like `delete-file' for tramp files."
283 (setq filename (expand-file-name filename))
284 (unless (file-exists-p filename)
285 (error "Cannot delete non-existing file `%s'" filename))
286 ; (with-parsed-tramp-file-name filename nil
287 (let (user host localname)
288 (with-parsed-tramp-file-name filename l
289 (setq user l-user host l-host localname l-localname))
290 (save-excursion
291 (let ((share (tramp-smb-get-share localname))
292 (dir (tramp-smb-get-localname (file-name-directory localname) t))
293 (file (file-name-nondirectory localname)))
294 (unless (file-exists-p filename)
295 (error "Cannot delete non-existing file `%s'" filename))
296 (tramp-smb-maybe-open-connection user host share)
297 (if (and
298 (tramp-smb-send-command user host (format "cd \"%s\"" dir))
299 (tramp-smb-send-command user host (format "rm \"%s\"" file)))
300 ;; Go Home
301 (tramp-smb-send-command user host (format "cd \\"))
302 ;; Error
303 (tramp-smb-send-command user host (format "cd \\"))
304 (error "Cannot delete file `%s'" filename))))))
306 (defun tramp-smb-handle-directory-files
307 (directory &optional full match nosort)
308 "Like `directory-files' for tramp files."
309 (setq directory (directory-file-name (expand-file-name directory)))
310 ; (with-parsed-tramp-file-name directory nil
311 (let (user host localname)
312 (with-parsed-tramp-file-name directory l
313 (setq user l-user host l-host localname l-localname))
314 (save-excursion
315 (let* ((share (tramp-smb-get-share localname))
316 (file (tramp-smb-get-localname localname nil))
317 (entries (tramp-smb-get-file-entries user host share file)))
318 ;; Just the file names are needed
319 (setq entries (mapcar 'car entries))
320 ;; Discriminate with regexp
321 (when match
322 (setq entries
323 (delete nil
324 (mapcar (lambda (x) (when (string-match match x) x))
325 entries))))
326 ;; Make absolute localnames if necessary
327 (when full
328 (setq entries
329 (mapcar (lambda (x)
330 (concat (file-name-as-directory directory) x))
331 entries)))
332 ;; Sort them if necessary
333 (unless nosort (setq entries (sort entries 'string-lessp)))
334 ;; That's it
335 entries))))
337 (defun tramp-smb-handle-directory-files-and-attributes
338 (directory &optional full match nosort id-format)
339 "Like `directory-files-and-attributes' for tramp files."
340 (mapcar
341 (lambda (x)
342 ;; We cannot call `file-attributes' for backward compatibility reasons.
343 ;; Its optional parameter ID-FORMAT is introduced with Emacs 21.4.
344 (cons x (tramp-smb-handle-file-attributes
345 (if full x (concat (file-name-as-directory directory) x)) id-format)))
346 (directory-files directory full match nosort)))
348 (defun tramp-smb-handle-file-attributes (filename &optional id-format)
349 "Like `file-attributes' for tramp files."
350 ; (with-parsed-tramp-file-name filename nil
351 (let (user host localname)
352 (with-parsed-tramp-file-name filename l
353 (setq user l-user host l-host localname l-localname))
354 (save-excursion
355 (let* ((share (tramp-smb-get-share localname))
356 (file (tramp-smb-get-localname localname nil))
357 (entries (tramp-smb-get-file-entries user host share file))
358 (entry (and entries
359 (assoc (file-name-nondirectory file) entries)))
360 (uid (if (and id-format (equal id-format 'string)) "nobody" -1))
361 (gid (if (and id-format (equal id-format 'string)) "nogroup" -1))
362 (inode (tramp-smb-get-inode share file))
363 (device (tramp-get-device nil tramp-smb-method user host)))
365 ; check result
366 (when entry
367 (list (and (string-match "d" (nth 1 entry))
368 t) ;0 file type
369 -1 ;1 link count
370 uid ;2 uid
371 gid ;3 gid
372 '(0 0) ;4 atime
373 (nth 3 entry) ;5 mtime
374 '(0 0) ;6 ctime
375 (nth 2 entry) ;7 size
376 (nth 1 entry) ;8 mode
377 nil ;9 gid weird
378 inode ;10 inode number
379 device)))))) ;11 file system number
381 (defun tramp-smb-handle-file-directory-p (filename)
382 "Like `file-directory-p' for tramp files."
383 ; (with-parsed-tramp-file-name filename nil
384 (let (user host localname)
385 (with-parsed-tramp-file-name filename l
386 (setq user l-user host l-host localname l-localname))
387 (save-excursion
388 (let* ((share (tramp-smb-get-share localname))
389 (file (tramp-smb-get-localname localname nil))
390 (entries (tramp-smb-get-file-entries user host share file))
391 (entry (and entries
392 (assoc (file-name-nondirectory file) entries))))
393 (and entry
394 (string-match "d" (nth 1 entry))
395 t)))))
397 (defun tramp-smb-handle-file-exists-p (filename)
398 "Like `file-exists-p' for tramp files."
399 ; (with-parsed-tramp-file-name filename nil
400 (let (user host localname)
401 (with-parsed-tramp-file-name filename l
402 (setq user l-user host l-host localname l-localname))
403 (save-excursion
404 (let* ((share (tramp-smb-get-share localname))
405 (file (tramp-smb-get-localname localname nil))
406 (entries (tramp-smb-get-file-entries user host share file)))
407 (and entries
408 (member (file-name-nondirectory file) (mapcar 'car entries))
409 t)))))
411 (defun tramp-smb-handle-file-local-copy (filename)
412 "Like `file-local-copy' for tramp files."
413 (with-parsed-tramp-file-name filename nil
414 (save-excursion
415 (let ((share (tramp-smb-get-share localname))
416 (file (tramp-smb-get-localname localname t))
417 (tmpfil (tramp-make-temp-file)))
418 (unless (file-exists-p filename)
419 (error "Cannot make local copy of non-existing file `%s'" filename))
420 (tramp-message-for-buffer
421 nil tramp-smb-method user host
422 5 "Fetching %s to tmp file %s..." filename tmpfil)
423 (tramp-smb-maybe-open-connection user host share)
424 (if (tramp-smb-send-command
425 user host (format "get \"%s\" %s" file tmpfil))
426 (tramp-message-for-buffer
427 nil tramp-smb-method user host
428 5 "Fetching %s to tmp file %s...done" filename tmpfil)
429 (error "Cannot make local copy of file `%s'" filename))
430 tmpfil))))
432 ;; This function should return "foo/" for directories and "bar" for
433 ;; files.
434 (defun tramp-smb-handle-file-name-all-completions (filename directory)
435 "Like `file-name-all-completions' for tramp files."
436 ; (with-parsed-tramp-file-name directory nil
437 (let (user host localname)
438 (with-parsed-tramp-file-name directory l
439 (setq user l-user host l-host localname l-localname))
440 (save-match-data
441 (save-excursion
442 (let* ((share (tramp-smb-get-share localname))
443 (file (tramp-smb-get-localname localname nil))
444 (entries (tramp-smb-get-file-entries user host share file)))
446 (all-completions
447 filename
448 (mapcar
449 (lambda (x)
450 (list
451 (if (string-match "d" (nth 1 x))
452 (file-name-as-directory (nth 0 x))
453 (nth 0 x))))
454 entries)))))))
456 (defun tramp-smb-handle-file-newer-than-file-p (file1 file2)
457 "Like `file-newer-than-file-p' for tramp files."
458 (cond
459 ((not (file-exists-p file1)) nil)
460 ((not (file-exists-p file2)) t)
461 (t (tramp-smb-time-less-p (file-attributes file2)
462 (file-attributes file1)))))
464 (defun tramp-smb-handle-file-writable-p (filename)
465 "Like `file-writable-p' for tramp files."
466 (if (not (file-exists-p filename))
467 (let ((dir (file-name-directory filename)))
468 (and (file-exists-p dir)
469 (file-writable-p dir)))
470 ; (with-parsed-tramp-file-name filename nil
471 (let (user host localname)
472 (with-parsed-tramp-file-name filename l
473 (setq user l-user host l-host localname l-localname))
474 (save-excursion
475 (let* ((share (tramp-smb-get-share localname))
476 (file (tramp-smb-get-localname localname nil))
477 (entries (tramp-smb-get-file-entries user host share file))
478 (entry (and entries
479 (assoc (file-name-nondirectory file) entries))))
480 (and share entry
481 (string-match "w" (nth 1 entry))
482 t))))))
484 (defun tramp-smb-handle-insert-directory
485 (filename switches &optional wildcard full-directory-p)
486 "Like `insert-directory' for tramp files.
487 WILDCARD and FULL-DIRECTORY-P are not handled."
488 (setq filename (expand-file-name filename))
489 (when (file-directory-p filename)
490 ;; This check is a little bit strange, but in `dired-add-entry'
491 ;; this function is called with a non-directory ...
492 (setq filename (file-name-as-directory filename)))
493 ; (with-parsed-tramp-file-name filename nil
494 (let (user host localname)
495 (with-parsed-tramp-file-name filename l
496 (setq user l-user host l-host localname l-localname))
497 (save-match-data
498 (let* ((share (tramp-smb-get-share localname))
499 (file (tramp-smb-get-localname localname nil))
500 (entries (tramp-smb-get-file-entries user host share file)))
502 ;; Delete dummy "" entry, useless entries
503 (setq entries
504 (if (file-directory-p filename)
505 (delq (assoc "" entries) entries)
506 ;; We just need the only and only entry FILENAME.
507 (list (assoc (file-name-nondirectory filename) entries))))
509 ;; Sort entries
510 (setq entries
511 (sort
512 entries
513 (lambda (x y)
514 (if (string-match "t" switches)
515 ; sort by date
516 (tramp-smb-time-less-p (nth 3 y) (nth 3 x))
517 ; sort by name
518 (string-lessp (nth 0 x) (nth 0 y))))))
520 ;; Print entries
521 (mapcar
522 (lambda (x)
523 (insert
524 (format
525 "%10s %3d %-8s %-8s %8s %s %s\n"
526 (nth 1 x) ; mode
527 1 "nobody" "nogroup"
528 (nth 2 x) ; size
529 (format-time-string
530 (if (tramp-smb-time-less-p
531 (tramp-smb-time-subtract (current-time) (nth 3 x))
532 tramp-smb-half-a-year)
533 "%b %e %R"
534 "%b %e %Y")
535 (nth 3 x)) ; date
536 (nth 0 x))) ; file name
537 (forward-line)
538 (beginning-of-line))
539 entries)))))
541 (defun tramp-smb-handle-make-directory (dir &optional parents)
542 "Like `make-directory' for tramp files."
543 (setq dir (directory-file-name (expand-file-name dir)))
544 (unless (file-name-absolute-p dir)
545 (setq dir (concat default-directory dir)))
546 ; (with-parsed-tramp-file-name dir nil
547 (let (user host localname)
548 (with-parsed-tramp-file-name dir l
549 (setq user l-user host l-host localname l-localname))
550 (save-match-data
551 (let* ((share (tramp-smb-get-share localname))
552 (ldir (file-name-directory dir)))
553 ;; Make missing directory parts
554 (when (and parents share (not (file-directory-p ldir)))
555 (make-directory ldir parents))
556 ;; Just do it
557 (when (file-directory-p ldir)
558 (make-directory-internal dir))
559 (unless (file-directory-p dir)
560 (error "Couldn't make directory %s" dir))))))
562 (defun tramp-smb-handle-make-directory-internal (directory)
563 "Like `make-directory-internal' for tramp files."
564 (setq directory (directory-file-name (expand-file-name directory)))
565 (unless (file-name-absolute-p directory)
566 (setq directory (concat default-directory directory)))
567 ; (with-parsed-tramp-file-name directory nil
568 (let (user host localname)
569 (with-parsed-tramp-file-name directory l
570 (setq user l-user host l-host localname l-localname))
571 (save-match-data
572 (let* ((share (tramp-smb-get-share localname))
573 (file (tramp-smb-get-localname localname nil)))
574 (when (file-directory-p (file-name-directory directory))
575 (tramp-smb-maybe-open-connection user host share)
576 (tramp-smb-send-command user host (format "mkdir \"%s\"" file)))
577 (unless (file-directory-p directory)
578 (error "Couldn't make directory %s" directory))))))
580 (defun tramp-smb-handle-rename-file
581 (filename newname &optional ok-if-already-exists)
582 "Like `rename-file' for tramp files."
583 (setq filename (expand-file-name filename)
584 newname (expand-file-name newname))
586 (let ((tmpfile (file-local-copy filename)))
588 (if tmpfile
589 ;; remote filename
590 (rename-file tmpfile newname ok-if-already-exists)
592 ;; remote newname
593 (when (file-directory-p newname)
594 (setq newname (expand-file-name
595 (file-name-nondirectory filename) newname)))
596 (when (and (not ok-if-already-exists)
597 (file-exists-p newname))
598 (error "rename-file: file %s already exists" newname))
600 ; (with-parsed-tramp-file-name newname nil
601 (let (user host localname)
602 (with-parsed-tramp-file-name newname l
603 (setq user l-user host l-host localname l-localname))
604 (save-excursion
605 (let ((share (tramp-smb-get-share localname))
606 (file (tramp-smb-get-localname localname t)))
607 (tramp-smb-maybe-open-connection user host share)
608 (tramp-message-for-buffer
609 nil tramp-smb-method user host
610 5 "Copying file %s to file %s..." filename newname)
611 (if (tramp-smb-send-command
612 user host (format "put %s \"%s\"" filename file))
613 (tramp-message-for-buffer
614 nil tramp-smb-method user host
615 5 "Copying file %s to file %s...done" filename newname)
616 (error "Cannot rename `%s'" filename)))))))
618 (delete-file filename))
620 (defun tramp-smb-handle-write-region
621 (start end filename &optional append visit lockname confirm)
622 "Like `write-region' for tramp files."
623 (unless (eq append nil)
624 (error "Cannot append to file using tramp (`%s')" filename))
625 (setq filename (expand-file-name filename))
626 ;; XEmacs takes a coding system as the seventh argument, not `confirm'
627 (when (and (not (featurep 'xemacs))
628 confirm (file-exists-p filename))
629 (unless (y-or-n-p (format "File %s exists; overwrite anyway? "
630 filename))
631 (error "File not overwritten")))
632 ; (with-parsed-tramp-file-name filename nil
633 (let (user host localname)
634 (with-parsed-tramp-file-name filename l
635 (setq user l-user host l-host localname l-localname))
636 (save-excursion
637 (let ((share (tramp-smb-get-share localname))
638 (file (tramp-smb-get-localname localname t))
639 (curbuf (current-buffer))
640 ;; We use this to save the value of `last-coding-system-used'
641 ;; after writing the tmp file. At the end of the function,
642 ;; we set `last-coding-system-used' to this saved value.
643 ;; This way, any intermediary coding systems used while
644 ;; talking to the remote shell or suchlike won't hose this
645 ;; variable. This approach was snarfed from ange-ftp.el.
646 coding-system-used
647 tmpfil)
648 ;; Write region into a tmp file.
649 (setq tmpfil (tramp-make-temp-file))
650 ;; We say `no-message' here because we don't want the visited file
651 ;; modtime data to be clobbered from the temp file. We call
652 ;; `set-visited-file-modtime' ourselves later on.
653 (tramp-run-real-handler
654 'write-region
655 (if confirm ; don't pass this arg unless defined for backward compat.
656 (list start end tmpfil append 'no-message lockname confirm)
657 (list start end tmpfil append 'no-message lockname)))
658 ;; Now, `last-coding-system-used' has the right value. Remember it.
659 (when (boundp 'last-coding-system-used)
660 (setq coding-system-used last-coding-system-used))
662 (tramp-smb-maybe-open-connection user host share)
663 (tramp-message-for-buffer
664 nil tramp-smb-method user host
665 5 "Writing tmp file %s to file %s..." tmpfil filename)
666 (if (tramp-smb-send-command
667 user host (format "put %s \"%s\"" tmpfil file))
668 (tramp-message-for-buffer
669 nil tramp-smb-method user host
670 5 "Writing tmp file %s to file %s...done" tmpfil filename)
671 (error "Cannot write `%s'" filename))
673 (delete-file tmpfil)
674 (unless (equal curbuf (current-buffer))
675 (error "Buffer has changed from `%s' to `%s'"
676 curbuf (current-buffer)))
677 (when (eq visit t)
678 (set-visited-file-modtime))
679 ;; Make `last-coding-system-used' have the right value.
680 (when (boundp 'last-coding-system-used)
681 (setq last-coding-system-used coding-system-used))))))
684 ;; Internal file name functions
686 (defun tramp-smb-get-share (localname)
687 "Returns the share name of LOCALNAME."
688 (save-match-data
689 (when (string-match "^/?\\([^/]+\\)/" localname)
690 (match-string 1 localname))))
692 (defun tramp-smb-get-localname (localname convert)
693 "Returns the file name of LOCALNAME.
694 If CONVERT is non-nil exchange \"/\" by \"\\\\\"."
695 (save-match-data
696 (let ((res localname))
698 (setq
699 res (if (string-match "^/?[^/]+/\\(.*\\)" res)
700 (if convert
701 (mapconcat
702 (lambda (x) (if (equal x ?/) "\\" (char-to-string x)))
703 (match-string 1 res) "")
704 (match-string 1 res))
705 (if (string-match "^/?\\([^/]+\\)$" res)
706 (match-string 1 res)
707 "")))
709 ;; Sometimes we have discarded `substitute-in-file-name'
710 (when (string-match "\\(\\$\\$\\)\\(/\\|$\\)" res)
711 (setq res (replace-match "$" nil nil res 1)))
713 res)))
715 ;; Share names of a host are cached. It is very unlikely that the
716 ;; shares do change during connection.
717 (defun tramp-smb-get-file-entries (user host share localname)
718 "Read entries which match LOCALNAME.
719 Either the shares are listed, or the `dir' command is executed.
720 Only entries matching the localname are returned.
721 Result is a list of (LOCALNAME MODE SIZE MONTH DAY TIME YEAR)."
722 (save-excursion
723 (save-match-data
724 (let ((base (or (and (> (length localname) 0)
725 (string-match "\\([^/]+\\)$" localname)
726 (regexp-quote (match-string 1 localname)))
727 ""))
728 res entry)
729 (set-buffer (tramp-get-buffer nil tramp-smb-method user host))
730 (if (and (not share) tramp-smb-share-cache)
731 ;; Return cached shares
732 (setq res tramp-smb-share-cache)
733 ;; Read entries
734 (tramp-smb-maybe-open-connection user host share)
735 (when share
736 (tramp-smb-send-command
737 user host
738 (format "dir %s"
739 (if (zerop (length localname)) "" (concat "\"" localname "*\"")))))
740 (goto-char (point-min))
741 ;; Loop the listing
742 (unless (re-search-forward tramp-smb-errors nil t)
743 (while (not (eobp))
744 (setq entry (tramp-smb-read-file-entry share))
745 (forward-line)
746 (when entry (add-to-list 'res entry))))
747 (unless share
748 ;; Cache share entries
749 (setq tramp-smb-share-cache res)))
751 ;; Add directory itself
752 (add-to-list 'res '("" "drwxrwxrwx" 0 (0 0)))
754 ;; There's a very strange error (debugged with XEmacs 21.4.14)
755 ;; If there's no short delay, it returns nil. No idea about
756 (when (featurep 'xemacs) (sleep-for 0.01))
758 ;; Check for matching entries
759 (delq nil (mapcar
760 (lambda (x) (and (string-match base (nth 0 x)) x))
761 res))))))
763 ;; Return either a share name (if SHARE is nil), or a file name
765 ;; If shares are listed, the following format is expected
767 ;; \s-\{8,8} - leading spaces
768 ;; \S-\(.*\S-\)\s-* - share name, 14 char
769 ;; \s- - space delimeter
770 ;; \S-+\s-* - type, 8 char, "Disk " expected
771 ;; \(\s-\{2,2\}.*\)? - space delimeter, comment
773 ;; Entries provided by smbclient DIR aren't fully regular.
774 ;; They should have the format
776 ;; \s-\{2,2} - leading spaces
777 ;; \S-\(.*\S-\)\s-* - file name, 30 chars, left bound
778 ;; \s-+[ADHRSV]* - permissions, 7 chars, right bound
779 ;; \s- - space delimeter
780 ;; \s-+[0-9]+ - size, 8 chars, right bound
781 ;; \s-\{2,2\} - space delimeter
782 ;; \w\{3,3\} - weekday
783 ;; \s- - space delimeter
784 ;; \w\{3,3\} - month
785 ;; \s- - space delimeter
786 ;; [ 19][0-9] - day
787 ;; \s- - space delimeter
788 ;; [0-9]\{2,2\}:[0-9]\{2,2\}:[0-9]\{2,2\} - time
789 ;; \s- - space delimeter
790 ;; [0-9]\{4,4\} - year
792 ;; samba/src/client.c (http://samba.org/doxygen/samba/client_8c-source.html)
793 ;; has function display_finfo:
795 ;; d_printf(" %-30s%7.7s %8.0f %s",
796 ;; finfo->name,
797 ;; attrib_string(finfo->mode),
798 ;; (double)finfo->size,
799 ;; asctime(LocalTime(&t)));
801 ;; in Samba 1.9, there's the following code:
803 ;; DEBUG(0,(" %-30s%7.7s%10d %s",
804 ;; CNV_LANG(finfo->name),
805 ;; attrib_string(finfo->mode),
806 ;; finfo->size,
807 ;; asctime(LocalTime(&t))));
809 ;; Problems:
810 ;; * Modern regexp constructs, like spy groups and counted repetitions, aren't
811 ;; available in older Emacsen.
812 ;; * The length of constructs (file name, size) might exceed the default.
813 ;; * File names might contain spaces.
814 ;; * Permissions might be empty.
816 ;; So we try to analyze backwards.
817 (defun tramp-smb-read-file-entry (share)
818 "Parse entry in SMB output buffer.
819 If SHARE is result, entries are of type dir. Otherwise, shares are listed.
820 Result is the list (LOCALNAME MODE SIZE MTIME)."
821 (let ((line (buffer-substring (point) (tramp-point-at-eol)))
822 localname mode size month day hour min sec year mtime)
824 (if (not share)
826 ; Read share entries
827 (when (string-match "^\\s-+\\(\\S-+\\)\\s-+Disk" line)
828 (setq localname (match-string 1 line)
829 mode "dr-xr-xr-x"
830 size 0))
832 ; Real listing
833 (block nil
835 ;; year
836 (if (string-match "\\([0-9]+\\)$" line)
837 (setq year (string-to-number (match-string 1 line))
838 line (substring line 0 -5))
839 (return))
841 ;; time
842 (if (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)$" line)
843 (setq hour (string-to-number (match-string 1 line))
844 min (string-to-number (match-string 2 line))
845 sec (string-to-number (match-string 3 line))
846 line (substring line 0 -9))
847 (return))
849 ;; day
850 (if (string-match "\\([0-9]+\\)$" line)
851 (setq day (string-to-number (match-string 1 line))
852 line (substring line 0 -3))
853 (return))
855 ;; month
856 (if (string-match "\\(\\w+\\)$" line)
857 (setq month (match-string 1 line)
858 line (substring line 0 -4))
859 (return))
861 ;; weekday
862 (if (string-match "\\(\\w+\\)$" line)
863 (setq line (substring line 0 -5))
864 (return))
866 ;; size
867 (if (string-match "\\([0-9]+\\)$" line)
868 (let ((length (- (max 10 (1+ (length (match-string 1 line)))))))
869 (setq size (string-to-number (match-string 1 line)))
870 (when (string-match "\\([ADHRSV]+\\)" (substring line length))
871 (setq length (+ length (match-end 0))))
872 (setq line (substring line 0 length)))
873 (return))
875 ;; mode: ARCH, DIR, HIDDEN, RONLY, SYSTEM, VOLID
876 (if (string-match "\\([ADHRSV]+\\)?$" line)
877 (setq
878 mode (or (match-string 1 line) "")
879 mode (save-match-data (format
880 "%s%s"
881 (if (string-match "D" mode) "d" "-")
882 (mapconcat
883 (lambda (x) "") " "
884 (concat "r" (if (string-match "R" mode) "-" "w") "x"))))
885 line (substring line 0 -7))
886 (return))
888 ;; localname
889 (if (string-match "^\\s-+\\(\\S-\\(.*\\S-\\)?\\)\\s-*$" line)
890 (setq localname (match-string 1 line))
891 (return))))
893 (when (and localname mode size)
894 (setq mtime
895 (if (and sec min hour day month year)
896 (encode-time
897 sec min hour day
898 (cdr (assoc (downcase month) tramp-smb-parse-time-months))
899 year)
900 '(0 0)))
901 (list localname mode size mtime))))
903 ;; Inodes don't exist for SMB files. Therefore we must generate virtual ones.
904 ;; Used in `find-buffer-visiting'.
905 ;; The method applied might be not so efficient (Ange-FTP uses hashes). But
906 ;; performance isn't the major issue given that file transfer will take time.
908 (defun tramp-smb-get-inode (share file)
909 "Returns the virtual inode number.
910 If it doesn't exist, generate a new one."
911 (let ((string (concat share "/" (directory-file-name file))))
912 (unless (assoc string tramp-smb-inodes)
913 (add-to-list 'tramp-smb-inodes
914 (list string (length tramp-smb-inodes))))
915 (nth 1 (assoc string tramp-smb-inodes))))
918 ;; Connection functions
920 (defun tramp-smb-send-command (user host command)
921 "Send the COMMAND to USER at HOST (logged into an SMB session).
922 Erases temporary buffer before sending the command. Returns nil if
923 there has been an error message from smbclient."
924 (save-excursion
925 (set-buffer (tramp-get-buffer nil tramp-smb-method user host))
926 (erase-buffer)
927 (tramp-send-command nil tramp-smb-method user host command nil t)
928 (tramp-smb-wait-for-output user host)))
930 (defun tramp-smb-maybe-open-connection (user host share)
931 "Maybe open a connection to HOST, logging in as USER, using `tramp-smb-program'.
932 Does not do anything if a connection is already open, but re-opens the
933 connection if a previous connection has died for some reason."
934 (let ((process-connection-type tramp-process-connection-type)
935 (p (get-buffer-process
936 (tramp-get-buffer nil tramp-smb-method user host))))
937 (save-excursion
938 (set-buffer (tramp-get-buffer nil tramp-smb-method user host))
939 ;; Check whether it is still the same share
940 (unless (and p (processp p) (string-equal tramp-smb-share share))
941 (when (and p (processp p))
942 (delete-process p)
943 (setq p nil)))
944 ;; If too much time has passed since last command was sent, look
945 ;; whether process is still alive. If it isn't, kill it.
946 (when (and tramp-last-cmd-time
947 (> (tramp-time-diff (current-time) tramp-last-cmd-time) 60)
948 p (processp p) (memq (process-status p) '(run open)))
949 (unless (and p (processp p) (memq (process-status p) '(run open)))
950 (delete-process p)
951 (setq p nil))))
952 (unless (and p (processp p) (memq (process-status p) '(run open)))
953 (when (and p (processp p))
954 (delete-process p))
955 (tramp-smb-open-connection user host share))))
957 (defun tramp-smb-open-connection (user host share)
958 "Open a connection using `tramp-smb-program'.
959 This starts the command `smbclient //HOST/SHARE -U USER', then waits
960 for a remote password prompt. It queries the user for the password,
961 then sends the password to the remote host.
963 Domain names in USER and port numbers in HOST are acknowledged."
965 (save-match-data
966 (let* ((buffer (tramp-get-buffer nil tramp-smb-method user host))
967 (real-user user)
968 (real-host host)
969 domain port args)
971 ; Check for domain ("user%domain") and port ("host#port")
972 (when (and user (string-match "\\(.+\\)%\\(.+\\)" user))
973 (setq real-user (or (match-string 1 user) user)
974 domain (match-string 2 user)))
976 (when (and host (string-match "\\(.+\\)#\\(.+\\)" host))
977 (setq real-host (or (match-string 1 host) host)
978 port (match-string 2 host)))
980 (if share
981 (setq args (list (concat "//" real-host "/" share)))
982 (setq args (list "-L" real-host )))
984 (if real-user
985 (setq args (append args (list "-U" real-user)))
986 (setq args (append args (list "-N"))))
988 (when domain (setq args (append args (list "-W" domain))))
989 (when port (setq args (append args (list "-p" port))))
991 ; OK, let's go
992 (tramp-pre-connection nil tramp-smb-method user host)
993 (tramp-message 7 "Opening connection for //%s@%s/%s..."
994 user host (or share ""))
996 (let* ((default-directory (tramp-temporary-file-directory))
997 ;; If we omit the conditional here, then we would use
998 ;; `undecided-dos' in some cases. With the conditional,
999 ;; we use nil in these cases. Which one is right?
1000 (coding-system-for-read (unless (and (not (featurep 'xemacs))
1001 (> emacs-major-version 20))
1002 tramp-dos-coding-system))
1003 (p (apply #'start-process (buffer-name buffer) buffer
1004 tramp-smb-program args)))
1006 (tramp-message 9 "Started process %s" (process-command p))
1007 (tramp-set-process-query-on-exit-flag p nil)
1008 (set-buffer buffer)
1009 (setq tramp-smb-share share)
1011 ; send password
1012 (when real-user
1013 (let ((pw-prompt "Password:"))
1014 (tramp-message 9 "Sending password")
1015 (tramp-enter-password p pw-prompt)))
1017 (unless (tramp-smb-wait-for-output user host)
1018 (tramp-clear-passwd user host)
1019 (error "Cannot open connection //%s@%s/%s"
1020 user host (or share "")))))))
1022 ;; We don't use timeouts. If needed, the caller shall wrap around.
1023 (defun tramp-smb-wait-for-output (user host)
1024 "Wait for output from smbclient command.
1025 Returns nil if an error message has appeared."
1026 (let ((proc (get-buffer-process (current-buffer)))
1027 (found (progn (goto-char (point-min))
1028 (re-search-forward tramp-smb-prompt nil t)))
1029 (err (progn (goto-char (point-min))
1030 (re-search-forward tramp-smb-errors nil t))))
1032 ;; Algorithm: get waiting output. See if last line contains
1033 ;; tramp-smb-prompt sentinel or tramp-smb-errors strings.
1034 ;; If not, wait a bit and again get waiting output.
1035 (while (and (not found) (not err))
1037 ;; Accept pending output.
1038 (accept-process-output proc)
1040 ;; Search for prompt.
1041 (goto-char (point-min))
1042 (setq found (re-search-forward tramp-smb-prompt nil t))
1044 ;; Search for errors.
1045 (goto-char (point-min))
1046 (setq err (re-search-forward tramp-smb-errors nil t)))
1048 ;; Add output to debug buffer if appropriate.
1049 (when tramp-debug-buffer
1050 (append-to-buffer
1051 (tramp-get-debug-buffer nil tramp-smb-method user host)
1052 (point-min) (point-max)))
1054 ;; Return value is whether no error message has appeared.
1055 (not err)))
1058 ;; Snarfed code from time-date.el and parse-time.el
1060 (defconst tramp-smb-half-a-year '(241 17024)
1061 "Evaluated by \"(days-to-time 183)\".")
1063 (defconst tramp-smb-parse-time-months '(("jan" . 1) ("feb" . 2) ("mar" . 3)
1064 ("apr" . 4) ("may" . 5) ("jun" . 6)
1065 ("jul" . 7) ("aug" . 8) ("sep" . 9)
1066 ("oct" . 10) ("nov" . 11) ("dec" . 12))
1067 "Alist mapping month names to integers.")
1069 (defun tramp-smb-time-less-p (t1 t2)
1070 "Say whether time value T1 is less than time value T2."
1071 (unless t1 (setq t1 '(0 0)))
1072 (unless t2 (setq t2 '(0 0)))
1073 (or (< (car t1) (car t2))
1074 (and (= (car t1) (car t2))
1075 (< (nth 1 t1) (nth 1 t2)))))
1077 (defun tramp-smb-time-subtract (t1 t2)
1078 "Subtract two time values.
1079 Return the difference in the format of a time value."
1080 (unless t1 (setq t1 '(0 0)))
1081 (unless t2 (setq t2 '(0 0)))
1082 (let ((borrow (< (cadr t1) (cadr t2))))
1083 (list (- (car t1) (car t2) (if borrow 1 0))
1084 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
1087 ;; `PC-do-completion' touches the returning "$$" by `substitute-in-file-name'.
1088 ;; Must be corrected.
1090 (defadvice PC-do-completion (around tramp-smb-advice-PC-do-completion activate)
1091 "Changes \"$\" back to \"$$\" in minibuffer."
1092 (if (funcall PC-completion-as-file-name-predicate)
1094 (progn
1095 ;; Substitute file names
1096 (let* ((beg (or (and (functionp 'minibuffer-prompt-end) ; Emacs 21
1097 (funcall 'minibuffer-prompt-end))
1098 (point-min)))
1099 (end (point-max))
1100 (str (substitute-in-file-name (buffer-substring beg end))))
1101 (delete-region beg end)
1102 (insert str)
1103 (ad-set-arg 2 (point)))
1105 ;; Do `PC-do-completion' without substitution
1106 (let* (save)
1107 (fset 'save (symbol-function 'substitute-in-file-name))
1108 (fset 'substitute-in-file-name (symbol-function 'identity))
1109 ad-do-it
1110 (fset 'substitute-in-file-name (symbol-function 'save)))
1112 ;; Expand "$"
1113 (let* ((beg (or (and (functionp 'minibuffer-prompt-end) ; Emacs 21
1114 (funcall 'minibuffer-prompt-end))
1115 (point-min)))
1116 (end (point-max))
1117 (str (buffer-substring beg end)))
1118 (delete-region beg end)
1119 (insert (if (string-match "\\(\\$\\)\\(/\\|$\\)" str)
1120 (replace-match "$$" nil nil str 1)
1121 str))))
1123 ;; No file names. Behave unchanged.
1124 ad-do-it))
1126 (provide 'tramp-smb)
1128 ;;; TODO:
1130 ;; * Provide a local smb.conf. The default one might not be readable.
1131 ;; * Error handling in case password is wrong.
1132 ;; * Read password from "~/.netrc".
1133 ;; * Return more comprehensive file permission string. Think whether it is
1134 ;; possible to implement `set-file-modes'.
1135 ;; * Handle WILDCARD and FULL-DIRECTORY-P in
1136 ;; `tramp-smb-handle-insert-directory'.
1137 ;; * Handle links (FILENAME.LNK).
1138 ;; * Maybe local tmp files should have the same extension like the original
1139 ;; files. Strange behaviour with jka-compr otherwise?
1140 ;; * Copy files in dired from SMB to another method doesn't work.
1141 ;; * Try to remove the inclusion of dummy "" directory. Seems to be at
1142 ;; several places, especially in `tramp-smb-handle-insert-directory'.
1143 ;; * Provide variables for debug.
1144 ;; * (RMS) Use unwind-protect to clean up the state so as to make the state
1145 ;; regular again.
1147 ;;; arch-tag: fcc9dbec-7503-4d73-b638-3c8aa59575f5
1148 ;;; tramp-smb.el ends here