Allow 'browse-url-emacs' to fetch URL in the selected window
[emacs.git] / lisp / net / tramp-adb.el
blob7a0ea71aee9d3608654082cc9b0a1875993fb0c3
1 ;;; tramp-adb.el --- Functions for calling Android Debug Bridge from Tramp -*- lexical-binding:t -*-
3 ;; Copyright (C) 2011-2018 Free Software Foundation, Inc.
5 ;; Author: Jürgen Hötzel <juergen@archlinux.org>
6 ;; Keywords: comm, processes
7 ;; Package: tramp
9 ;; This file is part of GNU Emacs.
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.
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.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; The Android Debug Bridge "adb" must be installed on your local
27 ;; machine. If it is not in your $PATH, add the following form into
28 ;; your .emacs:
30 ;; (setq tramp-adb-program "/path/to/adb")
32 ;; Due to security it is not possible to access non-root devices.
34 ;;; Code:
36 (require 'tramp)
38 ;;;###tramp-autoload
39 (defcustom tramp-adb-program "adb"
40 "Name of the Android Debug Bridge program."
41 :group 'tramp
42 :version "24.4"
43 :type 'string
44 :require 'tramp)
46 ;;;###tramp-autoload
47 (defcustom tramp-adb-connect-if-not-connected nil
48 "Try to run `adb connect' if provided device is not connected currently.
49 It is used for TCP/IP devices."
50 :group 'tramp
51 :version "25.1"
52 :type 'boolean
53 :require 'tramp)
55 ;;;###tramp-autoload
56 (defconst tramp-adb-method "adb"
57 "When this method name is used, forward all calls to Android Debug Bridge.")
59 ;;;###tramp-autoload
60 (defcustom tramp-adb-prompt
61 "^\\(?:[[:digit:]]*|?\\)?\\(?:[[:alnum:]\e;[]*@?[[:alnum:]]*[^#\\$]*\\)?[#\\$][[:space:]]"
62 "Regexp used as prompt in almquist shell."
63 :type 'string
64 :version "24.4"
65 :group 'tramp
66 :require 'tramp)
68 (defconst tramp-adb-ls-date-regexp
69 "[[:space:]][0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9][[:space:]][0-9][0-9]:[0-9][0-9][[:space:]]"
70 "Regexp for date format in ls output.")
72 (defconst tramp-adb-ls-toolbox-regexp
73 (concat
74 "^[[:space:]]*\\([-.[:alpha:]]+\\)" ; \1 permissions
75 "\\(?:[[:space:]]+[[:digit:]]+\\)?" ; links (Android 7/toybox)
76 "[[:space:]]*\\([^[:space:]]+\\)" ; \2 username
77 "[[:space:]]+\\([^[:space:]]+\\)" ; \3 group
78 "[[:space:]]+\\([[:digit:]]+\\)" ; \4 size
79 "[[:space:]]+\\([-[:digit:]]+[[:space:]][:[:digit:]]+\\)" ; \5 date
80 "[[:space:]]\\(.*\\)$") ; \6 filename
81 "Regexp for ls output.")
83 ;;;###tramp-autoload
84 (add-to-list 'tramp-methods
85 `(,tramp-adb-method
86 (tramp-tmpdir "/data/local/tmp")
87 (tramp-default-port 5555)))
89 ;;;###tramp-autoload
90 (add-to-list 'tramp-default-host-alist `(,tramp-adb-method nil ""))
92 ;;;###tramp-autoload
93 (eval-after-load 'tramp
94 '(tramp-set-completion-function
95 tramp-adb-method '((tramp-adb-parse-device-names ""))))
97 ;;;###tramp-autoload
98 (defconst tramp-adb-file-name-handler-alist
99 '((access-file . ignore)
100 (add-name-to-file . tramp-handle-add-name-to-file)
101 ;; `byte-compiler-base-file-name' performed by default handler.
102 ;; `copy-directory' performed by default handler.
103 (copy-file . tramp-adb-handle-copy-file)
104 (delete-directory . tramp-adb-handle-delete-directory)
105 (delete-file . tramp-adb-handle-delete-file)
106 ;; `diff-latest-backup-file' performed by default handler.
107 (directory-file-name . tramp-handle-directory-file-name)
108 (directory-files . tramp-handle-directory-files)
109 (directory-files-and-attributes
110 . tramp-adb-handle-directory-files-and-attributes)
111 (dired-compress-file . ignore)
112 (dired-uncache . tramp-handle-dired-uncache)
113 (expand-file-name . tramp-adb-handle-expand-file-name)
114 (file-accessible-directory-p . tramp-handle-file-accessible-directory-p)
115 (file-acl . ignore)
116 (file-attributes . tramp-adb-handle-file-attributes)
117 (file-directory-p . tramp-handle-file-directory-p)
118 (file-equal-p . tramp-handle-file-equal-p)
119 ;; FIXME: This is too sloppy.
120 (file-executable-p . tramp-handle-file-exists-p)
121 (file-exists-p . tramp-handle-file-exists-p)
122 (file-in-directory-p . tramp-handle-file-in-directory-p)
123 (file-local-copy . tramp-adb-handle-file-local-copy)
124 (file-modes . tramp-handle-file-modes)
125 (file-name-all-completions . tramp-adb-handle-file-name-all-completions)
126 (file-name-as-directory . tramp-handle-file-name-as-directory)
127 (file-name-case-insensitive-p . tramp-handle-file-name-case-insensitive-p)
128 (file-name-completion . tramp-handle-file-name-completion)
129 (file-name-directory . tramp-handle-file-name-directory)
130 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
131 ;; `file-name-sans-versions' performed by default handler.
132 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
133 (file-notify-add-watch . tramp-handle-file-notify-add-watch)
134 (file-notify-rm-watch . tramp-handle-file-notify-rm-watch)
135 (file-notify-valid-p . tramp-handle-file-notify-valid-p)
136 (file-ownership-preserved-p . ignore)
137 (file-readable-p . tramp-handle-file-exists-p)
138 (file-regular-p . tramp-handle-file-regular-p)
139 (file-remote-p . tramp-handle-file-remote-p)
140 (file-selinux-context . tramp-handle-file-selinux-context)
141 (file-symlink-p . tramp-handle-file-symlink-p)
142 (file-system-info . tramp-adb-handle-file-system-info)
143 (file-truename . tramp-adb-handle-file-truename)
144 (file-writable-p . tramp-adb-handle-file-writable-p)
145 (find-backup-file-name . tramp-handle-find-backup-file-name)
146 ;; `find-file-noselect' performed by default handler.
147 ;; `get-file-buffer' performed by default handler.
148 (insert-directory . tramp-handle-insert-directory)
149 (insert-file-contents . tramp-handle-insert-file-contents)
150 (load . tramp-handle-load)
151 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
152 (make-directory . tramp-adb-handle-make-directory)
153 (make-directory-internal . ignore)
154 (make-nearby-temp-file . tramp-handle-make-nearby-temp-file)
155 (make-symbolic-link . tramp-handle-make-symbolic-link)
156 (process-file . tramp-adb-handle-process-file)
157 (rename-file . tramp-adb-handle-rename-file)
158 (set-file-acl . ignore)
159 (set-file-modes . tramp-adb-handle-set-file-modes)
160 (set-file-selinux-context . ignore)
161 (set-file-times . tramp-adb-handle-set-file-times)
162 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
163 (shell-command . tramp-adb-handle-shell-command)
164 (start-file-process . tramp-adb-handle-start-file-process)
165 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
166 (temporary-file-directory . tramp-handle-temporary-file-directory)
167 (unhandled-file-name-directory . ignore)
168 (vc-registered . ignore)
169 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
170 (write-region . tramp-adb-handle-write-region))
171 "Alist of handler functions for Tramp ADB method.")
173 ;; It must be a `defsubst' in order to push the whole code into
174 ;; tramp-loaddefs.el. Otherwise, there would be recursive autoloading.
175 ;;;###tramp-autoload
176 (defsubst tramp-adb-file-name-p (filename)
177 "Check if it's a filename for ADB."
178 (let ((v (tramp-dissect-file-name filename)))
179 (string= (tramp-file-name-method v) tramp-adb-method)))
181 ;;;###tramp-autoload
182 (defun tramp-adb-file-name-handler (operation &rest args)
183 "Invoke the ADB handler for OPERATION.
184 First arg specifies the OPERATION, second arg is a list of arguments to
185 pass to the OPERATION."
186 (let ((fn (assoc operation tramp-adb-file-name-handler-alist)))
187 (if fn
188 (save-match-data (apply (cdr fn) args))
189 (tramp-run-real-handler operation args))))
191 ;;;###tramp-autoload
192 (tramp-register-foreign-file-name-handler
193 'tramp-adb-file-name-p 'tramp-adb-file-name-handler)
195 ;;;###tramp-autoload
196 (defun tramp-adb-parse-device-names (_ignore)
197 "Return a list of (nil host) tuples allowed to access."
198 (with-timeout (10)
199 (with-temp-buffer
200 ;; `call-process' does not react on timer under MS Windows.
201 ;; That's why we use `start-process'.
202 ;; We don't know yet whether we need a user or host name for the
203 ;; connection vector. We assume we don't, it will be OK in most
204 ;; of the cases. Otherwise, there might be an additional trace
205 ;; buffer, which doesn't hurt.
206 (let ((p (start-process
207 tramp-adb-program (current-buffer) tramp-adb-program "devices"))
208 (v (make-tramp-file-name :method tramp-adb-method))
209 result)
210 (tramp-message v 6 "%s" (mapconcat 'identity (process-command p) " "))
211 (process-put p 'adjust-window-size-function 'ignore)
212 (set-process-query-on-exit-flag p nil)
213 (while (process-live-p p)
214 (accept-process-output p 0.1))
215 (accept-process-output p 0.1)
216 (tramp-message v 6 "\n%s" (buffer-string))
217 (goto-char (point-min))
218 (while (search-forward-regexp "^\\(\\S-+\\)[[:space:]]+device$" nil t)
219 (push (list nil (match-string 1)) result))
221 ;; Replace ":" by "#".
222 (mapc
223 (lambda (elt)
224 (setcar
225 (cdr elt)
226 (replace-regexp-in-string
227 ":" tramp-prefix-port-format (car (cdr elt)))))
228 result)
229 result))))
231 (defun tramp-adb-handle-expand-file-name (name &optional dir)
232 "Like `expand-file-name' for Tramp files."
233 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
234 (setq dir (or dir default-directory "/"))
235 ;; Unless NAME is absolute, concat DIR and NAME.
236 (unless (file-name-absolute-p name)
237 (setq name (concat (file-name-as-directory dir) name)))
238 ;; If NAME is not a Tramp file, run the real handler.
239 (if (not (tramp-tramp-file-p name))
240 (tramp-run-real-handler 'expand-file-name (list name nil))
241 ;; Dissect NAME.
242 (with-parsed-tramp-file-name name nil
243 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
244 (setq localname (concat "/" localname)))
245 ;; Do normal `expand-file-name' (this does "/./" and "/../").
246 ;; `default-directory' is bound, because on Windows there would
247 ;; be problems with UNC shares or Cygwin mounts.
248 (let ((default-directory (tramp-compat-temporary-file-directory)))
249 (tramp-make-tramp-file-name
250 v (tramp-drop-volume-letter
251 (tramp-run-real-handler 'expand-file-name (list localname))))))))
253 (defun tramp-adb-handle-file-system-info (filename)
254 "Like `file-system-info' for Tramp files."
255 (ignore-errors
256 (with-parsed-tramp-file-name (expand-file-name filename) nil
257 (tramp-message v 5 "file system info: %s" localname)
258 (tramp-adb-send-command
259 v (format "df -k %s" (tramp-shell-quote-argument localname)))
260 (with-current-buffer (tramp-get-connection-buffer v)
261 (goto-char (point-min))
262 (forward-line)
263 (when (looking-at
264 (concat "[[:space:]]*[^[:space:]]+"
265 "[[:space:]]+\\([[:digit:]]+\\)"
266 "[[:space:]]+\\([[:digit:]]+\\)"
267 "[[:space:]]+\\([[:digit:]]+\\)"))
268 ;; The values are given as 1k numbers, so we must change
269 ;; them to number of bytes.
270 (list (* 1024 (string-to-number (concat (match-string 1) "e0")))
271 ;; The second value is the used size. We need the
272 ;; free size.
273 (* 1024 (- (string-to-number (concat (match-string 1) "e0"))
274 (string-to-number (concat (match-string 2) "e0"))))
275 (* 1024 (string-to-number (concat (match-string 3) "e0")))))))))
277 ;; This is derived from `tramp-sh-handle-file-truename'. Maybe the
278 ;; code could be shared?
279 (defun tramp-adb-handle-file-truename (filename)
280 "Like `file-truename' for Tramp files."
281 (format
282 "%s%s"
283 (with-parsed-tramp-file-name (expand-file-name filename) nil
284 (tramp-make-tramp-file-name
286 (with-tramp-file-property v localname "file-truename"
287 (let ((result nil)) ; result steps in reverse order
288 (tramp-message v 4 "Finding true name for `%s'" filename)
289 (let* ((steps (split-string localname "/" 'omit))
290 (localnamedir (tramp-run-real-handler
291 'file-name-as-directory (list localname)))
292 (is-dir (string= localname localnamedir))
293 (thisstep nil)
294 (numchase 0)
295 ;; Don't make the following value larger than
296 ;; necessary. People expect an error message in a
297 ;; timely fashion when something is wrong; otherwise
298 ;; they might think that Emacs is hung. Of course,
299 ;; correctness has to come first.
300 (numchase-limit 20)
301 symlink-target)
302 (while (and steps (< numchase numchase-limit))
303 (setq thisstep (pop steps))
304 (tramp-message
305 v 5 "Check %s"
306 (mapconcat 'identity
307 (append '("") (reverse result) (list thisstep))
308 "/"))
309 (setq symlink-target
310 (tramp-compat-file-attribute-type
311 (file-attributes
312 (tramp-make-tramp-file-name
313 v (mapconcat 'identity
314 (append
315 '("") (reverse result) (list thisstep))
316 "/")))))
317 (cond ((string= "." thisstep)
318 (tramp-message v 5 "Ignoring step `.'"))
319 ((string= ".." thisstep)
320 (tramp-message v 5 "Processing step `..'")
321 (pop result))
322 ((stringp symlink-target)
323 ;; It's a symlink, follow it.
324 (tramp-message v 5 "Follow symlink to %s" symlink-target)
325 (setq numchase (1+ numchase))
326 (when (file-name-absolute-p symlink-target)
327 (setq result nil))
328 ;; If the symlink was absolute, we'll get a string
329 ;; like "/user@host:/some/target"; extract the
330 ;; "/some/target" part from it.
331 (when (tramp-tramp-file-p symlink-target)
332 (unless (tramp-equal-remote filename symlink-target)
333 (tramp-error
334 v 'file-error
335 "Symlink target `%s' on wrong host" symlink-target))
336 (setq symlink-target localname))
337 (setq steps
338 (append (split-string symlink-target "/" 'omit)
339 steps)))
341 ;; It's a file.
342 (setq result (cons thisstep result)))))
343 (when (>= numchase numchase-limit)
344 (tramp-error
345 v 'file-error
346 "Maximum number (%d) of symlinks exceeded" numchase-limit))
347 (setq result (reverse result))
348 ;; Combine list to form string.
349 (setq result
350 (if result
351 (mapconcat 'identity (cons "" result) "/")
352 "/"))
353 (when (and is-dir (or (string= "" result)
354 (not (string= (substring result -1) "/"))))
355 (setq result (concat result "/"))))
357 (tramp-message v 4 "True name of `%s' is `%s'" localname result)
358 result))))
360 ;; Preserve trailing "/".
361 (if (string-equal (file-name-nondirectory filename) "") "/" "")))
363 (defun tramp-adb-handle-file-attributes (filename &optional id-format)
364 "Like `file-attributes' for Tramp files."
365 (unless id-format (setq id-format 'integer))
366 (ignore-errors
367 (with-parsed-tramp-file-name filename nil
368 (with-tramp-file-property
369 v localname (format "file-attributes-%s" id-format)
370 (and
371 (tramp-adb-send-command-and-check
372 v (format "%s -d -l %s"
373 (tramp-adb-get-ls-command v)
374 (tramp-shell-quote-argument localname)))
375 (with-current-buffer (tramp-get-buffer v)
376 (tramp-adb-sh-fix-ls-output)
377 (cdar (tramp-do-parse-file-attributes-with-ls v id-format))))))))
379 (defun tramp-do-parse-file-attributes-with-ls (vec &optional id-format)
380 "Parse `file-attributes' for Tramp files using the ls(1) command."
381 (with-current-buffer (tramp-get-buffer vec)
382 (goto-char (point-min))
383 (let ((file-properties nil))
384 (while (re-search-forward tramp-adb-ls-toolbox-regexp nil t)
385 (let* ((mod-string (match-string 1))
386 (is-dir (eq ?d (aref mod-string 0)))
387 (is-symlink (eq ?l (aref mod-string 0)))
388 (uid (match-string 2))
389 (gid (match-string 3))
390 (size (string-to-number (match-string 4)))
391 (date (match-string 5))
392 (name (match-string 6))
393 (symlink-target
394 (and is-symlink
395 (cadr (split-string name "\\( -> \\|\n\\)")))))
396 (push (list
397 (if is-symlink
398 (car (split-string name "\\( -> \\|\n\\)"))
399 name)
400 (or is-dir symlink-target)
401 1 ;link-count
402 ;; no way to handle numeric ids in Androids ash
403 (if (eq id-format 'integer) 0 uid)
404 (if (eq id-format 'integer) 0 gid)
405 '(0 0) ; atime
406 (date-to-time date) ; mtime
407 '(0 0) ; ctime
408 size
409 mod-string
410 ;; fake
412 (tramp-get-device vec))
413 file-properties)))
414 file-properties)))
416 (defun tramp-adb-handle-directory-files-and-attributes
417 (directory &optional full match nosort id-format)
418 "Like `directory-files-and-attributes' for Tramp files."
419 (when (file-directory-p directory)
420 (with-parsed-tramp-file-name (expand-file-name directory) nil
421 (copy-tree
422 (with-tramp-file-property
423 v localname (format "directory-files-and-attributes-%s-%s-%s-%s"
424 full match id-format nosort)
425 (with-current-buffer (tramp-get-buffer v)
426 (when (tramp-adb-send-command-and-check
427 v (format "%s -a -l %s"
428 (tramp-adb-get-ls-command v)
429 (tramp-shell-quote-argument localname)))
430 ;; We insert also filename/. and filename/.., because "ls" doesn't.
431 ;; Looks like it does include them in toybox, since Android 6.
432 (unless (re-search-backward "\\.$" nil t)
433 (narrow-to-region (point-max) (point-max))
434 (tramp-adb-send-command
435 v (format "%s -d -a -l %s %s"
436 (tramp-adb-get-ls-command v)
437 (tramp-shell-quote-argument
438 (concat (file-name-as-directory localname) "."))
439 (tramp-shell-quote-argument
440 (concat (file-name-as-directory localname) ".."))))
441 (widen)))
442 (tramp-adb-sh-fix-ls-output)
443 (let ((result (tramp-do-parse-file-attributes-with-ls
444 v (or id-format 'integer))))
445 (when full
446 (setq result
447 (mapcar
448 (lambda (x)
449 (cons (expand-file-name (car x) directory) (cdr x)))
450 result)))
451 (unless nosort
452 (setq result
453 (sort result (lambda (x y) (string< (car x) (car y))))))
454 (delq nil
455 (mapcar (lambda (x)
456 (if (or (not match) (string-match match (car x)))
458 result)))))))))
460 (defun tramp-adb-get-ls-command (vec)
461 "Determine `ls' command and its arguments."
462 (with-tramp-connection-property vec "ls"
463 (tramp-message vec 5 "Finding a suitable `ls' command")
464 (cond
465 ;; Support Android derived systems where "ls" command is provided
466 ;; by GNU Coreutils. Force "ls" to print one column and set
467 ;; time-style to imitate other "ls" flavors.
468 ((tramp-adb-send-command-and-check
469 vec "ls --time-style=long-iso /dev/null")
470 "ls -1 --time-style=long-iso")
471 ;; Can't disable coloring explicitly for toybox ls command. We
472 ;; also must force "ls" to print just one column.
473 ((tramp-adb-send-command-and-check vec "toybox") "ls -1")
474 ;; On CyanogenMod based system BusyBox is used and "ls" output
475 ;; coloring is enabled by default. So we try to disable it when
476 ;; possible.
477 ((tramp-adb-send-command-and-check vec "ls --color=never -al /dev/null")
478 "ls --color=never")
479 (t "ls"))))
481 (defun tramp-adb--gnu-switches-to-ash (switches)
482 "Almquist shell can't handle multiple arguments.
483 Convert (\"-al\") to (\"-a\" \"-l\"). Remove arguments like \"--dired\"."
484 (split-string
485 (apply 'concat
486 (mapcar (lambda (s)
487 (replace-regexp-in-string
488 "\\(.\\)" " -\\1" (replace-regexp-in-string "^-" "" s)))
489 ;; FIXME: Warning about removed switches (long and non-dash).
490 (delq nil
491 (mapcar
492 (lambda (s)
493 (and (not (string-match "\\(^--\\|^[^-]\\)" s)) s))
494 switches))))))
496 (defun tramp-adb-sh-fix-ls-output (&optional sort-by-time)
497 "Insert dummy 0 in empty size columns.
498 Androids \"ls\" command doesn't insert size column for directories:
499 Emacs dired can't find files."
500 (save-excursion
501 ;; Insert missing size.
502 (goto-char (point-min))
503 (while
504 (search-forward-regexp
505 "[[:space:]]\\([[:space:]][0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9][[:space:]]\\)" nil t)
506 (replace-match "0\\1" "\\1" nil)
507 ;; Insert missing "/".
508 (when (looking-at "[0-9][0-9]:[0-9][0-9][[:space:]]+$")
509 (end-of-line)
510 (insert "/")))
511 ;; Sort entries.
512 (let* ((lines (split-string (buffer-string) "\n" t))
513 (sorted-lines
514 (sort
515 lines
516 (if sort-by-time
517 'tramp-adb-ls-output-time-less-p
518 'tramp-adb-ls-output-name-less-p))))
519 (delete-region (point-min) (point-max))
520 (insert " " (mapconcat 'identity sorted-lines "\n ")))
521 ;; Add final newline.
522 (goto-char (point-max))
523 (unless (bolp) (insert "\n"))))
525 (defun tramp-adb-ls-output-time-less-p (a b)
526 "Sort \"ls\" output by time, descending."
527 (let (time-a time-b)
528 (string-match tramp-adb-ls-date-regexp a)
529 (setq time-a (apply 'encode-time (parse-time-string (match-string 0 a))))
530 (string-match tramp-adb-ls-date-regexp b)
531 (setq time-b (apply 'encode-time (parse-time-string (match-string 0 b))))
532 (time-less-p time-b time-a)))
534 (defun tramp-adb-ls-output-name-less-p (a b)
535 "Sort \"ls\" output by name, ascending."
536 (if (string-match directory-listing-before-filename-regexp a)
537 (let ((posa (match-end 0)))
538 (if (string-match directory-listing-before-filename-regexp b)
539 (let ((posb (match-end 0)))
540 (string-lessp (substring a posa) (substring b posb)))))))
542 (defun tramp-adb-handle-make-directory (dir &optional parents)
543 "Like `make-directory' for Tramp files."
544 (setq dir (expand-file-name dir))
545 (with-parsed-tramp-file-name dir nil
546 (when parents
547 (let ((par (expand-file-name ".." dir)))
548 (unless (file-directory-p par)
549 (make-directory par parents))))
550 (tramp-flush-file-properties v (file-name-directory localname))
551 (tramp-flush-directory-properties v localname)
552 (unless (or (tramp-adb-send-command-and-check
553 v (format "mkdir %s" (tramp-shell-quote-argument localname)))
554 (and parents (file-directory-p dir)))
555 (tramp-error v 'file-error "Couldn't make directory %s" dir))))
557 (defun tramp-adb-handle-delete-directory (directory &optional recursive _trash)
558 "Like `delete-directory' for Tramp files."
559 (setq directory (expand-file-name directory))
560 (with-parsed-tramp-file-name (file-truename directory) nil
561 (tramp-flush-file-properties v (file-name-directory localname))
562 (tramp-flush-directory-properties v localname))
563 (with-parsed-tramp-file-name directory nil
564 (tramp-flush-file-properties v (file-name-directory localname))
565 (tramp-flush-directory-properties v localname)
566 (tramp-adb-barf-unless-okay
567 v (format "%s %s"
568 (if recursive "rm -r" "rmdir")
569 (tramp-shell-quote-argument localname))
570 "Couldn't delete %s" directory)))
572 (defun tramp-adb-handle-delete-file (filename &optional _trash)
573 "Like `delete-file' for Tramp files."
574 (setq filename (expand-file-name filename))
575 (with-parsed-tramp-file-name filename nil
576 (tramp-flush-file-properties v (file-name-directory localname))
577 (tramp-flush-file-properties v localname)
578 (tramp-adb-barf-unless-okay
579 v (format "rm %s" (tramp-shell-quote-argument localname))
580 "Couldn't delete %s" filename)))
582 (defun tramp-adb-handle-file-name-all-completions (filename directory)
583 "Like `file-name-all-completions' for Tramp files."
584 (all-completions
585 filename
586 (with-parsed-tramp-file-name (expand-file-name directory) nil
587 (with-tramp-file-property v localname "file-name-all-completions"
588 (save-match-data
589 (tramp-adb-send-command
590 v (format "%s -a %s"
591 (tramp-adb-get-ls-command v)
592 (tramp-shell-quote-argument localname)))
593 (mapcar
594 (lambda (f)
595 (if (file-directory-p (expand-file-name f directory))
596 (file-name-as-directory f)
598 (with-current-buffer (tramp-get-buffer v)
599 (delete-dups
600 (append
601 ;; In older Android versions, "." and ".." are not
602 ;; included. In newer versions (toybox, since Android
603 ;; 6) they are. We fix this by `delete-dups'.
604 '("." "..")
605 (delq
607 (mapcar
608 (lambda (l) (and (not (string-match "^[[:space:]]*$" l)) l))
609 (split-string (buffer-string) "\n"))))))))))))
611 (defun tramp-adb-handle-file-local-copy (filename)
612 "Like `file-local-copy' for Tramp files."
613 (with-parsed-tramp-file-name filename nil
614 (unless (file-exists-p (file-truename filename))
615 (tramp-error
616 v tramp-file-missing
617 "Cannot make local copy of non-existing file `%s'" filename))
618 (let ((tmpfile (tramp-compat-make-temp-file filename)))
619 (with-tramp-progress-reporter
620 v 3 (format "Fetching %s to tmp file %s" filename tmpfile)
621 ;; "adb pull ..." does not always return an error code.
622 (when (or (tramp-adb-execute-adb-command
623 v "pull" (tramp-compat-file-name-unquote localname) tmpfile)
624 (not (file-exists-p tmpfile)))
625 (ignore-errors (delete-file tmpfile))
626 (tramp-error
627 v 'file-error "Cannot make local copy of file `%s'" filename))
628 (set-file-modes
629 tmpfile
630 (logior (or (file-modes filename) 0) (string-to-number "0400" 8))))
631 tmpfile)))
633 (defun tramp-adb-handle-file-writable-p (filename)
634 "Like `tramp-sh-handle-file-writable-p'.
635 But handle the case, if the \"test\" command is not available."
636 (with-parsed-tramp-file-name filename nil
637 (with-tramp-file-property v localname "file-writable-p"
638 (if (tramp-adb-find-test-command v)
639 (if (file-exists-p filename)
640 (tramp-adb-send-command-and-check
641 v (format "test -w %s" (tramp-shell-quote-argument localname)))
642 (and
643 (file-directory-p (file-name-directory filename))
644 (file-writable-p (file-name-directory filename))))
646 ;; Missing "test" command on Android < 4.
647 (let ((rw-path "/data/data"))
648 (tramp-message
650 "Not implemented yet (assuming \"/data/data\" is writable): %s"
651 localname)
652 (and (>= (length localname) (length rw-path))
653 (string= (substring localname 0 (length rw-path))
654 rw-path)))))))
656 (defun tramp-adb-handle-write-region
657 (start end filename &optional append visit lockname mustbenew)
658 "Like `write-region' for Tramp files."
659 (setq filename (expand-file-name filename))
660 (with-parsed-tramp-file-name filename nil
661 (when (and mustbenew (file-exists-p filename)
662 (or (eq mustbenew 'excl)
663 (not
664 (y-or-n-p
665 (format "File %s exists; overwrite anyway? " filename)))))
666 (tramp-error v 'file-already-exists filename))
668 ;; We must also flush the cache of the directory, because
669 ;; `file-attributes' reads the values from there.
670 (tramp-flush-file-properties v (file-name-directory localname))
671 (tramp-flush-file-properties v localname)
672 (let* ((curbuf (current-buffer))
673 (tmpfile (tramp-compat-make-temp-file filename)))
674 (when (and append (file-exists-p filename))
675 (copy-file filename tmpfile 'ok)
676 (set-file-modes
677 tmpfile
678 (logior (or (file-modes tmpfile) 0) (string-to-number "0600" 8))))
679 (tramp-run-real-handler
680 'write-region (list start end tmpfile append 'no-message lockname))
681 (with-tramp-progress-reporter
682 v 3 (format-message
683 "Moving tmp file `%s' to `%s'" tmpfile filename)
684 (unwind-protect
685 (when (tramp-adb-execute-adb-command
686 v "push" tmpfile (tramp-compat-file-name-unquote localname))
687 (tramp-error v 'file-error "Cannot write: `%s'" filename))
688 (delete-file tmpfile)))
690 (unless (equal curbuf (current-buffer))
691 (tramp-error
692 v 'file-error
693 "Buffer has changed from `%s' to `%s'" curbuf (current-buffer)))
695 ;; Set file modification time.
696 (when (or (eq visit t) (stringp visit))
697 (set-visited-file-modtime
698 (tramp-compat-file-attribute-modification-time
699 (file-attributes filename))))
701 ;; The end.
702 (when (and (null noninteractive)
703 (or (eq visit t) (null visit) (stringp visit)))
704 (tramp-message v 0 "Wrote %s" filename))
705 (run-hooks 'tramp-handle-write-region-hook))))
707 (defun tramp-adb-handle-set-file-modes (filename mode)
708 "Like `set-file-modes' for Tramp files."
709 (with-parsed-tramp-file-name filename nil
710 (tramp-flush-file-properties v (file-name-directory localname))
711 (tramp-flush-file-properties v localname)
712 (tramp-adb-send-command-and-check v (format "chmod %o %s" mode localname))))
714 (defun tramp-adb-handle-set-file-times (filename &optional time)
715 "Like `set-file-times' for Tramp files."
716 (with-parsed-tramp-file-name filename nil
717 (tramp-flush-file-properties v (file-name-directory localname))
718 (tramp-flush-file-properties v localname)
719 (let ((time (if (or (null time) (equal time '(0 0)))
720 (current-time)
721 time)))
722 (tramp-adb-send-command-and-check
723 ;; Use shell arithmetic because of Emacs integer size limit.
724 v (format "touch -t $(( %d * 65536 + %d )) %s"
725 (car time) (cadr time)
726 (tramp-shell-quote-argument localname))))))
728 (defun tramp-adb-handle-copy-file
729 (filename newname &optional ok-if-already-exists keep-date
730 _preserve-uid-gid _preserve-extended-attributes)
731 "Like `copy-file' for Tramp files.
732 PRESERVE-UID-GID and PRESERVE-EXTENDED-ATTRIBUTES are completely ignored."
733 (setq filename (expand-file-name filename)
734 newname (expand-file-name newname))
736 (if (file-directory-p filename)
737 (copy-directory filename newname keep-date t)
739 (let ((t1 (tramp-tramp-file-p filename))
740 (t2 (tramp-tramp-file-p newname)))
741 (with-parsed-tramp-file-name (if t1 filename newname) nil
742 (with-tramp-progress-reporter
743 v 0 (format "Copying %s to %s" filename newname)
745 (if (and t1 t2 (tramp-equal-remote filename newname))
746 (let ((l1 (file-remote-p filename 'localname))
747 (l2 (file-remote-p newname 'localname)))
748 (when (and (not ok-if-already-exists)
749 (file-exists-p newname))
750 (tramp-error v 'file-already-exists newname))
751 ;; We must also flush the cache of the directory,
752 ;; because `file-attributes' reads the values from
753 ;; there.
754 (tramp-flush-file-properties v (file-name-directory l2))
755 (tramp-flush-file-properties v l2)
756 ;; Short track.
757 (tramp-adb-barf-unless-okay
758 v (format
759 "cp -f %s %s"
760 (tramp-shell-quote-argument l1)
761 (tramp-shell-quote-argument l2))
762 "Error copying %s to %s" filename newname))
764 (let ((tmpfile (file-local-copy filename)))
766 (if tmpfile
767 ;; Remote filename.
768 (condition-case err
769 (rename-file tmpfile newname ok-if-already-exists)
770 ((error quit)
771 (delete-file tmpfile)
772 (signal (car err) (cdr err))))
774 ;; Remote newname.
775 (when (and (file-directory-p newname)
776 (tramp-compat-directory-name-p newname))
777 (setq newname
778 (expand-file-name
779 (file-name-nondirectory filename) newname)))
781 (with-parsed-tramp-file-name newname nil
782 (when (and (not ok-if-already-exists)
783 (file-exists-p newname))
784 (tramp-error v 'file-already-exists newname))
786 ;; We must also flush the cache of the directory,
787 ;; because `file-attributes' reads the values from
788 ;; there.
789 (tramp-flush-file-properties
790 v (file-name-directory localname))
791 (tramp-flush-file-properties v localname)
792 (when (tramp-adb-execute-adb-command
793 v "push"
794 (tramp-compat-file-name-unquote filename)
795 (tramp-compat-file-name-unquote localname))
796 (tramp-error
797 v 'file-error
798 "Cannot copy `%s' `%s'" filename newname)))))))))
800 ;; KEEP-DATE handling.
801 (when keep-date
802 (set-file-times
803 newname
804 (tramp-compat-file-attribute-modification-time
805 (file-attributes filename))))))
807 (defun tramp-adb-handle-rename-file
808 (filename newname &optional ok-if-already-exists)
809 "Like `rename-file' for Tramp files."
810 (setq filename (expand-file-name filename)
811 newname (expand-file-name newname))
813 (if (file-directory-p filename)
814 (progn
815 (copy-directory filename newname t t)
816 (delete-directory filename 'recursive))
818 (let ((t1 (tramp-tramp-file-p filename))
819 (t2 (tramp-tramp-file-p newname)))
820 (with-parsed-tramp-file-name (if t1 filename newname) nil
821 (with-tramp-progress-reporter
822 v 0 (format "Renaming %s to %s" filename newname)
824 (if (and t1 t2
825 (tramp-equal-remote filename newname)
826 (not (file-directory-p filename)))
827 (let ((l1 (file-remote-p filename 'localname))
828 (l2 (file-remote-p newname 'localname)))
829 (when (and (not ok-if-already-exists)
830 (file-exists-p newname))
831 (tramp-error v 'file-already-exists newname))
832 ;; We must also flush the cache of the directory, because
833 ;; `file-attributes' reads the values from there.
834 (tramp-flush-file-properties v (file-name-directory l1))
835 (tramp-flush-file-properties v l1)
836 (tramp-flush-file-properties v (file-name-directory l2))
837 (tramp-flush-file-properties v l2)
838 ;; Short track.
839 (tramp-adb-barf-unless-okay
840 v (format
841 "mv -f %s %s"
842 (tramp-shell-quote-argument l1)
843 (tramp-shell-quote-argument l2))
844 "Error renaming %s to %s" filename newname))
846 ;; Rename by copy.
847 (copy-file
848 filename newname ok-if-already-exists 'keep-time 'preserve-uid-gid)
849 (delete-file filename)))))))
851 (defun tramp-adb-handle-process-file
852 (program &optional infile destination display &rest args)
853 "Like `process-file' for Tramp files."
854 ;; The implementation is not complete yet.
855 (when (and (numberp destination) (zerop destination))
856 (error "Implementation does not handle immediate return"))
858 (with-parsed-tramp-file-name default-directory nil
859 (let (command input tmpinput stderr tmpstderr outbuf ret)
860 ;; Compute command.
861 (setq command (mapconcat 'tramp-shell-quote-argument
862 (cons program args) " "))
863 ;; Determine input.
864 (if (null infile)
865 (setq input "/dev/null")
866 (setq infile (expand-file-name infile))
867 (if (tramp-equal-remote default-directory infile)
868 ;; INFILE is on the same remote host.
869 (setq input (with-parsed-tramp-file-name infile nil localname))
870 ;; INFILE must be copied to remote host.
871 (setq input (tramp-make-tramp-temp-file v)
872 tmpinput (tramp-make-tramp-file-name v input))
873 (copy-file infile tmpinput t)))
874 (when input (setq command (format "%s <%s" command input)))
876 ;; Determine output.
877 (cond
878 ;; Just a buffer.
879 ((bufferp destination)
880 (setq outbuf destination))
881 ;; A buffer name.
882 ((stringp destination)
883 (setq outbuf (get-buffer-create destination)))
884 ;; (REAL-DESTINATION ERROR-DESTINATION)
885 ((consp destination)
886 ;; output.
887 (cond
888 ((bufferp (car destination))
889 (setq outbuf (car destination)))
890 ((stringp (car destination))
891 (setq outbuf (get-buffer-create (car destination))))
892 ((car destination)
893 (setq outbuf (current-buffer))))
894 ;; stderr.
895 (cond
896 ((stringp (cadr destination))
897 (setcar (cdr destination) (expand-file-name (cadr destination)))
898 (if (tramp-equal-remote default-directory (cadr destination))
899 ;; stderr is on the same remote host.
900 (setq stderr (with-parsed-tramp-file-name
901 (cadr destination) nil localname))
902 ;; stderr must be copied to remote host. The temporary
903 ;; file must be deleted after execution.
904 (setq stderr (tramp-make-tramp-temp-file v)
905 tmpstderr (tramp-make-tramp-file-name v stderr))))
906 ;; stderr to be discarded.
907 ((null (cadr destination))
908 (setq stderr "/dev/null"))))
909 ;; 't
910 (destination
911 (setq outbuf (current-buffer))))
912 (when stderr (setq command (format "%s 2>%s" command stderr)))
914 ;; Send the command. It might not return in time, so we protect
915 ;; it. Call it in a subshell, in order to preserve working
916 ;; directory.
917 (condition-case nil
918 (progn
919 (setq ret
920 (if (tramp-adb-send-command-and-check
922 (format "(cd %s; %s)"
923 (tramp-shell-quote-argument localname) command))
924 ;; Set return status accordingly.
925 0 1))
926 ;; We should add the output anyway.
927 (when outbuf
928 (with-current-buffer outbuf
929 (insert-buffer-substring (tramp-get-connection-buffer v)))
930 (when (and display (get-buffer-window outbuf t)) (redisplay))))
931 ;; When the user did interrupt, we should do it also. We use
932 ;; return code -1 as marker.
933 (quit
934 (kill-buffer (tramp-get-connection-buffer v))
935 (setq ret -1))
936 ;; Handle errors.
937 (error
938 (kill-buffer (tramp-get-connection-buffer v))
939 (setq ret 1)))
941 ;; Provide error file.
942 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
944 ;; Cleanup. We remove all file cache values for the connection,
945 ;; because the remote process could have changed them.
946 (when tmpinput (delete-file tmpinput))
948 (unless process-file-side-effects
949 (tramp-flush-directory-properties v ""))
951 ;; Return exit status.
952 (if (equal ret -1)
953 (keyboard-quit)
954 ret))))
956 (defun tramp-adb-handle-shell-command
957 (command &optional output-buffer error-buffer)
958 "Like `shell-command' for Tramp files."
959 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
960 ;; We cannot use `shell-file-name' and `shell-command-switch',
961 ;; they are variables of the local host.
962 (args (list "sh" "-c" (substring command 0 asynchronous)))
963 current-buffer-p
964 (output-buffer
965 (cond
966 ((bufferp output-buffer) output-buffer)
967 ((stringp output-buffer) (get-buffer-create output-buffer))
968 (output-buffer
969 (setq current-buffer-p t)
970 (current-buffer))
971 (t (get-buffer-create
972 (if asynchronous
973 "*Async Shell Command*"
974 "*Shell Command Output*")))))
975 (error-buffer
976 (cond
977 ((bufferp error-buffer) error-buffer)
978 ((stringp error-buffer) (get-buffer-create error-buffer))))
979 (buffer
980 (if (and (not asynchronous) error-buffer)
981 (with-parsed-tramp-file-name default-directory nil
982 (list output-buffer (tramp-make-tramp-temp-file v)))
983 output-buffer))
984 (p (get-buffer-process output-buffer)))
986 ;; Check whether there is another process running. Tramp does not
987 ;; support 2 (asynchronous) processes in parallel.
988 (when p
989 (if (yes-or-no-p "A command is running. Kill it? ")
990 (ignore-errors (kill-process p))
991 (tramp-compat-user-error p "Shell command in progress")))
993 (if current-buffer-p
994 (progn
995 (barf-if-buffer-read-only)
996 (push-mark nil t))
997 (with-current-buffer output-buffer
998 (setq buffer-read-only nil)
999 (erase-buffer)))
1001 (if (and (not current-buffer-p) (integerp asynchronous))
1002 (prog1
1003 ;; Run the process.
1004 (apply 'start-file-process "*Async Shell*" buffer args)
1005 ;; Display output.
1006 (pop-to-buffer output-buffer)
1007 (setq mode-line-process '(":%s"))
1008 (shell-mode))
1010 (prog1
1011 ;; Run the process.
1012 (apply 'process-file (car args) nil buffer nil (cdr args))
1013 ;; Insert error messages if they were separated.
1014 (when (listp buffer)
1015 (with-current-buffer error-buffer
1016 (insert-file-contents (cadr buffer)))
1017 (delete-file (cadr buffer)))
1018 (if current-buffer-p
1019 ;; This is like exchange-point-and-mark, but doesn't
1020 ;; activate the mark. It is cleaner to avoid activation,
1021 ;; even though the command loop would deactivate the mark
1022 ;; because we inserted text.
1023 (goto-char (prog1 (mark t)
1024 (set-marker (mark-marker) (point)
1025 (current-buffer))))
1026 ;; There's some output, display it.
1027 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
1028 (display-message-or-buffer output-buffer)))))))
1030 ;; We use BUFFER also as connection buffer during setup. Because of
1031 ;; this, its original contents must be saved, and restored once
1032 ;; connection has been setup.
1033 (defun tramp-adb-handle-start-file-process (name buffer program &rest args)
1034 "Like `start-file-process' for Tramp files."
1035 (with-parsed-tramp-file-name default-directory nil
1036 ;; When PROGRAM is nil, we should provide a tty. This is not
1037 ;; possible here.
1038 (unless (stringp program)
1039 (tramp-error v 'file-error "PROGRAM must be a string"))
1041 (let* ((buffer
1042 (if buffer
1043 (get-buffer-create buffer)
1044 ;; BUFFER can be nil. We use a temporary buffer.
1045 (generate-new-buffer tramp-temp-buffer-name)))
1046 (command
1047 (format "cd %s; %s"
1048 (tramp-shell-quote-argument localname)
1049 (mapconcat 'tramp-shell-quote-argument
1050 (cons program args) " ")))
1051 (tramp-process-connection-type
1052 (or (null program) tramp-process-connection-type))
1053 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
1054 (name1 name)
1055 (i 0)
1056 ;; We do not want to run timers.
1057 timer-list timer-idle-list)
1059 (while (get-process name1)
1060 ;; NAME must be unique as process name.
1061 (setq i (1+ i)
1062 name1 (format "%s<%d>" name i)))
1063 (setq name name1)
1064 ;; Set the new process properties.
1065 (tramp-set-connection-property v "process-name" name)
1066 (tramp-set-connection-property v "process-buffer" buffer)
1068 (with-current-buffer (tramp-get-connection-buffer v)
1069 (unwind-protect
1070 ;; We catch this event. Otherwise, `start-process' could
1071 ;; be called on the local host.
1072 (save-excursion
1073 (save-restriction
1074 ;; Activate narrowing in order to save BUFFER
1075 ;; contents. Clear also the modification time;
1076 ;; otherwise we might be interrupted by
1077 ;; `verify-visited-file-modtime'.
1078 (let ((buffer-undo-list t)
1079 (buffer-read-only nil)
1080 (mark (point)))
1081 (clear-visited-file-modtime)
1082 (narrow-to-region (point-max) (point-max))
1083 ;; We call `tramp-adb-maybe-open-connection', in
1084 ;; order to cleanup the prompt afterwards.
1085 (tramp-adb-maybe-open-connection v)
1086 (widen)
1087 (delete-region mark (point))
1088 (narrow-to-region (point-max) (point-max))
1089 ;; Send the command.
1090 (let ((tramp-adb-prompt (regexp-quote command)))
1091 (tramp-adb-send-command v command))
1092 (let ((p (tramp-get-connection-process v)))
1093 ;; Set query flag and process marker for this
1094 ;; process. We ignore errors, because the process
1095 ;; could have finished already.
1096 (ignore-errors
1097 (set-process-query-on-exit-flag p t)
1098 (set-marker (process-mark p) (point)))
1099 ;; Return process.
1100 p))))
1102 ;; Save exit.
1103 (if (string-match tramp-temp-buffer-name (buffer-name))
1104 (ignore-errors
1105 (set-process-buffer (tramp-get-connection-process v) nil)
1106 (kill-buffer (current-buffer)))
1107 (set-buffer-modified-p bmp))
1108 (tramp-flush-connection-property v "process-name")
1109 (tramp-flush-connection-property v "process-buffer"))))))
1111 (defun tramp-adb-get-device (vec)
1112 "Return full host name from VEC to be used in shell execution.
1113 E.g. a host name \"192.168.1.1#5555\" returns \"192.168.1.1:5555\"
1114 a host name \"R38273882DE\" returns \"R38273882DE\"."
1115 ;; Sometimes this is called before there is a connection process
1116 ;; yet. In order to work with the connection cache, we flush all
1117 ;; unwanted entries first.
1118 (tramp-flush-connection-properties nil)
1119 (with-tramp-connection-property (tramp-get-connection-process vec) "device"
1120 (let* ((host (tramp-file-name-host vec))
1121 (port (tramp-file-name-port-or-default vec))
1122 (devices (mapcar 'cadr (tramp-adb-parse-device-names nil))))
1123 (replace-regexp-in-string
1124 tramp-prefix-port-format ":"
1125 (cond ((member host devices) host)
1126 ;; This is the case when the host is connected to the default port.
1127 ((member (format "%s%s%d" host tramp-prefix-port-format port)
1128 devices)
1129 (format "%s:%d" host port))
1130 ;; An empty host name shall be mapped as well, when there
1131 ;; is exactly one entry in `devices'.
1132 ((and (zerop (length host)) (= (length devices) 1))
1133 (car devices))
1134 ;; Try to connect device.
1135 ((and tramp-adb-connect-if-not-connected
1136 (not (zerop (length host)))
1137 (not (tramp-adb-execute-adb-command
1138 vec "connect"
1139 (replace-regexp-in-string
1140 tramp-prefix-port-format ":" host))))
1141 ;; When new device connected, running other adb command (e.g.
1142 ;; adb shell) immediately will fail. To get around this
1143 ;; problem, add sleep 0.1 second here.
1144 (sleep-for 0.1)
1145 host)
1146 (t (tramp-error
1147 vec 'file-error "Could not find device %s" host)))))))
1149 (defun tramp-adb-execute-adb-command (vec &rest args)
1150 "Returns nil on success error-output on failure."
1151 (when (and (> (length (tramp-file-name-host vec)) 0)
1152 ;; The -s switch is only available for ADB device commands.
1153 (not (member (car args) '("connect" "disconnect"))))
1154 (setq args (append (list "-s" (tramp-adb-get-device vec)) args)))
1155 (with-temp-buffer
1156 (prog1
1157 (unless
1158 (zerop
1159 (apply 'tramp-call-process vec tramp-adb-program nil t nil args))
1160 (buffer-string))
1161 (tramp-message vec 6 "%s" (buffer-string)))))
1163 (defun tramp-adb-find-test-command (vec)
1164 "Checks, whether the ash has a builtin \"test\" command.
1165 This happens for Android >= 4.0."
1166 (with-tramp-connection-property vec "test"
1167 (tramp-adb-send-command-and-check vec "type test")))
1169 ;; Connection functions
1171 (defun tramp-adb-send-command (vec command)
1172 "Send the COMMAND to connection VEC."
1173 (tramp-adb-maybe-open-connection vec)
1174 (tramp-message vec 6 "%s" command)
1175 (tramp-send-string vec command)
1176 ;; fixme: Race condition
1177 (tramp-adb-wait-for-output (tramp-get-connection-process vec))
1178 (with-current-buffer (tramp-get-connection-buffer vec)
1179 (save-excursion
1180 (goto-char (point-min))
1181 ;; We can't use stty to disable echo of command.
1182 (delete-matching-lines (regexp-quote command))
1183 ;; When the local machine is W32, there are still trailing ^M.
1184 ;; There must be a better solution by setting the correct coding
1185 ;; system, but this requires changes in core Tramp.
1186 (goto-char (point-min))
1187 (while (re-search-forward "\r+$" nil t)
1188 (replace-match "" nil nil)))))
1190 (defun tramp-adb-send-command-and-check (vec command)
1191 "Run COMMAND and check its exit status.
1192 Sends `echo $?' along with the COMMAND for checking the exit
1193 status. If COMMAND is nil, just sends `echo $?'. Returns nil if
1194 the exit status is not equal 0, and t otherwise."
1195 (tramp-adb-send-command
1196 vec (if command
1197 (format "%s; echo tramp_exit_status $?" command)
1198 "echo tramp_exit_status $?"))
1199 (with-current-buffer (tramp-get-connection-buffer vec)
1200 (goto-char (point-max))
1201 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
1202 (tramp-error
1203 vec 'file-error "Couldn't find exit status of `%s'" command))
1204 (skip-chars-forward "^ ")
1205 (prog1
1206 (zerop (read (current-buffer)))
1207 (let (buffer-read-only)
1208 (delete-region (match-beginning 0) (point-max))))))
1210 (defun tramp-adb-barf-unless-okay (vec command fmt &rest args)
1211 "Run COMMAND, check exit status, throw error if exit status not okay.
1212 FMT and ARGS are passed to `error'."
1213 (unless (tramp-adb-send-command-and-check vec command)
1214 (apply 'tramp-error vec 'file-error fmt args)))
1216 (defun tramp-adb-wait-for-output (proc &optional timeout)
1217 "Wait for output from remote command."
1218 (unless (buffer-live-p (process-buffer proc))
1219 (delete-process proc)
1220 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
1221 (with-current-buffer (process-buffer proc)
1222 (if (tramp-wait-for-regexp
1223 proc timeout
1224 (tramp-get-connection-property proc "prompt" tramp-adb-prompt))
1225 (let (buffer-read-only)
1226 (goto-char (point-min))
1227 ;; ADB terminal sends "^H" sequences.
1228 (when (re-search-forward "<\b+" (point-at-eol) t)
1229 (forward-line 1)
1230 (delete-region (point-min) (point)))
1231 ;; Delete the prompt.
1232 (goto-char (point-min))
1233 (when (re-search-forward
1234 (tramp-get-connection-property proc "prompt" tramp-adb-prompt)
1235 (point-at-eol) t)
1236 (forward-line 1)
1237 (delete-region (point-min) (point)))
1238 (goto-char (point-max))
1239 (re-search-backward
1240 (tramp-get-connection-property proc "prompt" tramp-adb-prompt) nil t)
1241 (delete-region (point) (point-max)))
1242 (if timeout
1243 (tramp-error
1244 proc 'file-error
1245 "[[Remote adb prompt `%s' not found in %d secs]]"
1246 (tramp-get-connection-property proc "prompt" tramp-adb-prompt)
1247 timeout)
1248 (tramp-error
1249 proc 'file-error
1250 "[[Remote prompt `%s' not found]]"
1251 (tramp-get-connection-property proc "prompt" tramp-adb-prompt))))))
1253 (defun tramp-adb-maybe-open-connection (vec)
1254 "Maybe open a connection VEC.
1255 Does not do anything if a connection is already open, but re-opens the
1256 connection if a previous connection has died for some reason."
1257 (let* ((buf (tramp-get-connection-buffer vec))
1258 (p (get-buffer-process buf))
1259 (host (tramp-file-name-host vec))
1260 (user (tramp-file-name-user vec))
1261 (device (tramp-adb-get-device vec)))
1263 ;; Maybe we know already that "su" is not supported. We cannot
1264 ;; use a connection property, because we have not checked yet
1265 ;; whether it is still the same device.
1266 (when (and user (not (tramp-get-file-property vec "" "su-command-p" t)))
1267 (tramp-error vec 'file-error "Cannot switch to user `%s'" user))
1269 (unless (process-live-p p)
1270 (save-match-data
1271 (when (and p (processp p)) (delete-process p))
1272 (if (zerop (length device))
1273 (tramp-error vec 'file-error "Device %s not connected" host))
1274 (with-tramp-progress-reporter vec 3 "Opening adb shell connection"
1275 (let* ((coding-system-for-read 'utf-8-dos) ;is this correct?
1276 (process-connection-type tramp-process-connection-type)
1277 (args (if (> (length host) 0)
1278 (list "-s" device "shell")
1279 (list "shell")))
1280 (p (let ((default-directory
1281 (tramp-compat-temporary-file-directory)))
1282 (apply 'start-process (tramp-get-connection-name vec) buf
1283 tramp-adb-program args)))
1284 (prompt (md5 (concat (prin1-to-string process-environment)
1285 (current-time-string)))))
1286 (tramp-message
1287 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
1288 ;; Wait for initial prompt.
1289 (tramp-adb-wait-for-output p 30)
1290 (unless (process-live-p p)
1291 (tramp-error vec 'file-error "Terminated!"))
1292 (process-put p 'vector vec)
1293 (process-put p 'adjust-window-size-function 'ignore)
1294 (set-process-query-on-exit-flag p nil)
1296 ;; Change prompt.
1297 (tramp-set-connection-property
1298 p "prompt" (regexp-quote (format "///%s#$" prompt)))
1299 (tramp-adb-send-command
1300 vec (format "PS1=\"///\"\"%s\"\"#$\"" prompt))
1302 ;; Check whether the properties have been changed. If
1303 ;; yes, this is a strong indication that we must expire all
1304 ;; connection properties. We start again.
1305 (tramp-message vec 5 "Checking system information")
1306 (tramp-adb-send-command
1307 vec "echo \\\"`getprop ro.product.model` `getprop ro.product.version` `getprop ro.build.version.release`\\\"")
1308 (let ((old-getprop
1309 (tramp-get-connection-property vec "getprop" nil))
1310 (new-getprop
1311 (tramp-set-connection-property
1312 vec "getprop"
1313 (with-current-buffer (tramp-get-connection-buffer vec)
1314 ;; Read the expression.
1315 (goto-char (point-min))
1316 (read (current-buffer))))))
1317 (when (and (stringp old-getprop)
1318 (not (string-equal old-getprop new-getprop)))
1319 (tramp-message
1320 vec 3
1321 "Connection reset, because remote host changed from `%s' to `%s'"
1322 old-getprop new-getprop)
1323 (tramp-cleanup-connection vec t)
1324 (tramp-adb-maybe-open-connection vec)))
1326 ;; Change user if indicated.
1327 (when user
1328 (tramp-adb-send-command vec (format "su %s" user))
1329 (unless (tramp-adb-send-command-and-check vec nil)
1330 (delete-process p)
1331 (tramp-flush-file-property vec "" "su-command-p")
1332 (tramp-error
1333 vec 'file-error "Cannot switch to user `%s'" user)))
1335 ;; Set "remote-path" connection property. This is needed
1336 ;; for eshell.
1337 (tramp-adb-send-command vec "echo \\\"$PATH\\\"")
1338 (tramp-set-connection-property
1339 vec "remote-path"
1340 (split-string
1341 (with-current-buffer (tramp-get-connection-buffer vec)
1342 ;; Read the expression.
1343 (goto-char (point-min))
1344 (read (current-buffer)))
1345 ":" 'omit))
1347 ;; Set connection-local variables.
1348 (tramp-set-connection-local-variables vec)
1350 ;; Mark it as connected.
1351 (tramp-set-connection-property p "connected" t)))))))
1353 (add-hook 'tramp-unload-hook
1354 (lambda ()
1355 (unload-feature 'tramp-adb 'force)))
1357 (provide 'tramp-adb)
1359 ;;; tramp-adb.el ends here