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