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