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