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