tramp-adb.el 52.3 KB
Newer Older
Michael Albinus's avatar
Michael Albinus committed
1
;;; tramp-adb.el --- Functions for calling Android Debug Bridge from Tramp  -*- lexical-binding:t -*-
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 2011-2019 Free Software Foundation, Inc.
4

5
;; Author: Jürgen Hötzel <juergen@archlinux.org>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
;; Keywords: comm, processes
;; Package: tramp

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; 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/>.
23 24 25

;;; Commentary:

26 27 28
;; The Android Debug Bridge "adb" must be installed on your local
;; machine.  If it is not in your $PATH, add the following form into
;; your .emacs:
29
;;
30
;;   (setq tramp-adb-program "/path/to/adb")
31 32 33 34 35 36 37
;;
;; Due to security it is not possible to access non-root devices.

;;; Code:

(require 'tramp)

38 39 40
(defcustom tramp-adb-program "adb"
  "Name of the Android Debug Bridge program."
  :group 'tramp
41
  :version "24.4"
Michael Albinus's avatar
Michael Albinus committed
42
  :type 'string)
43

44 45 46 47 48
(defcustom tramp-adb-connect-if-not-connected nil
  "Try to run `adb connect' if provided device is not connected currently.
It is used for TCP/IP devices."
  :group 'tramp
  :version "25.1"
Michael Albinus's avatar
Michael Albinus committed
49
  :type 'boolean)
50

51 52
;;;###tramp-autoload
(defconst tramp-adb-method "adb"
53
  "When this method name is used, forward all calls to Android Debug Bridge.")
54

55
(defcustom tramp-adb-prompt
Jürgen Hötzel's avatar
Jürgen Hötzel committed
56
  "^\\(?:[[:digit:]]*|?\\)?\\(?:[[:alnum:]\e;[]*@?[[:alnum:]]*[^#\\$]*\\)?[#\\$][[:space:]]"
57
  "Regexp used as prompt in almquist shell."
58
  :type 'string
59
  :version "24.4"
Michael Albinus's avatar
Michael Albinus committed
60
  :group 'tramp)
61

62
(defconst tramp-adb-ls-date-regexp
63 64
  "[[:space:]][0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9][[:space:]][0-9][0-9]:[0-9][0-9][[:space:]]"
  "Regexp for date format in ls output.")
65

66 67
(defconst tramp-adb-ls-toolbox-regexp
  (concat
68
   "^[[:space:]]*\\([-.[:alpha:]]+\\)"	; \1 permissions
69
   "\\(?:[[:space:]]+[[:digit:]]+\\)?"	; links (Android 7/toybox)
70 71
   "[[:space:]]*\\([^[:space:]]+\\)"	; \2 username
   "[[:space:]]+\\([^[:space:]]+\\)"	; \3 group
72
   "[[:space:]]+\\([[:digit:]]+\\)"	; \4 size
73
   "[[:space:]]+\\([-[:digit:]]+[[:space:]][:[:digit:]]+\\)" ; \5 date
74 75
   "[[:space:]]\\(.*\\)$")		; \6 filename
  "Regexp for ls output.")
76

77
;;;###tramp-autoload
78 79 80 81 82
(tramp--with-startup
 (add-to-list 'tramp-methods
	      `(,tramp-adb-method
	        (tramp-tmpdir "/data/local/tmp")
                (tramp-default-port 5555)))
83

84
 (add-to-list 'tramp-default-host-alist `(,tramp-adb-method nil ""))
85

86 87
 (tramp-set-completion-function
  tramp-adb-method '((tramp-adb-parse-device-names ""))))
88 89 90

;;;###tramp-autoload
(defconst tramp-adb-file-name-handler-alist
Michael Albinus's avatar
Michael Albinus committed
91
  '((access-file . ignore)
92
    (add-name-to-file . tramp-handle-add-name-to-file)
Michael Albinus's avatar
Michael Albinus committed
93 94 95 96 97 98 99 100 101 102 103
    ;; `byte-compiler-base-file-name' performed by default handler.
    ;; `copy-directory' performed by default handler.
    (copy-file . tramp-adb-handle-copy-file)
    (delete-directory . tramp-adb-handle-delete-directory)
    (delete-file . tramp-adb-handle-delete-file)
    ;; `diff-latest-backup-file' performed by default handler.
    (directory-file-name . tramp-handle-directory-file-name)
    (directory-files . tramp-handle-directory-files)
    (directory-files-and-attributes
     . tramp-adb-handle-directory-files-and-attributes)
    (dired-compress-file . ignore)
104
    (dired-uncache . tramp-handle-dired-uncache)
105
    (exec-path . tramp-adb-handle-exec-path)
106
    (expand-file-name . tramp-handle-expand-file-name)
Michael Albinus's avatar
Michael Albinus committed
107 108 109
    (file-accessible-directory-p . tramp-handle-file-accessible-directory-p)
    (file-acl . ignore)
    (file-attributes . tramp-adb-handle-file-attributes)
Michael Albinus's avatar
Michael Albinus committed
110
    (file-directory-p . tramp-handle-file-directory-p)
111
    (file-equal-p . tramp-handle-file-equal-p)
Michael Albinus's avatar
Michael Albinus committed
112 113 114
    ;; FIXME: This is too sloppy.
    (file-executable-p . tramp-handle-file-exists-p)
    (file-exists-p . tramp-handle-file-exists-p)
115
    (file-in-directory-p . tramp-handle-file-in-directory-p)
Michael Albinus's avatar
Michael Albinus committed
116 117 118
    (file-local-copy . tramp-adb-handle-file-local-copy)
    (file-modes . tramp-handle-file-modes)
    (file-name-all-completions . tramp-adb-handle-file-name-all-completions)
119
    (file-name-as-directory . tramp-handle-file-name-as-directory)
120
    (file-name-case-insensitive-p . tramp-handle-file-name-case-insensitive-p)
121 122 123
    (file-name-completion . tramp-handle-file-name-completion)
    (file-name-directory . tramp-handle-file-name-directory)
    (file-name-nondirectory . tramp-handle-file-name-nondirectory)
Michael Albinus's avatar
Michael Albinus committed
124
    ;; `file-name-sans-versions' performed by default handler.
125
    (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
Michael Albinus's avatar
Michael Albinus committed
126 127
    (file-notify-add-watch . tramp-handle-file-notify-add-watch)
    (file-notify-rm-watch . tramp-handle-file-notify-rm-watch)
128
    (file-notify-valid-p . tramp-handle-file-notify-valid-p)
Michael Albinus's avatar
Michael Albinus committed
129 130
    (file-ownership-preserved-p . ignore)
    (file-readable-p . tramp-handle-file-exists-p)
131 132
    (file-regular-p . tramp-handle-file-regular-p)
    (file-remote-p . tramp-handle-file-remote-p)
Michael Albinus's avatar
Michael Albinus committed
133
    (file-selinux-context . tramp-handle-file-selinux-context)
134
    (file-symlink-p . tramp-handle-file-symlink-p)
135
    (file-system-info . tramp-adb-handle-file-system-info)
Michael Albinus's avatar
Michael Albinus committed
136
    (file-truename . tramp-adb-handle-file-truename)
137 138
    (file-writable-p . tramp-adb-handle-file-writable-p)
    (find-backup-file-name . tramp-handle-find-backup-file-name)
Michael Albinus's avatar
Michael Albinus committed
139
    ;; `get-file-buffer' performed by default handler.
140
    (insert-directory . tramp-handle-insert-directory)
141
    (insert-file-contents . tramp-handle-insert-file-contents)
Michael Albinus's avatar
Michael Albinus committed
142
    (load . tramp-handle-load)
143
    (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
Michael Albinus's avatar
Michael Albinus committed
144 145
    (make-directory . tramp-adb-handle-make-directory)
    (make-directory-internal . ignore)
146
    (make-nearby-temp-file . tramp-handle-make-nearby-temp-file)
147
    (make-process . tramp-adb-handle-make-process)
148
    (make-symbolic-link . tramp-handle-make-symbolic-link)
Michael Albinus's avatar
Michael Albinus committed
149 150 151
    (process-file . tramp-adb-handle-process-file)
    (rename-file . tramp-adb-handle-rename-file)
    (set-file-acl . ignore)
152
    (set-file-modes . tramp-adb-handle-set-file-modes)
Michael Albinus's avatar
Michael Albinus committed
153
    (set-file-selinux-context . ignore)
154
    (set-file-times . tramp-adb-handle-set-file-times)
Michael Albinus's avatar
Michael Albinus committed
155
    (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
156
    (shell-command . tramp-adb-handle-shell-command)
157
    (start-file-process . tramp-handle-start-file-process)
Michael Albinus's avatar
Michael Albinus committed
158
    (substitute-in-file-name . tramp-handle-substitute-in-file-name)
159
    (temporary-file-directory . tramp-handle-temporary-file-directory)
Michael Albinus's avatar
Michael Albinus committed
160
    (tramp-set-file-uid-gid . ignore)
161
    (unhandled-file-name-directory . ignore)
Michael Albinus's avatar
Michael Albinus committed
162 163 164
    (vc-registered . ignore)
    (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
    (write-region . tramp-adb-handle-write-region))
165 166
  "Alist of handler functions for Tramp ADB method.")

167 168
;; It must be a `defsubst' in order to push the whole code into
;; tramp-loaddefs.el.  Otherwise, there would be recursive autoloading.
169
;;;###tramp-autoload
170
(defsubst tramp-adb-file-name-p (filename)
171
  "Check if it's a filename for ADB."
Michael Albinus's avatar
Michael Albinus committed
172 173 174
  (and (tramp-tramp-file-p filename)
       (string= (tramp-file-name-method (tramp-dissect-file-name filename))
		tramp-adb-method)))
175 176 177 178 179 180

;;;###tramp-autoload
(defun tramp-adb-file-name-handler (operation &rest args)
  "Invoke the ADB handler for OPERATION.
First arg specifies the OPERATION, second arg is a list of arguments to
pass to the OPERATION."
181
  (let ((fn (assoc operation tramp-adb-file-name-handler-alist)))
182 183 184 185
    (if fn
	(save-match-data (apply (cdr fn) args))
      (tramp-run-real-handler operation args))))

Michael Albinus's avatar
Michael Albinus committed
186
;;;###tramp-autoload
187 188 189
(tramp--with-startup
 (tramp-register-foreign-file-name-handler
  #'tramp-adb-file-name-p #'tramp-adb-file-name-handler))
Michael Albinus's avatar
Michael Albinus committed
190

191
;;;###tramp-autoload
192
(defun tramp-adb-parse-device-names (_ignore)
193
  "Return a list of (nil host) tuples allowed to access."
194 195
  (with-timeout (10)
    (with-temp-buffer
196 197
      ;; `call-process' does not react on timer under MS Windows.
      ;; That's why we use `start-process'.
Michael Albinus's avatar
Michael Albinus committed
198 199 200 201
      ;; We don't know yet whether we need a user or host name for the
      ;; connection vector.  We assume we don't, it will be OK in most
      ;; of the cases.  Otherwise, there might be an additional trace
      ;; buffer, which doesn't hurt.
202 203
      (let ((p (start-process
		tramp-adb-program (current-buffer) tramp-adb-program "devices"))
Michael Albinus's avatar
Michael Albinus committed
204
	    (v (make-tramp-file-name :method tramp-adb-method))
205
	    result)
206
	(tramp-message v 6 "%s" (mapconcat 'identity (process-command p) " "))
207
	(process-put p 'adjust-window-size-function 'ignore)
208
	(set-process-query-on-exit-flag p nil)
209
	(while (accept-process-output p nil nil t))
210
	(tramp-message v 6 "\n%s" (buffer-string))
211 212
	(goto-char (point-min))
	(while (search-forward-regexp "^\\(\\S-+\\)[[:space:]]+device$" nil t)
Michael Albinus's avatar
Michael Albinus committed
213
	  (push (list nil (match-string 1)) result))
214 215 216 217 218 219

	;; Replace ":" by "#".
	(mapc
	 (lambda (elt)
	   (setcar
	    (cdr elt)
220
	    (replace-regexp-in-string
221 222
	     ":" tramp-prefix-port-format (car (cdr elt)))))
	 result)
223
	result))))
224

225 226 227 228 229 230 231 232 233 234 235
(defun tramp-adb-handle-file-system-info (filename)
  "Like `file-system-info' for Tramp files."
  (ignore-errors
    (with-parsed-tramp-file-name (expand-file-name filename) nil
      (tramp-message v 5 "file system info: %s" localname)
      (tramp-adb-send-command
       v (format "df -k %s" (tramp-shell-quote-argument localname)))
      (with-current-buffer (tramp-get-connection-buffer v)
	(goto-char (point-min))
	(forward-line)
	(when (looking-at
236 237 238 239 240
	       (eval-when-compile
		 (concat "[[:space:]]*[^[:space:]]+"
			 "[[:space:]]+\\([[:digit:]]+\\)"
			 "[[:space:]]+\\([[:digit:]]+\\)"
			 "[[:space:]]+\\([[:digit:]]+\\)")))
241 242
	  ;; The values are given as 1k numbers, so we must change
	  ;; them to number of bytes.
Michael Albinus's avatar
Michael Albinus committed
243
	  (list (* 1024 (string-to-number (match-string 1)))
244 245
		;; The second value is the used size.  We need the
		;; free size.
Michael Albinus's avatar
Michael Albinus committed
246 247 248
		(* 1024 (- (string-to-number (match-string 1))
			   (string-to-number (match-string 2))))
		(* 1024 (string-to-number (match-string 3)))))))))
249

250 251
;; This is derived from `tramp-sh-handle-file-truename'.  Maybe the
;; code could be shared?
252
(defun tramp-adb-handle-file-truename (filename)
253
  "Like `file-truename' for Tramp files."
254 255 256 257
   ;; Preserve trailing "/".
  (funcall
   (if (string-equal (file-name-nondirectory filename) "")
       'file-name-as-directory 'identity)
258 259
   (with-parsed-tramp-file-name (expand-file-name filename) nil
     (tramp-make-tramp-file-name
Michael Albinus's avatar
Michael Albinus committed
260
      v
261
      (with-tramp-file-property v localname "file-truename"
262 263
	(let ((result nil)			; result steps in reverse order
	      (quoted (tramp-compat-file-name-quoted-p localname)))
264
	  (tramp-message v 4 "Finding true name for `%s'" filename)
265
	  (let* ((steps (split-string localname "/" 'omit))
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
		 (localnamedir (tramp-run-real-handler
				'file-name-as-directory (list localname)))
		 (is-dir (string= localname localnamedir))
		 (thisstep nil)
		 (numchase 0)
		 ;; Don't make the following value larger than
		 ;; necessary.  People expect an error message in a
		 ;; timely fashion when something is wrong; otherwise
		 ;; they might think that Emacs is hung.  Of course,
		 ;; correctness has to come first.
		 (numchase-limit 20)
		 symlink-target)
	    (while (and steps (< numchase numchase-limit))
	      (setq thisstep (pop steps))
	      (tramp-message
	       v 5 "Check %s"
	       (mapconcat 'identity
			  (append '("") (reverse result) (list thisstep))
			  "/"))
	      (setq symlink-target
286 287 288
		    (tramp-compat-file-attribute-type
		     (file-attributes
		      (tramp-make-tramp-file-name
Michael Albinus's avatar
Michael Albinus committed
289 290 291 292
		       v (mapconcat 'identity
				    (append
				     '("") (reverse result) (list thisstep))
				    "/")))))
293
	      (cond ((string= "." thisstep)
294
		     (tramp-message v 5 "Ignoring step `.'"))
295
		    ((string= ".." thisstep)
296
		     (tramp-message v 5 "Processing step `..'")
297 298 299 300 301 302 303 304 305 306 307 308 309 310
		     (pop result))
		    ((stringp symlink-target)
		     ;; It's a symlink, follow it.
		     (tramp-message v 5 "Follow symlink to %s" symlink-target)
		     (setq numchase (1+ numchase))
		     (when (file-name-absolute-p symlink-target)
		       (setq result nil))
		     ;; If the symlink was absolute, we'll get a string
		     ;; like "/user@host:/some/target"; extract the
		     ;; "/some/target" part from it.
		     (when (tramp-tramp-file-p symlink-target)
		       (unless (tramp-equal-remote filename symlink-target)
			 (tramp-error
			  v 'file-error
311
			  "Symlink target `%s' on wrong host" symlink-target))
312 313
		       (setq symlink-target localname))
		     (setq steps
314
			   (append (split-string symlink-target "/" 'omit)
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
				   steps)))
		    (t
		     ;; It's a file.
		     (setq result (cons thisstep result)))))
	    (when (>= numchase numchase-limit)
	      (tramp-error
	       v 'file-error
	       "Maximum number (%d) of symlinks exceeded" numchase-limit))
	    (setq result (reverse result))
	    ;; Combine list to form string.
	    (setq result
		  (if result
		      (mapconcat 'identity (cons "" result) "/")
		    "/"))
	    (when (and is-dir (or (string= "" result)
				  (not (string= (substring result -1) "/"))))
	      (setq result (concat result "/"))))

333 334 335 336 337 338 339 340 341 342 343
	  ;; Detect cycle.
	  (when (and (file-symlink-p filename)
		     (string-equal result localname))
	    (tramp-error
	     v 'file-error
	     "Apparent cycle of symbolic links for %s" filename))
	  ;; If the resulting localname looks remote, we must quote it
	  ;; for security reasons.
	  (when (or quoted (file-remote-p result))
	    (let (file-name-handler-alist)
	      (setq result (tramp-compat-file-name-quote result))))
344
	  (tramp-message v 4 "True name of `%s' is `%s'" localname result)
345
	  result))))))
346 347 348 349

(defun tramp-adb-handle-file-attributes (filename &optional id-format)
  "Like `file-attributes' for Tramp files."
  (unless id-format (setq id-format 'integer))
350 351 352 353 354 355 356 357 358 359 360 361
  (ignore-errors
    (with-parsed-tramp-file-name filename nil
      (with-tramp-file-property
	  v localname (format "file-attributes-%s" id-format)
	(and
	 (tramp-adb-send-command-and-check
	  v (format "%s -d -l %s"
		    (tramp-adb-get-ls-command v)
		    (tramp-shell-quote-argument localname)))
	 (with-current-buffer (tramp-get-buffer v)
	   (tramp-adb-sh-fix-ls-output)
	   (cdar (tramp-do-parse-file-attributes-with-ls v id-format))))))))
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380

(defun tramp-do-parse-file-attributes-with-ls (vec &optional id-format)
  "Parse `file-attributes' for Tramp files using the ls(1) command."
  (with-current-buffer (tramp-get-buffer vec)
    (goto-char (point-min))
    (let ((file-properties nil))
      (while (re-search-forward tramp-adb-ls-toolbox-regexp nil t)
	(let* ((mod-string (match-string 1))
	       (is-dir (eq ?d (aref mod-string 0)))
	       (is-symlink (eq ?l (aref mod-string 0)))
	       (uid (match-string 2))
	       (gid (match-string 3))
	       (size (string-to-number (match-string 4)))
	       (date (match-string 5))
	       (name (match-string 6))
	       (symlink-target
		(and is-symlink
		     (cadr (split-string name "\\( -> \\|\n\\)")))))
	  (push (list
381 382 383
		 (if is-symlink
		     (car (split-string name "\\( -> \\|\n\\)"))
		   name)
384 385 386 387 388
		 (or is-dir symlink-target)
		 1     ;link-count
		 ;; no way to handle numeric ids in Androids ash
		 (if (eq id-format 'integer) 0 uid)
		 (if (eq id-format 'integer) 0 gid)
389
		 tramp-time-dont-know   ; atime
390
		 (date-to-time date)	; mtime
391
		 tramp-time-dont-know   ; ctime
392 393 394 395
		 size
		 mod-string
		 ;; fake
		 t 1
396
		 (tramp-get-device vec))
397 398 399 400 401 402 403 404
		file-properties)))
      file-properties)))

(defun tramp-adb-handle-directory-files-and-attributes
  (directory &optional full match nosort id-format)
  "Like `directory-files-and-attributes' for Tramp files."
  (when (file-directory-p directory)
    (with-parsed-tramp-file-name (expand-file-name directory) nil
405 406 407 408 409 410 411 412 413 414
      (copy-tree
       (with-tramp-file-property
	   v localname (format "directory-files-and-attributes-%s-%s-%s-%s"
			       full match id-format nosort)
	 (with-current-buffer (tramp-get-buffer v)
	   (when (tramp-adb-send-command-and-check
		  v (format "%s -a -l %s"
			    (tramp-adb-get-ls-command v)
			    (tramp-shell-quote-argument localname)))
	     ;; We insert also filename/. and filename/.., because "ls" doesn't.
415 416 417 418 419 420 421 422 423 424 425
	     ;; Looks like it does include them in toybox, since Android 6.
	     (unless (re-search-backward "\\.$" nil t)
	       (narrow-to-region (point-max) (point-max))
	       (tramp-adb-send-command
		v (format "%s -d -a -l %s %s"
			  (tramp-adb-get-ls-command v)
			  (tramp-shell-quote-argument
			   (concat (file-name-as-directory localname) "."))
			  (tramp-shell-quote-argument
			   (concat (file-name-as-directory localname) ".."))))
	       (widen)))
426 427 428 429 430 431 432 433 434 435 436 437 438 439
	   (tramp-adb-sh-fix-ls-output)
	   (let ((result (tramp-do-parse-file-attributes-with-ls
			  v (or id-format 'integer))))
	     (when full
	       (setq result
		     (mapcar
		      (lambda (x)
			(cons (expand-file-name (car x) directory) (cdr x)))
		      result)))
	     (unless nosort
	       (setq result
		     (sort result (lambda (x y) (string< (car x) (car y))))))
	     (delq nil
		   (mapcar (lambda (x)
440
			     (if (or (not match) (string-match-p match (car x)))
441 442
				 x))
			   result)))))))))
443

444
(defun tramp-adb-get-ls-command (vec)
Michael Albinus's avatar
Michael Albinus committed
445
  "Determine `ls' command and its arguments."
446
  (with-tramp-connection-property vec "ls"
447
    (tramp-message vec 5 "Finding a suitable `ls' command")
Jürgen Hötzel's avatar
Jürgen Hötzel committed
448
    (cond
449 450
     ;; Support Android derived systems where "ls" command is provided
     ;; by GNU Coreutils. Force "ls" to print one column and set
Paul Eggert's avatar
Paul Eggert committed
451
     ;; time-style to imitate other "ls" flavors.
452 453 454
     ((tramp-adb-send-command-and-check
       vec "ls --time-style=long-iso /dev/null")
      "ls -1 --time-style=long-iso")
455
     ;; Can't disable coloring explicitly for toybox ls command.  We
456 457
     ;; also must force "ls" to print just one column.
     ((tramp-adb-send-command-and-check vec "toybox") "ls -1")
Jürgen Hötzel's avatar
Jürgen Hötzel committed
458
     ;; On CyanogenMod based system BusyBox is used and "ls" output
459 460
     ;; coloring is enabled by default.  So we try to disable it when
     ;; possible.
Jürgen Hötzel's avatar
Jürgen Hötzel committed
461 462 463
     ((tramp-adb-send-command-and-check vec "ls --color=never -al /dev/null")
      "ls --color=never")
     (t "ls"))))
464

465
(defun tramp-adb--gnu-switches-to-ash (switches)
466 467 468 469 470
  "Almquist shell can't handle multiple arguments.
Convert (\"-al\") to (\"-a\" \"-l\").  Remove arguments like \"--dired\"."
  (split-string
   (apply 'concat
	  (mapcar (lambda (s)
471
		    (replace-regexp-in-string
472
		     "\\(.\\)" " -\\1" (replace-regexp-in-string "^-" "" s)))
473 474 475
		  ;; FIXME: Warning about removed switches (long and non-dash).
		  (delq nil
			(mapcar
476
			 (lambda (s)
477
			   (and (not (string-match-p "\\(^--\\|^[^-]\\)" s)) s))
478 479 480
			 switches))))))

(defun tramp-adb-sh-fix-ls-output (&optional sort-by-time)
481 482 483
  "Insert dummy 0 in empty size columns.
Androids \"ls\" command doesn't insert size column for directories:
Emacs dired can't find files."
484 485 486
  (save-excursion
    ;; Insert missing size.
    (goto-char (point-min))
487 488 489
    (while
	(search-forward-regexp
	 "[[:space:]]\\([[:space:]][0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9][[:space:]]\\)" nil t)
490 491
      (replace-match "0\\1" "\\1" nil)
      ;; Insert missing "/".
492
      (when (looking-at-p "[0-9][0-9]:[0-9][0-9][[:space:]]+$")
493 494 495 496 497 498 499 500 501 502 503 504 505 506
	(end-of-line)
	(insert "/")))
    ;; Sort entries.
    (let* ((lines (split-string (buffer-string) "\n" t))
	   (sorted-lines
	    (sort
	     lines
	     (if sort-by-time
		 'tramp-adb-ls-output-time-less-p
	       'tramp-adb-ls-output-name-less-p))))
      (delete-region (point-min) (point-max))
      (insert "  " (mapconcat 'identity sorted-lines "\n  ")))
    ;; Add final newline.
    (goto-char (point-max))
507
    (unless (bolp) (insert "\n"))))
508 509 510 511 512 513 514 515

(defun tramp-adb-ls-output-time-less-p (a b)
  "Sort \"ls\" output by time, descending."
  (let (time-a time-b)
    (string-match tramp-adb-ls-date-regexp a)
    (setq time-a (apply 'encode-time (parse-time-string (match-string 0 a))))
    (string-match tramp-adb-ls-date-regexp b)
    (setq time-b (apply 'encode-time (parse-time-string (match-string 0 b))))
516
    (time-less-p time-b time-a)))
517 518 519

(defun tramp-adb-ls-output-name-less-p (a b)
  "Sort \"ls\" output by name, ascending."
520 521 522 523 524
  (if (string-match directory-listing-before-filename-regexp a)
      (let ((posa (match-end 0)))
	(if (string-match directory-listing-before-filename-regexp b)
	    (let ((posb (match-end 0)))
	      (string-lessp (substring a posa) (substring b posb)))))))
525 526 527 528 529 530 531 532 533

(defun tramp-adb-handle-make-directory (dir &optional parents)
  "Like `make-directory' for Tramp files."
  (setq dir (expand-file-name dir))
  (with-parsed-tramp-file-name dir nil
    (when parents
      (let ((par (expand-file-name ".." dir)))
	(unless (file-directory-p par)
	  (make-directory par parents))))
534 535
    (tramp-flush-file-properties v (file-name-directory localname))
    (tramp-flush-directory-properties v localname)
536 537 538 539
    (unless (or (tramp-adb-send-command-and-check
		 v (format "mkdir %s" (tramp-shell-quote-argument localname)))
		(and parents (file-directory-p dir)))
      (tramp-error v 'file-error "Couldn't make directory %s" dir))))
540

Michael Albinus's avatar
Michael Albinus committed
541
(defun tramp-adb-handle-delete-directory (directory &optional recursive _trash)
542 543
  "Like `delete-directory' for Tramp files."
  (setq directory (expand-file-name directory))
544
  (with-parsed-tramp-file-name (file-truename directory) nil
545 546
    (tramp-flush-file-properties v (file-name-directory localname))
    (tramp-flush-directory-properties v localname))
547
  (with-parsed-tramp-file-name directory nil
548 549
    (tramp-flush-file-properties v (file-name-directory localname))
    (tramp-flush-directory-properties v localname)
550 551 552 553
    (tramp-adb-barf-unless-okay
     v (format "%s %s"
	       (if recursive "rm -r" "rmdir")
	       (tramp-shell-quote-argument localname))
554
     "Couldn't delete %s" directory)))
555

556
(defun tramp-adb-handle-delete-file (filename &optional _trash)
557 558 559
  "Like `delete-file' for Tramp files."
  (setq filename (expand-file-name filename))
  (with-parsed-tramp-file-name filename nil
560 561
    (tramp-flush-file-properties v (file-name-directory localname))
    (tramp-flush-file-properties v localname)
562 563
    (tramp-adb-barf-unless-okay
     v (format "rm %s" (tramp-shell-quote-argument localname))
564
     "Couldn't delete %s" filename)))
565 566 567 568 569

(defun tramp-adb-handle-file-name-all-completions (filename directory)
  "Like `file-name-all-completions' for Tramp files."
  (all-completions
   filename
Michael Albinus's avatar
Michael Albinus committed
570
   (with-parsed-tramp-file-name (expand-file-name directory) nil
571
     (with-tramp-file-property v localname "file-name-all-completions"
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
       (tramp-adb-send-command
	v (format "%s -a %s"
		  (tramp-adb-get-ls-command v)
		  (tramp-shell-quote-argument localname)))
       (mapcar
	(lambda (f)
	  (if (file-directory-p (expand-file-name f directory))
	      (file-name-as-directory f)
	    f))
	(with-current-buffer (tramp-get-buffer v)
	  (delete-dups
	   (append
	    ;; In older Android versions, "." and ".." are not
	    ;; included.  In newer versions (toybox, since Android 6)
	    ;; they are.  We fix this by `delete-dups'.
	    '("." "..")
	    (delq
	     nil
	     (mapcar
591
	      (lambda (l) (and (not (string-match-p "^[[:space:]]*$" l)) l))
592
	      (split-string (buffer-string) "\n")))))))))))
593 594 595 596 597 598

(defun tramp-adb-handle-file-local-copy (filename)
  "Like `file-local-copy' for Tramp files."
  (with-parsed-tramp-file-name filename nil
    (unless (file-exists-p (file-truename filename))
      (tramp-error
Michael Albinus's avatar
Michael Albinus committed
599
       v tramp-file-missing
600
       "Cannot make local copy of non-existing file `%s'" filename))
601 602 603
    (let ((tmpfile (tramp-compat-make-temp-file filename)))
      (with-tramp-progress-reporter
	  v 3 (format "Fetching %s to tmp file %s" filename tmpfile)
604
	;; "adb pull ..." does not always return an error code.
605 606
	(when (or (tramp-adb-execute-adb-command
		   v "pull" (tramp-compat-file-name-unquote localname) tmpfile)
607 608
		  (not (file-exists-p tmpfile)))
	  (ignore-errors (delete-file tmpfile))
609
	  (tramp-error
610
	   v 'file-error "Cannot make local copy of file `%s'" filename))
611
	(set-file-modes tmpfile (logior (or (file-modes filename) 0) #o0400)))
612 613 614
      tmpfile)))

(defun tramp-adb-handle-file-writable-p (filename)
615
  "Like `file-writable-p' for Tramp files.
616 617 618 619 620
But handle the case, if the \"test\" command is not available."
  (with-parsed-tramp-file-name filename nil
    (with-tramp-file-property v localname "file-writable-p"
      (if (tramp-adb-find-test-command v)
	  (if (file-exists-p filename)
621 622
	      (tramp-adb-send-command-and-check
	       v (format "test -w %s" (tramp-shell-quote-argument localname)))
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
	    (and
	     (file-directory-p (file-name-directory filename))
	     (file-writable-p (file-name-directory filename))))

	;; Missing "test" command on Android < 4.
       (let ((rw-path "/data/data"))
	 (tramp-message
	  v 5
	  "Not implemented yet (assuming \"/data/data\" is writable): %s"
	  localname)
	 (and (>= (length localname) (length rw-path))
	      (string= (substring localname 0 (length rw-path))
		       rw-path)))))))

(defun tramp-adb-handle-write-region
638
  (start end filename &optional append visit lockname mustbenew)
639 640 641
  "Like `write-region' for Tramp files."
  (setq filename (expand-file-name filename))
  (with-parsed-tramp-file-name filename nil
642 643 644 645 646 647 648
    (when (and mustbenew (file-exists-p filename)
	       (or (eq mustbenew 'excl)
		   (not
		    (y-or-n-p
		     (format "File %s exists; overwrite anyway? " filename)))))
      (tramp-error v 'file-already-exists filename))

649 650
    ;; We must also flush the cache of the directory, because
    ;; `file-attributes' reads the values from there.
651 652
    (tramp-flush-file-properties v (file-name-directory localname))
    (tramp-flush-file-properties v localname)
653 654
    (let* ((curbuf (current-buffer))
	   (tmpfile (tramp-compat-make-temp-file filename)))
655 656
      (when (and append (file-exists-p filename))
	(copy-file filename tmpfile 'ok)
657
	(set-file-modes tmpfile (logior (or (file-modes tmpfile) 0) #o0600)))
658
      (tramp-run-real-handler
659
       'write-region (list start end tmpfile append 'no-message lockname))
660
      (with-tramp-progress-reporter
661
        v 3 (format-message
662
             "Moving tmp file `%s' to `%s'" tmpfile filename)
663
	(unwind-protect
664 665
	    (when (tramp-adb-execute-adb-command
		   v "push" tmpfile (tramp-compat-file-name-unquote localname))
666
	      (tramp-error v 'file-error "Cannot write: `%s'" filename))
667 668 669 670 671
	  (delete-file tmpfile)))

      (unless (equal curbuf (current-buffer))
	(tramp-error
	 v 'file-error
672 673 674 675 676 677 678 679 680 681 682 683 684
	 "Buffer has changed from `%s' to `%s'" curbuf (current-buffer)))

      ;; Set file modification time.
      (when (or (eq visit t) (stringp visit))
	(set-visited-file-modtime
	 (tramp-compat-file-attribute-modification-time
	  (file-attributes filename))))

      ;; The end.
      (when (and (null noninteractive)
		 (or (eq visit t) (null visit) (stringp visit)))
	(tramp-message v 0 "Wrote %s" filename))
      (run-hooks 'tramp-handle-write-region-hook))))
685 686 687 688

(defun tramp-adb-handle-set-file-modes (filename mode)
  "Like `set-file-modes' for Tramp files."
  (with-parsed-tramp-file-name filename nil
689 690
    (tramp-flush-file-properties v (file-name-directory localname))
    (tramp-flush-file-properties v localname)
691
    (tramp-adb-send-command-and-check v (format "chmod %o %s" mode localname))))
692

693 694 695
(defun tramp-adb-handle-set-file-times (filename &optional time)
  "Like `set-file-times' for Tramp files."
  (with-parsed-tramp-file-name filename nil
696 697
    (tramp-flush-file-properties v (file-name-directory localname))
    (tramp-flush-file-properties v localname)
698 699 700
    (let ((time (if (or (null time)
			(tramp-compat-time-equal-p time tramp-time-doesnt-exist)
			(tramp-compat-time-equal-p time tramp-time-dont-know))
701 702
		    (current-time)
		  time)))
703 704
      (tramp-adb-send-command-and-check
       ;; Use shell arithmetic because of Emacs integer size limit.
705 706 707 708
       v (format "touch -t $(( %d * 65536 + %d )) %s"
		 (car time) (cadr time)
		 (tramp-shell-quote-argument localname))))))

709 710
(defun tramp-adb-handle-copy-file
  (filename newname &optional ok-if-already-exists keep-date
711
   _preserve-uid-gid _preserve-extended-attributes)
712
  "Like `copy-file' for Tramp files.
713
PRESERVE-UID-GID and PRESERVE-EXTENDED-ATTRIBUTES are completely ignored."
714 715 716 717
  (setq filename (expand-file-name filename)
	newname (expand-file-name newname))

  (if (file-directory-p filename)
718
      (copy-directory filename newname keep-date t)
719 720 721 722 723 724 725 726

    (let ((t1 (tramp-tramp-file-p filename))
	  (t2 (tramp-tramp-file-p newname)))
      (with-parsed-tramp-file-name (if t1 filename newname) nil
	(with-tramp-progress-reporter
	    v 0 (format "Copying %s to %s" filename newname)

	  (if (and t1 t2 (tramp-equal-remote filename newname))
727 728
	      (let ((l1 (tramp-compat-file-local-name filename))
		    (l2 (tramp-compat-file-local-name newname)))
729 730 731 732 733 734
		(when (and (not ok-if-already-exists)
			   (file-exists-p newname))
		  (tramp-error v 'file-already-exists newname))
		;; We must also flush the cache of the directory,
		;; because `file-attributes' reads the values from
		;; there.
735 736
		(tramp-flush-file-properties v (file-name-directory l2))
		(tramp-flush-file-properties v l2)
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
		;; Short track.
		(tramp-adb-barf-unless-okay
		 v (format
		    "cp -f %s %s"
		    (tramp-shell-quote-argument l1)
		    (tramp-shell-quote-argument l2))
		 "Error copying %s to %s" filename newname))

	    (let ((tmpfile (file-local-copy filename)))

	      (if tmpfile
		  ;; Remote filename.
		  (condition-case err
		      (rename-file tmpfile newname ok-if-already-exists)
		    ((error quit)
		     (delete-file tmpfile)
		     (signal (car err) (cdr err))))

		;; Remote newname.
756
		(when (and (file-directory-p newname)
757
			   (tramp-compat-directory-name-p newname))
758 759 760 761 762 763 764 765 766 767 768 769
		  (setq newname
			(expand-file-name
			 (file-name-nondirectory filename) newname)))

		(with-parsed-tramp-file-name newname nil
		  (when (and (not ok-if-already-exists)
			     (file-exists-p newname))
		    (tramp-error v 'file-already-exists newname))

		  ;; We must also flush the cache of the directory,
		  ;; because `file-attributes' reads the values from
		  ;; there.
770 771 772
		  (tramp-flush-file-properties
		   v (file-name-directory localname))
		  (tramp-flush-file-properties v localname)
773 774 775 776 777 778 779
		  (when (tramp-adb-execute-adb-command
			 v "push"
			 (tramp-compat-file-name-unquote filename)
			 (tramp-compat-file-name-unquote localname))
		    (tramp-error
		     v 'file-error
		     "Cannot copy `%s' `%s'" filename newname)))))))))
780 781 782

    ;; KEEP-DATE handling.
    (when keep-date
783 784 785 786
      (set-file-times
       newname
       (tramp-compat-file-attribute-modification-time
	(file-attributes filename))))))
787 788 789 790 791 792 793

(defun tramp-adb-handle-rename-file
  (filename newname &optional ok-if-already-exists)
  "Like `rename-file' for Tramp files."
  (setq filename (expand-file-name filename)
	newname (expand-file-name newname))

Michael Albinus's avatar
Michael Albinus committed
794 795 796 797 798 799 800 801 802 803 804 805 806 807
  (if (file-directory-p filename)
      (progn
	(copy-directory filename newname t t)
	(delete-directory filename 'recursive))

    (let ((t1 (tramp-tramp-file-p filename))
	  (t2 (tramp-tramp-file-p newname)))
      (with-parsed-tramp-file-name (if t1 filename newname) nil
	(with-tramp-progress-reporter
	    v 0 (format "Renaming %s to %s" filename newname)

	  (if (and t1 t2
		   (tramp-equal-remote filename newname)
		   (not (file-directory-p filename)))
808 809
	      (let ((l1 (tramp-compat-file-local-name filename))
		    (l2 (tramp-compat-file-local-name newname)))
Michael Albinus's avatar
Michael Albinus committed
810 811 812 813 814
		(when (and (not ok-if-already-exists)
			   (file-exists-p newname))
		  (tramp-error v 'file-already-exists newname))
		;; We must also flush the cache of the directory, because
		;; `file-attributes' reads the values from there.
815 816 817 818
		(tramp-flush-file-properties v (file-name-directory l1))
		(tramp-flush-file-properties v l1)
		(tramp-flush-file-properties v (file-name-directory l2))
		(tramp-flush-file-properties v l2)
Michael Albinus's avatar
Michael Albinus committed
819 820 821 822 823 824 825 826 827 828 829 830
		;; Short track.
		(tramp-adb-barf-unless-okay
		 v (format
		    "mv -f %s %s"
		    (tramp-shell-quote-argument l1)
		    (tramp-shell-quote-argument l2))
		 "Error renaming %s to %s" filename newname))

	    ;; Rename by copy.
	    (copy-file
	     filename newname ok-if-already-exists 'keep-time 'preserve-uid-gid)
	    (delete-file filename)))))))
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852

(defun tramp-adb-handle-process-file
  (program &optional infile destination display &rest args)
  "Like `process-file' for Tramp files."
  ;; The implementation is not complete yet.
  (when (and (numberp destination) (zerop destination))
    (error "Implementation does not handle immediate return"))

  (with-parsed-tramp-file-name default-directory nil
    (let (command input tmpinput stderr tmpstderr outbuf ret)
      ;; Compute command.
      (setq command (mapconcat 'tramp-shell-quote-argument
			       (cons program args) " "))
      ;; Determine input.
      (if (null infile)
	  (setq input "/dev/null")
	(setq infile (expand-file-name infile))
	(if (tramp-equal-remote default-directory infile)
	    ;; INFILE is on the same remote host.
	    (setq input (with-parsed-tramp-file-name infile nil localname))
	  ;; INFILE must be copied to remote host.
	  (setq input (tramp-make-tramp-temp-file v)
Michael Albinus's avatar
Michael Albinus committed
853
		tmpinput (tramp-make-tramp-file-name v input))
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
	  (copy-file infile tmpinput t)))
      (when input (setq command (format "%s <%s" command input)))

      ;; Determine output.
      (cond
       ;; Just a buffer.
       ((bufferp destination)
	(setq outbuf destination))
       ;; A buffer name.
       ((stringp destination)
	(setq outbuf (get-buffer-create destination)))
       ;; (REAL-DESTINATION ERROR-DESTINATION)
       ((consp destination)
	;; output.
	(cond
	 ((bufferp (car destination))
	  (setq outbuf (car destination)))
	 ((stringp (car destination))
	  (setq outbuf (get-buffer-create (car destination))))
	 ((car destination)
	  (setq outbuf (current-buffer))))
	;; stderr.
	(cond
	 ((stringp (cadr destination))
	  (setcar (cdr destination) (expand-file-name (cadr destination)))
	  (if (tramp-equal-remote default-directory (cadr destination))
	      ;; stderr is on the same remote host.
	      (setq stderr (with-parsed-tramp-file-name
			       (cadr destination) nil localname))
	    ;; stderr must be copied to remote host.  The temporary
	    ;; file must be deleted after execution.
	    (setq stderr (tramp-make-tramp-temp-file v)
Michael Albinus's avatar
Michael Albinus committed
886
		  tmpstderr (tramp-make-tramp-file-name v stderr))))
887 888 889 890 891 892 893 894 895 896 897 898 899
	 ;; stderr to be discarded.
	 ((null (cadr destination))
	  (setq stderr "/dev/null"))))
       ;; 't
       (destination
	(setq outbuf (current-buffer))))
      (when stderr (setq command (format "%s 2>%s" command stderr)))

      ;; Send the command.  It might not return in time, so we protect
      ;; it.  Call it in a subshell, in order to preserve working
      ;; directory.
      (condition-case nil
	  (progn
900 901 902 903 904 905 906
	    (setq ret
		  (if (tramp-adb-send-command-and-check
		       v
		       (format "(cd %s; %s)"
			       (tramp-shell-quote-argument localname) command))
		      ;; Set return status accordingly.
		      0 1))
907
	    ;; We should add the output anyway.
908 909 910
	    (when outbuf
	      (with-current-buffer outbuf
		(insert-buffer-substring (tramp-get-connection-buffer v)))
911
	      (when (and display (get-buffer-window outbuf t)) (redisplay))))
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
	;; When the user did interrupt, we should do it also.  We use
	;; return code -1 as marker.
	(quit
	 (kill-buffer (tramp-get-connection-buffer v))
	 (setq ret -1))
	;; Handle errors.
	(error
	 (kill-buffer (tramp-get-connection-buffer v))
	 (setq ret 1)))

      ;; Provide error file.
      (when tmpstderr (rename-file tmpstderr (cadr destination) t))

      ;; Cleanup.  We remove all file cache values for the connection,
      ;; because the remote process could have changed them.
      (when tmpinput (delete-file tmpinput))

929
      (unless process-file-side-effects
930
        (tramp-flush-directory-properties v ""))
931 932 933 934 935 936 937 938 939

      ;; Return exit status.
      (if (equal ret -1)
	  (keyboard-quit)
	ret))))

(defun tramp-adb-handle-shell-command
  (command &optional output-buffer error-buffer)
  "Like `shell-command' for Tramp files."
940
  (let* ((asynchronous (string-match-p "[ \t]*&[ \t]*\\'" command))
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
	 ;; We cannot use `shell-file-name' and `shell-command-switch',
	 ;; they are variables of the local host.
	 (args (list "sh" "-c" (substring command 0 asynchronous)))
	 current-buffer-p
	 (output-buffer
	  (cond
	   ((bufferp output-buffer) output-buffer)
	   ((stringp output-buffer) (get-buffer-create output-buffer))
	   (output-buffer
	    (setq current-buffer-p t)
	    (current-buffer))
	   (t (get-buffer-create
	       (if asynchronous
		   "*Async Shell Command*"
		 "*Shell Command Output*")))))
	 (error-buffer
	  (cond
	   ((bufferp error-buffer) error-buffer)
	   ((stringp error-buffer) (get-buffer-create error-buffer))))
	 (buffer
	  (if (and (not asynchronous) error-buffer)
	      (with-parsed-tramp-file-name default-directory nil
		(list output-buffer (tramp-make-tramp-temp-file v)))
	    output-buffer))
	 (p (get-buffer-process output-buffer)))

    ;; Check whether there is another process running.  Tramp does not
    ;; support 2 (asynchronous) processes in parallel.
    (when p
      (if (yes-or-no-p "A command is running.  Kill it? ")
	  (ignore-errors (kill-process p))
Michael Albinus's avatar
Michael Albinus committed
972
	(tramp-user-error p "Shell command in progress")))
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008

    (if current-buffer-p
	(progn
	  (barf-if-buffer-read-only)
	  (push-mark nil t))
      (with-current-buffer output-buffer
	(setq buffer-read-only nil)
	(erase-buffer)))

    (if (and (not current-buffer-p) (integerp asynchronous))
	(prog1
	    ;; Run the process.
	    (apply 'start-file-process "*Async Shell*" buffer args)
	  ;; Display output.
	  (pop-to-buffer output-buffer)
	  (setq mode-line-process '(":%s"))
	  (shell-mode))

      (prog1
	  ;; Run the process.
	  (apply 'process-file (car args) nil buffer nil (cdr args))
	;; Insert error messages if they were separated.
	(when (listp buffer)
	  (with-current-buffer error-buffer
	    (insert-file-contents (cadr buffer)))
	  (delete-file (cadr buffer)))
	(if current-buffer-p
	    ;; This is like exchange-point-and-mark, but doesn't
	    ;; activate the mark.  It is cleaner to avoid activation,
	    ;; even though the command loop would deactivate the mark
	    ;; because we inserted text.
	    (goto-char (prog1 (mark t)
			 (set-marker (mark-marker) (point)
				     (current-buffer))))
	  ;; There's some output, display it.
	  (when (with-current-buffer output-buffer (> (point-max) (point-min)))
1009
	    (display-message-or-buffer output-buffer)))))))
1010

1011
;; We use BUFFER also as connection buffer during setup.  Because of
1012 1013
;; this, its original contents must be saved, and restored once
;; connection has been setup.
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
(defun tramp-adb-handle-make-process (&rest args)
  "Like `make-process' for Tramp files."
  (when args
    (with-parsed-tramp-file-name (expand-file-name default-directory) nil
      (let ((name (plist-get args :name))
	    (buffer (plist-get args :buffer))
	    (command (plist-get args :command))
	    (coding (plist-get args :coding))
	    (noquery (plist-get args :noquery))
	    (stop (plist-get args :stop))
	    (connection-type (plist-get args :connection-type))
	    (filter (plist-get args :filter))
	    (sentinel (plist-get args :sentinel))
	    (stderr (plist-get args :stderr)))
	(unless (stringp name)
	  (signal 'wrong-type-argument (list 'stringp name)))
	(unless (or (null buffer) (bufferp buffer) (stringp buffer))
	  (signal 'wrong-type-argument (list 'stringp buffer)))
	(unless (consp command)
	  (signal 'wrong-type-argument (list 'consp command)))
	(unless (or (null coding)
		    (and (symbolp coding) (memq coding coding-system-list))
		    (and (consp coding)
			 (memq (car coding) coding-system-list)
			 (memq (cdr coding) coding-system-list)))
	  (signal 'wrong-type-argument (list 'symbolp coding)))
	(unless (or (null connection-type) (memq connection-type '(pipe pty)))
	  (signal 'wrong-type-argument (list 'symbolp connection-type)))
	(unless (or (null filter) (functionp filter))
	  (signal 'wrong-type-argument (list 'functionp filter)))
	(unless (or (null sentinel) (functionp sentinel))
	  (signal 'wrong-type-argument (list 'functionp sentinel)))
	(unless (or (null stderr) (bufferp stderr) (stringp stderr))
	  (signal 'wrong-type-argument (list 'stringp stderr)))

	(let* ((buffer
		(if buffer
		    (get-buffer-create buffer)
		  ;; BUFFER can be nil.  We use a temporary buffer.
		  (generate-new-buffer tramp-temp-buffer-name)))
	       (program (car command))
	       (args (cdr command))
	       (command
		(format "cd %s; %s"
			(tramp-shell-quote-argument localname)
			(mapconcat 'tramp-shell-quote-argument
				   (cons program args) " ")))
	       (tramp-process-connection-type
		(or (null program) tramp-process-connection-type))
	       (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
	       (name1 name)
	       (i 0)
	       ;; We do not want to run timers.
	       timer-list timer-idle-list)

	  (while (get-process name1)
	    ;; NAME must be unique as process name.
	    (setq i (1+ i)
		  name1 (format "%s<%d>" name i)))
	  (setq name name1)
	  ;; Set the new process properties.
	  (tramp-set-connection-property v "process-name" name)
	  (tramp-set-connection-property v "process-buffer" buffer)

	  (with-current-buffer (tramp-get-connection-buffer v)
	    (unwind-protect
		;; We catch this event.  Otherwise, `make-process'
		;; could be called on the local host.
		(save-excursion
		  (save-restriction
		    ;; Activate narrowing in order to save BUFFER
		    ;; contents.  Clear also the modification time;
		    ;; otherwise we might be interrupted by
		    ;; `verify-visited-file-modtime'.
		    (let ((buffer-undo-list t)
1089
			  (inhibit-read-only t)
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
			  (mark (point)))
		      (clear-visited-file-modtime)
		      (narrow-to-region (point-max) (point-max))
		      ;; We call `tramp-adb-maybe-open-connection', in
		      ;; order to cleanup the prompt afterwards.
		      (tramp-adb-maybe-open-connection v)
		      (widen)
		      (delete-region mark (point))
		      (narrow-to-region (point-max) (point-max))
		      ;; Send the command.
		      (let ((tramp-adb-prompt (regexp-quote command)))
			(tramp-adb-send-command v command))
		      (let ((p (tramp-get-connection-process v)))
			;; Stop process if indicated.
			(when stop
			  (stop-process p))
			;; Set sentinel and filter.
			(when sentinel
			  (set-process-sentinel p sentinel))
			(when filter
			  (set-process-filter p filter))
			;; Set query flag and process marker for this
			;; process.  We ignore errors, because the
			;; process could have finished already.
			(ignore-errors
			  (set-process-query-on-exit-flag p (null noquery))
			  (set-marker (process-mark p) (point)))
			;; Return process.
			p))))

	      ;; Save exit.
	      (if (string-match-p tramp-temp-buffer-name (buffer-name))
		  (ignore-errors
		    (set-process-buffer (tramp-get-connection-process v) nil)
		    (kill-buffer (current-buffer)))
		(set-buffer-modified-p bmp))
	      (tramp-flush-connection-property v "process-name")
	      (tramp-flush-connection-property v "process-buffer"))))))))
1128

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
(defun tramp-adb-handle-exec-path ()
  "Like `exec-path' for Tramp files."
  (append
   (with-parsed-tramp-file-name default-directory nil
     (with-tramp-connection-property v "remote-path"
       (tramp-adb-send-command v "echo \\\"$PATH\\\"")
       (split-string
	(with-current-buffer (tramp-get-connection-buffer v)
	  ;; Read the expression.
	  (goto-char (point-min))
	  (read (current-buffer)))
	":" 'omit)))
   ;; The equivalent to `exec-directory'.
1142
   `(,(tramp-compat-file-local-name default-directory))))
1143

1144
(defun tramp-adb-get-device (vec)
Paul Eggert's avatar
Paul Eggert committed
1145
  "Return full host name from VEC to be used in shell execution.
1146 1147 1148 1149 1150
E.g. a host name \"192.168.1.1#5555\" returns \"192.168.1.1:5555\"
     a host name \"R38273882DE\" returns \"R38273882DE\"."
  ;; Sometimes this is called before there is a connection process
  ;; yet.  In order to work with the connection cache, we flush all
  ;; unwanted entries first.
1151
  (tramp-flush-connection-properties nil)
1152
  (with-tramp-connection-property (tramp-get-connection-process vec) "device"
Michael Albinus's avatar
Michael Albinus committed
1153
    (let* ((host (tramp-file-name-host vec))
1154
	   (port (tramp-file-name-port-or-default vec))
1155
	   (devices (mapcar 'cadr (tramp-adb-parse-device-names nil))))
1156
      (replace-regexp-in-string
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
       tramp-prefix-port-format ":"
       (cond ((member host devices) host)
	     ;; This is the case when the host is connected to the default port.
	     ((member (format "%s%s%d" host tramp-prefix-port-format port)
		      devices)
	      (format "%s:%d" host port))
	     ;; An empty host name shall be mapped as well, when there
	     ;; is exactly one entry in `devices'.
	     ((and (zerop (length host)) (= (length devices) 1))
	      (car devices))
	     ;; Try to connect device.
	     ((and tramp-adb-connect-if-not-connected
		   (not (zerop (length host)))
		   (not (tramp-adb-execute-adb-command
                         vec "connect"
1172
                         (replace-regexp-in-string
1173 1174 1175 1176 1177 1178 1179 1180
                          tramp-prefix-port-format ":" host))))
	      ;; When new device connected, running other adb command (e.g.
	      ;; adb shell) immediately will fail.  To get around this
	      ;; problem, add sleep 0.1 second here.
	      (sleep-for 0.1)
	      host)
	     (t (tramp-error
		 vec 'file-error "Could not find device %s" host)))))))
1181 1182 1183

(defun tramp-adb-execute-adb-command (vec &rest args)
  "Returns nil on success error-output on failure."
Zhongwei Yao's avatar