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