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