]> code.delx.au - gnu-emacs/blob - lisp/net/tramp-adb.el
Merge from emacs-24; up to 2012-12-02T06:22:32Z!cyd@gnu.org
[gnu-emacs] / lisp / net / tramp-adb.el
1 ;;; tramp-adb.el --- Functions for calling Android Debug Bridge from Tramp
2
3 ;; Copyright (C) 2011-2012 Free Software Foundation, Inc.
4
5 ;; Author: Juergen Hoetzel <juergen@archlinux.org>
6 ;; Keywords: comm, processes
7 ;; Package: tramp
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. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; The Android Debug Bridge must be installed on your local machine.
27 ;; Add the following form into your .emacs:
28 ;;
29 ;; (setq tramp-adb-sdk-dir "/path/to/android/sdk")
30 ;;
31 ;; Due to security it is not possible to access non-root devices.
32
33 ;;; Code:
34
35 (require 'tramp)
36
37 (defvar dired-move-to-filename-regexp)
38
39 (defcustom tramp-adb-sdk-dir "~/Android/sdk"
40 "Set to the directory containing the Android SDK."
41 :type 'string
42 :version "24.4"
43 :group 'tramp)
44
45 ;;;###tramp-autoload
46 (defconst tramp-adb-method "adb"
47 "*When this method name is used, forward all calls to Android Debug Bridge.")
48
49 (defcustom tramp-adb-prompt "^\\(?:[[:alnum:]]*@[[:alnum:]]*[^#\\$]*\\)?[#\\$][[:space:]]"
50 "Regexp used as prompt in almquist shell."
51 :type 'string
52 :version "24.4"
53 :group 'tramp)
54
55 (defconst tramp-adb-ls-date-regexp "[[:space:]][0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9][[:space:]][0-9][0-9]:[0-9][0-9][[:space:]]")
56
57 ;;;###tramp-autoload
58 (add-to-list 'tramp-methods `(,tramp-adb-method))
59
60 ;;;###tramp-autoload
61 (eval-after-load 'tramp
62 '(tramp-set-completion-function
63 tramp-adb-method '((tramp-adb-parse-device-names ""))))
64
65 ;;;###tramp-autoload
66 (add-to-list 'tramp-foreign-file-name-handler-alist
67 (cons 'tramp-adb-file-name-p 'tramp-adb-file-name-handler))
68
69 (defconst tramp-adb-file-name-handler-alist
70 '((directory-file-name . tramp-handle-directory-file-name)
71 (dired-uncache . tramp-handle-dired-uncache)
72 (file-name-as-directory . tramp-handle-file-name-as-directory)
73 (file-name-completion . tramp-handle-file-name-completion)
74 (file-name-all-completions . tramp-adb-handle-file-name-all-completions)
75 (file-attributes . tramp-adb-handle-file-attributes)
76 (file-name-directory . tramp-handle-file-name-directory)
77 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
78 (file-truename . tramp-adb-handle-file-truename)
79 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
80 (file-name-as-directory . tramp-handle-file-name-as-directory)
81 (file-regular-p . tramp-handle-file-regular-p)
82 (file-remote-p . tramp-handle-file-remote-p)
83 (file-directory-p . tramp-adb-handle-file-directory-p)
84 (file-symlink-p . tramp-handle-file-symlink-p)
85 ;; FIXME: This is too sloppy.
86 (file-executable-p . file-exists-p)
87 (file-exists-p . tramp-adb-handle-file-exists-p)
88 (file-readable-p . tramp-handle-file-exists-p)
89 (file-writable-p . tramp-adb-handle-file-writable-p)
90 (file-local-copy . tramp-adb-handle-file-local-copy)
91 (file-modes . tramp-handle-file-modes)
92 (expand-file-name . tramp-adb-handle-expand-file-name)
93 (find-backup-file-name . tramp-handle-find-backup-file-name)
94 (directory-files . tramp-handle-directory-files)
95 (make-directory . tramp-adb-handle-make-directory)
96 (delete-directory . tramp-adb-handle-delete-directory)
97 (delete-file . tramp-adb-handle-delete-file)
98 (load . tramp-handle-load)
99 (insert-directory . tramp-adb-handle-insert-directory)
100 (insert-file-contents . tramp-handle-insert-file-contents)
101 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
102 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
103 (vc-registered . ignore) ;no vc control files on Android devices
104 (write-region . tramp-adb-handle-write-region)
105 (set-file-modes . tramp-adb-handle-set-file-modes)
106 (set-file-times . ignore)
107 (copy-file . tramp-adb-handle-copy-file)
108 (rename-file . tramp-adb-handle-rename-file)
109 (process-file . tramp-adb-handle-process-file)
110 (shell-command . tramp-adb-handle-shell-command)
111 (start-file-process . tramp-adb-handle-start-file-process))
112 "Alist of handler functions for Tramp ADB method.")
113
114 ;; It must be a `defsubst' in order to push the whole code into
115 ;; tramp-loaddefs.el. Otherwise, there would be recursive autoloading.
116 ;;;###tramp-autoload
117 (defsubst tramp-adb-file-name-p (filename)
118 "Check if it's a filename for ADB."
119 (let ((v (tramp-dissect-file-name filename)))
120 (string= (tramp-file-name-method v) tramp-adb-method)))
121
122 ;;;###tramp-autoload
123 (defun tramp-adb-file-name-handler (operation &rest args)
124 "Invoke the ADB handler for OPERATION.
125 First arg specifies the OPERATION, second arg is a list of arguments to
126 pass to the OPERATION."
127 (let ((fn (assoc operation tramp-adb-file-name-handler-alist))
128 ;; `tramp-default-host's default value is (system-name). Not
129 ;; useful for us.
130 (tramp-default-host
131 (unless (equal (eval (car (get 'tramp-default-host 'standard-value)))
132 tramp-default-host)
133 tramp-default-host)))
134 (if fn
135 (save-match-data (apply (cdr fn) args))
136 (tramp-run-real-handler operation args))))
137
138 ;; This cannot be a constant, because `tramp-adb-sdk-dir' is customizable.
139 (defun tramp-adb-program ()
140 "The Android Debug Bridge."
141 (expand-file-name "platform-tools/adb" tramp-adb-sdk-dir))
142
143 ;;;###tramp-autoload
144 (defun tramp-adb-parse-device-names (ignore)
145 "Return a list of (nil host) tuples allowed to access."
146 (with-temp-buffer
147 (when (zerop (call-process (tramp-adb-program) nil t nil "devices"))
148 (let (result)
149 (goto-char (point-min))
150 (while (search-forward-regexp "^\\(\\S-+\\)[[:space:]]+device$" nil t)
151 (add-to-list 'result (list nil (match-string 1))))
152 result))))
153
154 (defun tramp-adb-handle-expand-file-name (name &optional dir)
155 "Like `expand-file-name' for Tramp files."
156 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
157 (setq dir (or dir default-directory "/"))
158 ;; Unless NAME is absolute, concat DIR and NAME.
159 (unless (file-name-absolute-p name)
160 (setq name (concat (file-name-as-directory dir) name)))
161 ;; If NAME is not a Tramp file, run the real handler.
162 (if (not (tramp-tramp-file-p name))
163 (tramp-run-real-handler 'expand-file-name (list name nil))
164 ;; Dissect NAME.
165 (with-parsed-tramp-file-name name nil
166 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
167 (setq localname (concat "/" localname)))
168 ;; Do normal `expand-file-name' (this does "/./" and "/../").
169 ;; We bind `directory-sep-char' here for XEmacs on Windows,
170 ;; which would otherwise use backslash. `default-directory' is
171 ;; bound, because on Windows there would be problems with UNC
172 ;; shares or Cygwin mounts.
173 (let ((directory-sep-char ?/)
174 (default-directory (tramp-compat-temporary-file-directory)))
175 (tramp-make-tramp-file-name
176 method user host
177 (tramp-drop-volume-letter
178 (tramp-run-real-handler
179 'expand-file-name (list localname))))))))
180
181 (defun tramp-adb-handle-file-directory-p (filename)
182 "Like `file-directory-p' for Tramp files."
183 (car (file-attributes (file-truename filename))))
184
185 ;; This is derived from `tramp-sh-handle-file-truename'. Maybe the
186 ;; code could be shared?
187 (defun tramp-adb-handle-file-truename (filename &optional counter prev-dirs)
188 "Like `file-truename' for Tramp files."
189 (with-parsed-tramp-file-name (expand-file-name filename) nil
190 (with-tramp-file-property v localname "file-truename"
191 (let ((result nil)) ; result steps in reverse order
192 (tramp-message v 4 "Finding true name for `%s'" filename)
193 (let* ((directory-sep-char ?/)
194 (steps (tramp-compat-split-string localname "/"))
195 (localnamedir (tramp-run-real-handler
196 'file-name-as-directory (list localname)))
197 (is-dir (string= localname localnamedir))
198 (thisstep nil)
199 (numchase 0)
200 ;; Don't make the following value larger than
201 ;; necessary. People expect an error message in a
202 ;; timely fashion when something is wrong; otherwise
203 ;; they might think that Emacs is hung. Of course,
204 ;; correctness has to come first.
205 (numchase-limit 20)
206 symlink-target)
207 (while (and steps (< numchase numchase-limit))
208 (setq thisstep (pop steps))
209 (tramp-message
210 v 5 "Check %s"
211 (mapconcat 'identity
212 (append '("") (reverse result) (list thisstep))
213 "/"))
214 (setq symlink-target
215 (nth 0 (file-attributes
216 (tramp-make-tramp-file-name
217 method user host
218 (mapconcat 'identity
219 (append '("")
220 (reverse result)
221 (list thisstep))
222 "/")))))
223 (cond ((string= "." thisstep)
224 (tramp-message v 5 "Ignoring step `.'"))
225 ((string= ".." thisstep)
226 (tramp-message v 5 "Processing step `..'")
227 (pop result))
228 ((stringp symlink-target)
229 ;; It's a symlink, follow it.
230 (tramp-message v 5 "Follow symlink to %s" symlink-target)
231 (setq numchase (1+ numchase))
232 (when (file-name-absolute-p symlink-target)
233 (setq result nil))
234 ;; If the symlink was absolute, we'll get a string
235 ;; like "/user@host:/some/target"; extract the
236 ;; "/some/target" part from it.
237 (when (tramp-tramp-file-p symlink-target)
238 (unless (tramp-equal-remote filename symlink-target)
239 (tramp-error
240 v 'file-error
241 "Symlink target `%s' on wrong host" symlink-target))
242 (setq symlink-target localname))
243 (setq steps
244 (append (tramp-compat-split-string
245 symlink-target "/")
246 steps)))
247 (t
248 ;; It's a file.
249 (setq result (cons thisstep result)))))
250 (when (>= numchase numchase-limit)
251 (tramp-error
252 v 'file-error
253 "Maximum number (%d) of symlinks exceeded" numchase-limit))
254 (setq result (reverse result))
255 ;; Combine list to form string.
256 (setq result
257 (if result
258 (mapconcat 'identity (cons "" result) "/")
259 "/"))
260 (when (and is-dir (or (string= "" result)
261 (not (string= (substring result -1) "/"))))
262 (setq result (concat result "/"))))
263
264 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
265 (tramp-make-tramp-file-name method user host result)))))
266
267 (defun tramp-adb-handle-file-attributes (filename &optional id-format)
268 "Like `file-attributes' for Tramp files."
269 (unless id-format (setq id-format 'integer))
270 (ignore-errors
271 (with-parsed-tramp-file-name filename nil
272 (with-tramp-file-property v localname (format "file-attributes-%s" id-format)
273 (tramp-adb-barf-unless-okay
274 v (format "ls -d -l %s" (tramp-shell-quote-argument localname)) "")
275 (with-current-buffer (tramp-get-buffer v)
276 (tramp-adb-sh-fix-ls-output)
277 (let* ((columns (split-string (buffer-string)))
278 (mod-string (nth 0 columns))
279 (is-dir (eq ?d (aref mod-string 0)))
280 (is-symlink (eq ?l (aref mod-string 0)))
281 (symlink-target (and is-symlink (cadr (split-string (buffer-string) "\\( -> \\|\n\\)"))))
282 (uid (nth 1 columns))
283 (gid (nth 2 columns))
284 (date (format "%s %s" (nth 4 columns) (nth 5 columns)))
285 (size (string-to-number (nth 3 columns))))
286 (list
287 (or is-dir symlink-target)
288 1 ;link-count
289 ;; no way to handle numeric ids in Androids ash
290 (if (eq id-format 'integer) 0 uid)
291 (if (eq id-format 'integer) 0 gid)
292 '(0 0) ; atime
293 (date-to-time date) ; mtime
294 '(0 0) ; ctime
295 size
296 mod-string
297 ;; fake
298 t 1 1)))))))
299
300 (defun tramp-adb--gnu-switches-to-ash
301 (switches)
302 "Almquist shell can't handle multiple arguments.
303 Convert (\"-al\") to (\"-a\" \"-l\"). Remove arguments like \"--dired\"."
304 (split-string
305 (apply 'concat
306 (mapcar (lambda (s)
307 (replace-regexp-in-string
308 "\\(.\\)" " -\\1"
309 (replace-regexp-in-string "^-" "" s)))
310 ;; FIXME: Warning about removed switches (long and non-dash).
311 (delq nil
312 (mapcar
313 (lambda (s) (and (not (string-match "\\(^--\\|^[^-]\\)" s)) s))
314 switches))))))
315
316 (defun tramp-adb-handle-insert-directory
317 (filename switches &optional wildcard full-directory-p)
318 "Like `insert-directory' for Tramp files."
319 (when (stringp switches)
320 (setq switches (tramp-adb--gnu-switches-to-ash (split-string switches))))
321 (with-parsed-tramp-file-name (file-truename filename) nil
322 (with-current-buffer (tramp-get-buffer v)
323 (let ((name (tramp-shell-quote-argument (directory-file-name localname)))
324 (switch-d (member "-d" switches))
325 (switch-t (member "-t" switches))
326 (switches (mapconcat 'identity (remove "-t" switches) " ")))
327 (tramp-adb-barf-unless-okay
328 v (format "ls %s %s" switches name)
329 "Cannot insert directory listing: %s" filename)
330 (unless switch-d
331 ;; We insert also filename/. and filename/.., because "ls" doesn't.
332 (narrow-to-region (point) (point))
333 (ignore-errors
334 (tramp-adb-barf-unless-okay
335 v (format "ls -d %s %s %s"
336 switches
337 (concat (file-name-as-directory name) ".")
338 (concat (file-name-as-directory name) ".."))
339 "Cannot insert directory listing: %s" filename))
340 (widen))
341 (tramp-adb-sh-fix-ls-output switch-t)))
342 (insert-buffer-substring (tramp-get-buffer v))))
343
344 (defun tramp-adb-sh-fix-ls-output (&optional sort-by-time)
345 "Androids ls command doesn't insert size column for directories: Emacs dired can't find files. Insert dummy 0 in empty size columns."
346 (save-excursion
347 ;; Insert missing size.
348 (goto-char (point-min))
349 (while (search-forward-regexp "[[:space:]]\\([[:space:]][0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9][[:space:]]\\)" nil t)
350 (replace-match "0\\1" "\\1" nil)
351 ;; Insert missing "/".
352 (when (looking-at "[0-9][0-9]:[0-9][0-9][[:space:]]+$")
353 (end-of-line)
354 (insert "/")))
355 ;; Sort entries.
356 (let* ((lines (split-string (buffer-string) "\n" t))
357 (sorted-lines
358 (sort
359 lines
360 (if sort-by-time
361 'tramp-adb-ls-output-time-less-p
362 'tramp-adb-ls-output-name-less-p))))
363 (delete-region (point-min) (point-max))
364 (insert " " (mapconcat 'identity sorted-lines "\n ")))
365 ;; Add final newline.
366 (goto-char (point-max))
367 (unless (= (point) (line-beginning-position))
368 (insert "\n"))))
369
370
371 (defun tramp-adb-ls-output-time-less-p (a b)
372 "Sort \"ls\" output by time, descending."
373 (let (time-a time-b)
374 (string-match tramp-adb-ls-date-regexp a)
375 (setq time-a (apply 'encode-time (parse-time-string (match-string 0 a))))
376 (string-match tramp-adb-ls-date-regexp b)
377 (setq time-b (apply 'encode-time (parse-time-string (match-string 0 b))))
378 (time-less-p time-b time-a)))
379
380 (defun tramp-adb-ls-output-name-less-p (a b)
381 "Sort \"ls\" output by name, ascending."
382 (let (posa posb)
383 (string-match dired-move-to-filename-regexp a)
384 (setq posa (match-end 0))
385 (string-match dired-move-to-filename-regexp b)
386 (setq posb (match-end 0))
387 (string-lessp (substring a posa) (substring b posb))))
388
389 (defun tramp-adb-handle-make-directory (dir &optional parents)
390 "Like `make-directory' for Tramp files."
391 (setq dir (expand-file-name dir))
392 (with-parsed-tramp-file-name dir nil
393 (when parents
394 (let ((par (expand-file-name ".." dir)))
395 (unless (file-directory-p par)
396 (make-directory par parents))))
397 (tramp-adb-barf-unless-okay
398 v (format "mkdir %s" (tramp-shell-quote-argument localname))
399 "Couldn't make directory %s" dir)
400 (tramp-flush-directory-property v (file-name-directory localname))))
401
402 (defun tramp-adb-handle-delete-directory (directory &optional recursive)
403 "Like `delete-directory' for Tramp files."
404 (setq directory (expand-file-name directory))
405 (with-parsed-tramp-file-name directory nil
406 (tramp-flush-file-property v (file-name-directory localname))
407 (tramp-flush-directory-property v localname)
408 (tramp-adb-barf-unless-okay
409 v (format "%s %s"
410 (if recursive "rm -r" "rmdir")
411 (tramp-shell-quote-argument localname))
412 "Couldn't delete %s" directory)))
413
414 (defun tramp-adb-handle-delete-file (filename &optional trash)
415 "Like `delete-file' for Tramp files."
416 (setq filename (expand-file-name filename))
417 (with-parsed-tramp-file-name filename nil
418 (tramp-flush-file-property v (file-name-directory localname))
419 (tramp-flush-file-property v localname)
420 (tramp-adb-barf-unless-okay
421 v (format "rm %s" (tramp-shell-quote-argument localname))
422 "Couldn't delete %s" filename)))
423
424 (defun tramp-adb-handle-file-name-all-completions (filename directory)
425 "Like `file-name-all-completions' for Tramp files."
426 (all-completions
427 filename
428 (with-parsed-tramp-file-name directory nil
429 (with-tramp-file-property v localname "file-name-all-completions"
430 (save-match-data
431 (tramp-adb-send-command
432 v (format "ls %s" (tramp-shell-quote-argument localname)))
433 (mapcar
434 (lambda (f)
435 (if (file-directory-p f)
436 (file-name-as-directory f)
437 f))
438 (with-current-buffer (tramp-get-buffer v)
439 (delq
440 nil
441 (mapcar
442 (lambda (l) (and (not (string-match "^[[:space:]]*$" l)) l))
443 (split-string (buffer-string) "\n"))))))))))
444
445 (defun tramp-adb-handle-file-local-copy (filename)
446 "Like `file-local-copy' for Tramp files."
447 (with-parsed-tramp-file-name filename nil
448 (unless (file-exists-p (file-truename filename))
449 (tramp-error
450 v 'file-error
451 "Cannot make local copy of non-existing file `%s'" filename))
452 (let ((tmpfile (tramp-compat-make-temp-file filename)))
453 (with-tramp-progress-reporter
454 v 3 (format "Fetching %s to tmp file %s" filename tmpfile)
455 (when (tramp-adb-execute-adb-command v "pull" localname tmpfile)
456 (delete-file tmpfile)
457 (tramp-error
458 v 'file-error "Cannot make local copy of file `%s'" filename))
459 (set-file-modes tmpfile (file-modes filename)))
460 tmpfile)))
461
462 (defun tramp-adb-handle-file-writable-p (filename)
463 "Like `tramp-sh-handle-file-writable-p'.
464 But handle the case, if the \"test\" command is not available."
465 (with-parsed-tramp-file-name filename nil
466 (with-tramp-file-property v localname "file-writable-p"
467 (if (tramp-adb-find-test-command v)
468 (if (file-exists-p filename)
469 (zerop
470 (tramp-adb-command-exit-status
471 v (format "test -w %s" (tramp-shell-quote-argument localname))))
472 (and
473 (file-directory-p (file-name-directory filename))
474 (file-writable-p (file-name-directory filename))))
475
476 ;; Missing "test" command on Android < 4.
477 (let ((rw-path "/data/data"))
478 (tramp-message
479 v 5
480 "Not implemented yet (assuming \"/data/data\" is writable): %s"
481 localname)
482 (and (>= (length localname) (length rw-path))
483 (string= (substring localname 0 (length rw-path))
484 rw-path)))))))
485
486 (defun tramp-adb-handle-write-region
487 (start end filename &optional append visit lockname confirm)
488 "Like `write-region' for Tramp files."
489 (setq filename (expand-file-name filename))
490 (with-parsed-tramp-file-name filename nil
491 (when append
492 (tramp-error
493 v 'file-error "Cannot append to file using Tramp (`%s')" filename))
494 (when (and confirm (file-exists-p filename))
495 (unless (y-or-n-p (format "File %s exists; overwrite anyway? "
496 filename))
497 (tramp-error v 'file-error "File not overwritten")))
498 ;; We must also flush the cache of the directory, because
499 ;; `file-attributes' reads the values from there.
500 (tramp-flush-file-property v (file-name-directory localname))
501 (tramp-flush-file-property v localname)
502 (let* ((curbuf (current-buffer))
503 (tmpfile (tramp-compat-make-temp-file filename)))
504 (tramp-run-real-handler
505 'write-region
506 (list start end tmpfile append 'no-message lockname confirm))
507 (with-tramp-progress-reporter
508 v 3 (format "Moving tmp file %s to %s" tmpfile filename)
509 (unwind-protect
510 (when (tramp-adb-execute-adb-command v "push" tmpfile localname)
511 (tramp-error v 'file-error "Cannot write: `%s' filename"))
512 (delete-file tmpfile)))
513
514 (unless (equal curbuf (current-buffer))
515 (tramp-error
516 v 'file-error
517 "Buffer has changed from `%s' to `%s'" curbuf (current-buffer))))))
518
519 (defun tramp-adb-handle-set-file-modes (filename mode)
520 "Like `set-file-modes' for Tramp files."
521 (with-parsed-tramp-file-name filename nil
522 (tramp-flush-file-property v localname)
523 (tramp-adb-barf-unless-okay
524 v (format "chmod %s %s" (tramp-compat-decimal-to-octal mode) localname)
525 "Error while changing file's mode %s" filename)))
526
527 (defun tramp-adb-handle-copy-file
528 (filename newname &optional ok-if-already-exists keep-date
529 preserve-uid-gid preserve-extended-attributes)
530 "Like `copy-file' for Tramp files.
531 PRESERVE-UID-GID and PRESERVE-EXTENDED-ATTRIBUTES are completely ignored."
532 (setq filename (expand-file-name filename)
533 newname (expand-file-name newname))
534
535 (if (file-directory-p filename)
536 (copy-directory filename newname keep-date t)
537 (with-tramp-progress-reporter
538 (tramp-dissect-file-name (if (file-remote-p filename) filename newname))
539 0 (format "Copying %s to %s" filename newname)
540
541 (let ((tmpfile (file-local-copy filename)))
542
543 (if tmpfile
544 ;; Remote filename.
545 (condition-case err
546 (rename-file tmpfile newname ok-if-already-exists)
547 ((error quit)
548 (delete-file tmpfile)
549 (signal (car err) (cdr err))))
550
551 ;; Remote newname.
552 (when (file-directory-p newname)
553 (setq newname
554 (expand-file-name (file-name-nondirectory filename) newname)))
555
556 (with-parsed-tramp-file-name newname nil
557 (when (and (not ok-if-already-exists)
558 (file-exists-p newname))
559 (tramp-error v 'file-already-exists newname))
560
561 ;; We must also flush the cache of the directory, because
562 ;; `file-attributes' reads the values from there.
563 (tramp-flush-file-property v (file-name-directory localname))
564 (tramp-flush-file-property v localname)
565 (when (tramp-adb-execute-adb-command v "push" filename localname)
566 (tramp-error
567 v 'file-error "Cannot copy `%s' `%s'" filename newname))))))
568
569 ;; KEEP-DATE handling.
570 (when keep-date
571 (set-file-times newname (nth 5 (file-attributes filename))))))
572
573 (defun tramp-adb-handle-rename-file
574 (filename newname &optional ok-if-already-exists)
575 "Like `rename-file' for Tramp files."
576 (setq filename (expand-file-name filename)
577 newname (expand-file-name newname))
578
579 (with-parsed-tramp-file-name
580 (if (file-remote-p filename) filename newname) nil
581 (with-tramp-progress-reporter
582 v 0 (format "Renaming %s to %s" newname filename)
583
584 (if (and (tramp-equal-remote filename newname)
585 (not (file-directory-p filename)))
586 (progn
587 (when (and (not ok-if-already-exists)
588 (file-exists-p newname))
589 (tramp-error v 'file-already-exists newname))
590 ;; We must also flush the cache of the directory, because
591 ;; `file-attributes' reads the values from there.
592 (tramp-flush-file-property v (file-name-directory localname))
593 (tramp-flush-file-property v localname)
594 ;; Short track.
595 (tramp-adb-barf-unless-okay
596 v (format "mv %s %s" (file-remote-p filename 'localname) localname)
597 "Error renaming %s to %s" filename newname))
598
599 ;; Rename by copy.
600 (copy-file filename newname ok-if-already-exists t t)
601 (delete-file filename)))))
602
603 (defun tramp-adb-handle-process-file
604 (program &optional infile destination display &rest args)
605 "Like `process-file' for Tramp files."
606 ;; The implementation is not complete yet.
607 (when (and (numberp destination) (zerop destination))
608 (error "Implementation does not handle immediate return"))
609
610 (with-parsed-tramp-file-name default-directory nil
611 (let (command input tmpinput stderr tmpstderr outbuf ret)
612 ;; Compute command.
613 (setq command (mapconcat 'tramp-shell-quote-argument
614 (cons program args) " "))
615 ;; Determine input.
616 (if (null infile)
617 (setq input "/dev/null")
618 (setq infile (expand-file-name infile))
619 (if (tramp-equal-remote default-directory infile)
620 ;; INFILE is on the same remote host.
621 (setq input (with-parsed-tramp-file-name infile nil localname))
622 ;; INFILE must be copied to remote host.
623 (setq input (tramp-make-tramp-temp-file v)
624 tmpinput (tramp-make-tramp-file-name method user host input))
625 (copy-file infile tmpinput t)))
626 (when input (setq command (format "%s <%s" command input)))
627
628 ;; Determine output.
629 (cond
630 ;; Just a buffer.
631 ((bufferp destination)
632 (setq outbuf destination))
633 ;; A buffer name.
634 ((stringp destination)
635 (setq outbuf (get-buffer-create destination)))
636 ;; (REAL-DESTINATION ERROR-DESTINATION)
637 ((consp destination)
638 ;; output.
639 (cond
640 ((bufferp (car destination))
641 (setq outbuf (car destination)))
642 ((stringp (car destination))
643 (setq outbuf (get-buffer-create (car destination))))
644 ((car destination)
645 (setq outbuf (current-buffer))))
646 ;; stderr.
647 (cond
648 ((stringp (cadr destination))
649 (setcar (cdr destination) (expand-file-name (cadr destination)))
650 (if (tramp-equal-remote default-directory (cadr destination))
651 ;; stderr is on the same remote host.
652 (setq stderr (with-parsed-tramp-file-name
653 (cadr destination) nil localname))
654 ;; stderr must be copied to remote host. The temporary
655 ;; file must be deleted after execution.
656 (setq stderr (tramp-make-tramp-temp-file v)
657 tmpstderr (tramp-make-tramp-file-name
658 method user host stderr))))
659 ;; stderr to be discarded.
660 ((null (cadr destination))
661 (setq stderr "/dev/null"))))
662 ;; 't
663 (destination
664 (setq outbuf (current-buffer))))
665 (when stderr (setq command (format "%s 2>%s" command stderr)))
666
667 ;; Send the command. It might not return in time, so we protect
668 ;; it. Call it in a subshell, in order to preserve working
669 ;; directory.
670 (condition-case nil
671 (progn
672 (setq ret 0
673 ret
674 (tramp-adb-barf-unless-okay
675 v (format "(cd %s; %s)"
676 (tramp-shell-quote-argument localname)
677 command)
678 ""))
679 ;; We should show the output anyway.
680 (when outbuf
681 (with-current-buffer outbuf
682 (insert-buffer-substring (tramp-get-connection-buffer v)))
683 (when display (display-buffer outbuf))))
684 ;; When the user did interrupt, we should do it also. We use
685 ;; return code -1 as marker.
686 (quit
687 (kill-buffer (tramp-get-connection-buffer v))
688 (setq ret -1))
689 ;; Handle errors.
690 (error
691 (kill-buffer (tramp-get-connection-buffer v))
692 (setq ret 1)))
693
694 ;; Provide error file.
695 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
696
697 ;; Cleanup. We remove all file cache values for the connection,
698 ;; because the remote process could have changed them.
699 (when tmpinput (delete-file tmpinput))
700
701 ;; `process-file-side-effects' has been introduced with GNU
702 ;; Emacs 23.2. If set to `nil', no remote file will be changed
703 ;; by `program'. If it doesn't exist, we assume its default
704 ;; value 't'.
705 (unless (and (boundp 'process-file-side-effects)
706 (not (symbol-value 'process-file-side-effects)))
707 (tramp-flush-directory-property v ""))
708
709 ;; Return exit status.
710 (if (equal ret -1)
711 (keyboard-quit)
712 ret))))
713
714 (defun tramp-adb-handle-shell-command
715 (command &optional output-buffer error-buffer)
716 "Like `shell-command' for Tramp files."
717 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
718 ;; We cannot use `shell-file-name' and `shell-command-switch',
719 ;; they are variables of the local host.
720 (args (list "sh" "-c" (substring command 0 asynchronous)))
721 current-buffer-p
722 (output-buffer
723 (cond
724 ((bufferp output-buffer) output-buffer)
725 ((stringp output-buffer) (get-buffer-create output-buffer))
726 (output-buffer
727 (setq current-buffer-p t)
728 (current-buffer))
729 (t (get-buffer-create
730 (if asynchronous
731 "*Async Shell Command*"
732 "*Shell Command Output*")))))
733 (error-buffer
734 (cond
735 ((bufferp error-buffer) error-buffer)
736 ((stringp error-buffer) (get-buffer-create error-buffer))))
737 (buffer
738 (if (and (not asynchronous) error-buffer)
739 (with-parsed-tramp-file-name default-directory nil
740 (list output-buffer (tramp-make-tramp-temp-file v)))
741 output-buffer))
742 (p (get-buffer-process output-buffer)))
743
744 ;; Check whether there is another process running. Tramp does not
745 ;; support 2 (asynchronous) processes in parallel.
746 (when p
747 (if (yes-or-no-p "A command is running. Kill it? ")
748 (ignore-errors (kill-process p))
749 (error "Shell command in progress")))
750
751 (if current-buffer-p
752 (progn
753 (barf-if-buffer-read-only)
754 (push-mark nil t))
755 (with-current-buffer output-buffer
756 (setq buffer-read-only nil)
757 (erase-buffer)))
758
759 (if (and (not current-buffer-p) (integerp asynchronous))
760 (prog1
761 ;; Run the process.
762 (apply 'start-file-process "*Async Shell*" buffer args)
763 ;; Display output.
764 (pop-to-buffer output-buffer)
765 (setq mode-line-process '(":%s"))
766 (shell-mode))
767
768 (prog1
769 ;; Run the process.
770 (apply 'process-file (car args) nil buffer nil (cdr args))
771 ;; Insert error messages if they were separated.
772 (when (listp buffer)
773 (with-current-buffer error-buffer
774 (insert-file-contents (cadr buffer)))
775 (delete-file (cadr buffer)))
776 (if current-buffer-p
777 ;; This is like exchange-point-and-mark, but doesn't
778 ;; activate the mark. It is cleaner to avoid activation,
779 ;; even though the command loop would deactivate the mark
780 ;; because we inserted text.
781 (goto-char (prog1 (mark t)
782 (set-marker (mark-marker) (point)
783 (current-buffer))))
784 ;; There's some output, display it.
785 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
786 (if (functionp 'display-message-or-buffer)
787 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
788 (pop-to-buffer output-buffer))))))))
789
790 ;; We use BUFFER also as connection buffer during setup. Because of
791 ;; this, its original contents must be saved, and restored once
792 ;; connection has been setup.
793 (defun tramp-adb-handle-start-file-process (name buffer program &rest args)
794 "Like `start-file-process' for Tramp files."
795 (with-parsed-tramp-file-name default-directory nil
796 ;; When PROGRAM is nil, we just provide a tty.
797 (let ((command
798 (when (stringp program)
799 (format "cd %s; %s"
800 (tramp-shell-quote-argument localname)
801 (mapconcat 'tramp-shell-quote-argument
802 (cons program args) " "))))
803 (tramp-process-connection-type
804 (or (null program) tramp-process-connection-type))
805 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
806 (name1 name)
807 (i 0))
808 (unwind-protect
809 (save-excursion
810 (save-restriction
811 (unless buffer
812 ;; BUFFER can be nil. We use a temporary buffer.
813 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
814 (while (get-process name1)
815 ;; NAME must be unique as process name.
816 (setq i (1+ i)
817 name1 (format "%s<%d>" name i)))
818 (setq name name1)
819 ;; Set the new process properties.
820 (tramp-set-connection-property v "process-name" name)
821 (tramp-set-connection-property v "process-buffer" buffer)
822 ;; Activate narrowing in order to save BUFFER contents.
823 ;; Clear also the modification time; otherwise we might
824 ;; be interrupted by `verify-visited-file-modtime'.
825 (with-current-buffer (tramp-get-connection-buffer v)
826 (let ((buffer-undo-list t))
827 (clear-visited-file-modtime)
828 (narrow-to-region (point-max) (point-max))
829 (if command
830 ;; Send the command.
831 (tramp-adb-send-command v command)
832 ;; Open the connection.
833 (tramp-adb-maybe-open-connection v))))
834 (let ((p (tramp-get-connection-process v)))
835 ;; Set sentinel and query flag for this process.
836 (tramp-set-connection-property p "vector" v)
837 (set-process-sentinel p 'tramp-process-sentinel)
838 (tramp-compat-set-process-query-on-exit-flag p t)
839 ;; Return process.
840 p)))
841 ;; Save exit.
842 (with-current-buffer (tramp-get-connection-buffer v)
843 (if (string-match tramp-temp-buffer-name (buffer-name))
844 (progn
845 (set-process-buffer (tramp-get-connection-process v) nil)
846 (kill-buffer (current-buffer)))
847 (set-buffer-modified-p bmp)))
848 (tramp-set-connection-property v "process-name" nil)
849 (tramp-set-connection-property v "process-buffer" nil)))))
850
851 ;; Android < 4 doesn't provide test command.
852
853 (defun tramp-adb-handle-file-exists-p (filename)
854 "Like `file-exists-p' for Tramp files."
855 (with-parsed-tramp-file-name filename nil
856 (with-tramp-file-property v localname "file-exists-p"
857 (file-attributes filename))))
858
859 ;; Helper functions.
860
861 (defun tramp-adb-execute-adb-command (vec &rest args)
862 "Returns nil on success error-output on failure."
863 (when (tramp-file-name-host vec)
864 (setq args (append (list "-s" (tramp-file-name-host vec)) args)))
865 (with-temp-buffer
866 (prog1
867 (unless (zerop (apply 'call-process (tramp-adb-program) nil t nil args))
868 (buffer-string))
869 (tramp-message
870 vec 6 "%s %s\n%s"
871 (tramp-adb-program) (mapconcat 'identity args " ") (buffer-string)))))
872
873 (defun tramp-adb-find-test-command (vec)
874 "Checks, whether the ash has a builtin \"test\" command.
875 This happens for Android >= 4.0."
876 (with-tramp-connection-property vec "test"
877 (zerop (tramp-adb-command-exit-status vec "type test"))))
878
879 ;; Connection functions
880
881 (defun tramp-adb-send-command (vec command)
882 "Send the COMMAND to connection VEC."
883 (tramp-adb-maybe-open-connection vec)
884 (tramp-message vec 6 "%s" command)
885 (tramp-send-string vec command)
886 ;; fixme: Race condition
887 (tramp-adb-wait-for-output (tramp-get-connection-process vec))
888 (with-current-buffer (tramp-get-connection-buffer vec)
889 (save-excursion
890 (goto-char (point-min))
891 ;; We can't use stty to disable echo of command.
892 (delete-matching-lines (regexp-quote command))
893 ;; When the local machine is W32, there are still trailing ^M.
894 ;; There must be a better solution by setting the correct coding
895 ;; system, but this requires changes in core Tramp.
896 (goto-char (point-min))
897 (while (re-search-forward "\r+$" nil t)
898 (replace-match "" nil nil)))))
899
900 (defun tramp-adb-barf-unless-okay (vec command fmt &rest args)
901 "Run COMMAND, check exit status, throw error if exit status not okay.
902 FMT and ARGS are passed to `error'."
903 (tramp-adb-send-command vec (format "%s; echo tramp_exit_status $?" command))
904 (with-current-buffer (tramp-get-connection-buffer vec)
905 (goto-char (point-max))
906 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
907 (tramp-error
908 vec 'file-error "Couldn't find exit status of `%s'" command))
909 (skip-chars-forward "^ ")
910 (unless (zerop (read (current-buffer)))
911 (apply 'tramp-error vec 'file-error fmt args))
912 (let (buffer-read-only)
913 (delete-region (match-beginning 0) (point-max)))))
914
915 (defun tramp-adb-command-exit-status
916 (vec command)
917 "Run COMMAND and return its exit status.
918 Sends `echo $?' along with the COMMAND for checking the exit status. If
919 COMMAND is nil, just sends `echo $?'. Returns the exit status found."
920 (tramp-adb-send-command vec (format "%s; echo tramp_exit_status $?" command))
921 (with-current-buffer (tramp-get-connection-buffer vec)
922 (goto-char (point-max))
923 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
924 (tramp-error
925 vec 'file-error "Couldn't find exit status of `%s'" command))
926 (skip-chars-forward "^ ")
927 (read (current-buffer))))
928
929 (defun tramp-adb-wait-for-output (proc &optional timeout)
930 "Wait for output from remote command."
931 (unless (buffer-live-p (process-buffer proc))
932 (delete-process proc)
933 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
934 (with-current-buffer (process-buffer proc)
935 (if (tramp-wait-for-regexp proc timeout tramp-adb-prompt)
936 (let (buffer-read-only)
937 (goto-char (point-min))
938 ;; ADB terminal sends "^H" sequences.
939 (when (re-search-forward "<\b+" (point-at-eol) t)
940 (forward-line 1)
941 (delete-region (point-min) (point)))
942 ;; Delete the prompt.
943 (goto-char (point-min))
944 (when (re-search-forward tramp-adb-prompt (point-at-eol) t)
945 (forward-line 1)
946 (delete-region (point-min) (point)))
947 (goto-char (point-max))
948 (re-search-backward tramp-adb-prompt nil t)
949 (delete-region (point) (point-max)))
950 (if timeout
951 (tramp-error
952 proc 'file-error
953 "[[Remote adb prompt `%s' not found in %d secs]]"
954 tramp-adb-prompt timeout)
955 (tramp-error
956 proc 'file-error
957 "[[Remote prompt `%s' not found]]" tramp-adb-prompt)))))
958
959 (defun tramp-adb-maybe-open-connection (vec)
960 "Maybe open a connection VEC.
961 Does not do anything if a connection is already open, but re-opens the
962 connection if a previous connection has died for some reason."
963 (let* ((buf (tramp-get-connection-buffer vec))
964 (p (get-buffer-process buf)))
965 (unless
966 (and p (processp p) (memq (process-status p) '(run open)))
967 (save-match-data
968 (when (and p (processp p)) (delete-process p))
969 (with-tramp-progress-reporter vec 3 "Opening adb shell connection"
970 (let* ((coding-system-for-read 'utf-8-dos) ;is this correct?
971 (process-connection-type tramp-process-connection-type)
972 (args (if (tramp-file-name-host vec)
973 (list "-s" (tramp-file-name-host vec) "shell")
974 (list "shell")))
975 (p (let ((default-directory
976 (tramp-compat-temporary-file-directory)))
977 (apply 'start-process (tramp-get-connection-name vec) buf
978 (tramp-adb-program) args))))
979 (tramp-message
980 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
981 ;; Wait for initial prompt.
982 (tramp-adb-wait-for-output p)
983 (unless (eq 'run (process-status p))
984 (tramp-error vec 'file-error "Terminated!"))
985 (set-process-query-on-exit-flag p nil)
986
987 ;; Check whether the properties have been changed. If
988 ;; yes, this is a strong indication that we must expire all
989 ;; connection properties. We start again.
990 (tramp-message vec 5 "Checking system information")
991 (tramp-adb-send-command
992 vec "echo \\\"`getprop ro.product.model` `getprop ro.product.version` `getprop ro.build.version.release`\\\"")
993 (let ((old-getprop
994 (tramp-get-connection-property vec "getprop" nil))
995 (new-getprop
996 (tramp-set-connection-property
997 vec "getprop"
998 (with-current-buffer (tramp-get-connection-buffer vec)
999 ;; Read the expression.
1000 (goto-char (point-min))
1001 (read (current-buffer))))))
1002 (when (and (stringp old-getprop)
1003 (not (string-equal old-getprop new-getprop)))
1004 (tramp-cleanup vec)
1005 (tramp-message
1006 vec 3
1007 "Connection reset, because remote host changed from `%s' to `%s'"
1008 old-getprop new-getprop)
1009 (tramp-adb-maybe-open-connection vec)))))))))
1010
1011 (provide 'tramp-adb)
1012 ;;; tramp-adb.el ends here