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