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