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