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