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