tramp-sh.el 194 KB
Newer Older
1 2
;;; tramp-sh.el --- Tramp access functions for (s)sh-like connections

3
;; Copyright (C) 1998-2011 Free Software Foundation, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

;; (copyright statements below in code to be updated with the above notice)

;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
;;         Michael Albinus <michael.albinus@gmx.de>
;; 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
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Code:

29
(eval-when-compile (require 'cl))	; ignore-errors
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
(require 'tramp)
(require 'shell)

;; Pacify byte-compiler.  The function is needed on XEmacs only.  I'm
;; not sure at all that this is the right way to do it, but let's hope
;; it works for now, and wait for a guru to point out the Right Way to
;; achieve this.
;;(eval-when-compile
;;  (unless (fboundp 'dired-insert-set-properties)
;;    (fset 'dired-insert-set-properties 'ignore)))
;; Gerd suggests this:
(eval-when-compile (require 'dired))
;; Note that dired is required at run-time, too, when it is needed.
;; It is only needed on XEmacs for the function
;; `dired-insert-set-properties'.

(defcustom tramp-inline-compress-start-size 4096
  "*The minimum size of compressing where inline transfer.
When inline transfer, compress transfered data of file
whose size is this value or above (up to `tramp-copy-size-limit').
If it is nil, no compression at all will be applied."
  :group 'tramp
  :type '(choice (const nil) integer))

(defcustom tramp-copy-size-limit 10240
  "*The maximum file size where inline copying is preferred over an out-of-the-band copy.
If it is nil, inline out-of-the-band copy will be used without a check."
  :group 'tramp
  :type '(choice (const nil) integer))

;;;###tramp-autoload
(defcustom tramp-terminal-type "dumb"
  "*Value of TERM environment variable for logging in to remote host.
Because Tramp wants to parse the output of the remote shell, it is easily
confused by ANSI color escape sequences and suchlike.  Often, shell init
files conditionalize this setup based on the TERM environment variable."
  :group 'tramp
  :type 'string)

69
;; ksh on OpenBSD 4.5 requires, that $PS1 contains a `#' character for
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
;; root users.  It uses the `$' character for other users.  In order
;; to guarantee a proper prompt, we use "#$" for the prompt.

(defvar tramp-end-of-output
  (format
   "///%s#$"
   (md5 (concat (prin1-to-string process-environment) (current-time-string))))
  "String used to recognize end of output.
The '$' character at the end is quoted; the string cannot be
detected as prompt when being sent on echoing hosts, therefore.")

;;;###tramp-autoload
(defconst tramp-initial-end-of-output "#$ "
  "Prompt when establishing a connection.")

;; Initialize `tramp-methods' with the supported methods.
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("rcp"
    (tramp-login-program        "rsh")
    (tramp-login-args           (("%h") ("-l" "%u")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-copy-program         "rcp")
93
    (tramp-copy-args            (("%k" "-p") ("-r")))
94 95 96 97 98 99 100 101 102
    (tramp-copy-keep-date       t)
    (tramp-copy-recursive       t)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("remcp"
    (tramp-login-program        "remsh")
    (tramp-login-args           (("%h") ("-l" "%u")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-copy-program         "rcp")
103
    (tramp-copy-args            (("%k" "-p")))
104 105
    (tramp-copy-keep-date       t)))
;;;###tramp-autoload
106
(add-to-list 'tramp-methods
Michael Albinus's avatar
Michael Albinus committed
107 108
 '("scp"
   (tramp-login-program        "ssh")
109 110 111 112
   (tramp-login-args           (("-l" "%u") ("-p" "%p")	("-e" "none") ("%h")))
   (tramp-async-args           (("-q")))
   (tramp-remote-sh            "/bin/sh")
   (tramp-copy-program         "scp")
113
   (tramp-copy-args            (("-P" "%p") ("%k" "-p")	("-q") ("-r")))
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
   (tramp-copy-keep-date       t)
   (tramp-copy-recursive       t)
   (tramp-gw-args              (("-o" "GlobalKnownHostsFile=/dev/null")
				("-o" "UserKnownHostsFile=/dev/null")
				("-o" "StrictHostKeyChecking=no")))
   (tramp-default-port         22)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("scp1"
    (tramp-login-program        "ssh")
    (tramp-login-args           (("-l" "%u") ("-p" "%p")
				 ("-1") ("-e" "none") ("%h")))
    (tramp-async-args           (("-q")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-copy-program         "scp")
129
    (tramp-copy-args            (("-1") ("-P" "%p") ("%k" "-p") ("-q") ("-r")))
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    (tramp-copy-keep-date       t)
    (tramp-copy-recursive       t)
    (tramp-gw-args              (("-o" "GlobalKnownHostsFile=/dev/null")
				 ("-o" "UserKnownHostsFile=/dev/null")
				 ("-o" "StrictHostKeyChecking=no")))
    (tramp-default-port         22)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("scp2"
    (tramp-login-program        "ssh")
    (tramp-login-args           (("-l" "%u") ("-p" "%p")
				 ("-2") ("-e" "none") ("%h")))
    (tramp-async-args           (("-q")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-copy-program         "scp")
145
    (tramp-copy-args            (("-2") ("-P" "%p") ("%k" "-p") ("-q") ("-r")))
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    (tramp-copy-keep-date       t)
    (tramp-copy-recursive       t)
    (tramp-gw-args              (("-o" "GlobalKnownHostsFile=/dev/null")
				 ("-o" "UserKnownHostsFile=/dev/null")
				 ("-o" "StrictHostKeyChecking=no")))
    (tramp-default-port         22)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("scpc"
    (tramp-login-program        "ssh")
    (tramp-login-args           (("-l" "%u") ("-p" "%p")
				 ("-o" "ControlPath=%t.%%r@%%h:%%p")
				 ("-o" "ControlMaster=yes")
				 ("-e" "none") ("%h")))
    (tramp-async-args           (("-q")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-copy-program         "scp")
163
    (tramp-copy-args            (("-P" "%p") ("%k" "-p") ("-q") ("-r")
164 165 166
				 ("-o" "ControlPath=%t.%%r@%%h:%%p")
				 ("-o" "ControlMaster=auto")))
    (tramp-copy-keep-date       t)
167
    (tramp-copy-recursive       t)
168 169 170 171 172 173 174 175 176 177 178 179 180 181
    (tramp-gw-args              (("-o" "GlobalKnownHostsFile=/dev/null")
				 ("-o" "UserKnownHostsFile=/dev/null")
				 ("-o" "StrictHostKeyChecking=no")))
    (tramp-default-port         22)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("scpx"
    (tramp-login-program        "ssh")
    (tramp-login-args           (("-l" "%u") ("-p" "%p")
				 ("-e" "none") ("-t" "-t")
				 ("%h") ("/bin/sh")))
    (tramp-async-args           (("-q")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-copy-program         "scp")
182
    (tramp-copy-args            (("-P" "%p") ("%k" "-p") ("-q") ("-r")))
183
    (tramp-copy-keep-date       t)
184
    (tramp-copy-recursive       t)
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    (tramp-gw-args              (("-o" "GlobalKnownHostsFile=/dev/null")
				 ("-o" "UserKnownHostsFile=/dev/null")
				 ("-o" "StrictHostKeyChecking=no")))
    (tramp-default-port         22)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("sftp"
    (tramp-login-program        "ssh")
    (tramp-login-args           (("-l" "%u") ("-p" "%p") ("-e" "none") ("%h")))
    (tramp-async-args           (("-q")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-copy-program         "sftp")))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("rsync"
    (tramp-login-program        "ssh")
    (tramp-login-args           (("-l" "%u") ("-p" "%p") ("-e" "none") ("%h")))
    (tramp-async-args           (("-q")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-copy-program         "rsync")
205
    (tramp-copy-args            (("-e" "ssh") ("%k" "-t") ("-r")))
206 207 208 209 210 211 212 213 214 215 216 217 218 219
    (tramp-copy-keep-date       t)
    (tramp-copy-keep-tmpfile    t)
    (tramp-copy-recursive       t)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  `("rsyncc"
    (tramp-login-program        "ssh")
    (tramp-login-args           (("-l" "%u") ("-p" "%p")
				 ("-o" "ControlPath=%t.%%r@%%h:%%p")
				 ("-o" "ControlMaster=yes")
				 ("-e" "none") ("%h")))
    (tramp-async-args           (("-q")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-copy-program         "rsync")
220
    (tramp-copy-args            (("%k" "-t") ("-r")))
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    (tramp-copy-env             (("RSYNC_RSH")
				 (,(concat
				    "ssh"
				    " -o ControlPath=%t.%%r@%%h:%%p"
				    " -o ControlMaster=auto"))))
    (tramp-copy-keep-date       t)
    (tramp-copy-keep-tmpfile    t)
    (tramp-copy-recursive       t)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("rsh"
    (tramp-login-program        "rsh")
    (tramp-login-args           (("%h") ("-l" "%u")))
    (tramp-remote-sh            "/bin/sh")))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("remsh"
    (tramp-login-program        "remsh")
    (tramp-login-args           (("%h") ("-l" "%u")))
    (tramp-remote-sh            "/bin/sh")))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("ssh"
    (tramp-login-program        "ssh")
    (tramp-login-args           (("-l" "%u") ("-p" "%p") ("-e" "none") ("%h")))
    (tramp-async-args           (("-q")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-gw-args              (("-o" "GlobalKnownHostsFile=/dev/null")
				 ("-o" "UserKnownHostsFile=/dev/null")
				 ("-o" "StrictHostKeyChecking=no")))
    (tramp-default-port         22)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("ssh1"
    (tramp-login-program        "ssh")
    (tramp-login-args           (("-l" "%u") ("-p" "%p")
				 ("-1") ("-e" "none") ("%h")))
    (tramp-async-args           (("-q")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-gw-args              (("-o" "GlobalKnownHostsFile=/dev/null")
				 ("-o" "UserKnownHostsFile=/dev/null")
				 ("-o" "StrictHostKeyChecking=no")))
    (tramp-default-port         22)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("ssh2"
    (tramp-login-program        "ssh")
    (tramp-login-args           (("-l" "%u") ("-p" "%p")
				 ("-2") ("-e" "none") ("%h")))
    (tramp-async-args           (("-q")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-gw-args              (("-o" "GlobalKnownHostsFile=/dev/null")
				 ("-o" "UserKnownHostsFile=/dev/null")
				 ("-o" "StrictHostKeyChecking=no")))
    (tramp-default-port         22)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("sshx"
    (tramp-login-program        "ssh")
    (tramp-login-args           (("-l" "%u") ("-p" "%p")
				 ("-e" "none") ("-t" "-t")
				 ("%h") ("/bin/sh")))
    (tramp-async-args           (("-q")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-gw-args              (("-o" "GlobalKnownHostsFile=/dev/null")
				 ("-o" "UserKnownHostsFile=/dev/null")
				 ("-o" "StrictHostKeyChecking=no")))
    (tramp-default-port         22)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("telnet"
    (tramp-login-program        "telnet")
    (tramp-login-args           (("%h") ("%p")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-default-port         23)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("su"
    (tramp-login-program        "su")
    (tramp-login-args           (("-") ("%u")))
    (tramp-remote-sh            "/bin/sh")))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("sudo"
    (tramp-login-program        "sudo")
    (tramp-login-args           (("-u" "%u") ("-s") ("-H") ("-p" "Password:")))
    (tramp-remote-sh            "/bin/sh")))
;;;###tramp-autoload
309 310 311 312 313 314
(add-to-list 'tramp-methods
  '("ksu"
    (tramp-login-program        "ksu")
    (tramp-login-args           (("%u") ("-q")))
    (tramp-remote-sh            "/bin/sh")))
;;;###tramp-autoload
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
(add-to-list 'tramp-methods
  '("krlogin"
    (tramp-login-program        "krlogin")
    (tramp-login-args           (("%h") ("-l" "%u") ("-x")))
    (tramp-remote-sh            "/bin/sh")))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("plink"
    (tramp-login-program        "plink")
    (tramp-login-args           (("-l" "%u") ("-P" "%p") ("-ssh") ("%h")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-password-end-of-line "xy") ;see docstring for "xy"
    (tramp-default-port         22)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("plink1"
    (tramp-login-program        "plink")
    (tramp-login-args           (("-l" "%u") ("-P" "%p") ("-1" "-ssh") ("%h")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-password-end-of-line "xy") ;see docstring for "xy"
    (tramp-default-port         22)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  `("plinkx"
    (tramp-login-program        "plink")
    ;; ("%h") must be a single element, see
    ;; `tramp-compute-multi-hops'.
    (tramp-login-args           (("-load") ("%h") ("-t")
				 (,(format
				    "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
				    tramp-terminal-type
				    tramp-initial-end-of-output))
				 ("/bin/sh")))
    (tramp-remote-sh            "/bin/sh")))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("pscp"
    (tramp-login-program        "plink")
    (tramp-login-args           (("-l" "%u") ("-P" "%p") ("-ssh") ("%h")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-copy-program         "pscp")
356 357
    (tramp-copy-args            (("-P" "%p") ("-scp") ("%k" "-p")
				 ("-q") ("-r")))
358
    (tramp-copy-keep-date       t)
359
    (tramp-copy-recursive       t)
360 361 362 363 364 365 366 367 368
    (tramp-password-end-of-line "xy") ;see docstring for "xy"
    (tramp-default-port         22)))
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("psftp"
    (tramp-login-program        "plink")
    (tramp-login-args           (("-l" "%u") ("-P" "%p") ("-ssh") ("%h")))
    (tramp-remote-sh            "/bin/sh")
    (tramp-copy-program         "pscp")
369 370
    (tramp-copy-args            (("-P" "%p") ("-sftp") ("%k" "-p")
				 ("-q") ("-r")))
371
    (tramp-copy-keep-date       t)
372
    (tramp-copy-recursive       t)
373 374 375 376 377 378 379 380
    (tramp-password-end-of-line "xy"))) ;see docstring for "xy"
;;;###tramp-autoload
(add-to-list 'tramp-methods
  '("fcp"
    (tramp-login-program        "fsh")
    (tramp-login-args           (("%h") ("-l" "%u") ("sh" "-i")))
    (tramp-remote-sh            "/bin/sh -i")
    (tramp-copy-program         "fcp")
381
    (tramp-copy-args            (("%k" "-p")))
382 383
    (tramp-copy-keep-date       t)))

384
;;;###tramp-autoload
385 386 387
(add-to-list 'tramp-default-method-alist
	     `(,tramp-local-host-regexp "\\`root\\'" "su"))

388
;;;###tramp-autoload
389
(add-to-list 'tramp-default-user-alist
390 391
	     `(,(concat "\\`" (regexp-opt '("su" "sudo" "ksu")) "\\'")
	       nil "root"))
392
;; Do not add "ssh" based methods, otherwise ~/.ssh/config would be ignored.
393
;;;###tramp-autoload
394
(add-to-list 'tramp-default-user-alist
395 396 397
	     `(,(concat
		 "\\`"
		 (regexp-opt
398 399
		  '("rcp" "remcp" "rsh" "telnet" "krlogin"
		    "plink" "plink1" "pscp" "psftp" "fcp"))
400
		 "\\'")
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
	       nil ,(user-login-name)))

(defconst tramp-completion-function-alist-rsh
  '((tramp-parse-rhosts "/etc/hosts.equiv")
    (tramp-parse-rhosts "~/.rhosts"))
  "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")

(defconst tramp-completion-function-alist-ssh
  '((tramp-parse-rhosts      "/etc/hosts.equiv")
    (tramp-parse-rhosts      "/etc/shosts.equiv")
    (tramp-parse-shosts      "/etc/ssh_known_hosts")
    (tramp-parse-sconfig     "/etc/ssh_config")
    (tramp-parse-shostkeys   "/etc/ssh2/hostkeys")
    (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
    (tramp-parse-rhosts      "~/.rhosts")
    (tramp-parse-rhosts      "~/.shosts")
    (tramp-parse-shosts      "~/.ssh/known_hosts")
    (tramp-parse-sconfig     "~/.ssh/config")
    (tramp-parse-shostkeys   "~/.ssh2/hostkeys")
    (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
  "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")

(defconst tramp-completion-function-alist-telnet
  '((tramp-parse-hosts "/etc/hosts"))
  "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")

(defconst tramp-completion-function-alist-su
  '((tramp-parse-passwd "/etc/passwd"))
  "Default list of (FUNCTION FILE) pairs to be examined for su methods.")

(defconst tramp-completion-function-alist-putty
  '((tramp-parse-putty
     "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
  "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")

(tramp-set-completion-function "rcp" tramp-completion-function-alist-rsh)
(tramp-set-completion-function "remcp" tramp-completion-function-alist-rsh)
(tramp-set-completion-function "scp" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "scp1" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "scp2" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "scpc" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "scpx" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "sftp" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "rsync" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "rsyncc" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "rsh" tramp-completion-function-alist-rsh)
(tramp-set-completion-function "remsh" tramp-completion-function-alist-rsh)
(tramp-set-completion-function "ssh" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "ssh1" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "ssh2" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "ssh1_old" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "ssh2_old" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "sshx" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "telnet" tramp-completion-function-alist-telnet)
(tramp-set-completion-function "su" tramp-completion-function-alist-su)
(tramp-set-completion-function "sudo" tramp-completion-function-alist-su)
457
(tramp-set-completion-function "ksu" tramp-completion-function-alist-su)
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
(tramp-set-completion-function "krlogin" tramp-completion-function-alist-rsh)
(tramp-set-completion-function "plink" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "plink1" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "plinkx" tramp-completion-function-alist-putty)
(tramp-set-completion-function "pscp" tramp-completion-function-alist-ssh)
(tramp-set-completion-function "fcp" tramp-completion-function-alist-ssh)

;; "getconf PATH" yields:
;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
;; GNU/Linux (Debian, Suse): /bin:/usr/bin
;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
;; IRIX64: /usr/bin
(defcustom tramp-remote-path
  '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
    "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
    "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
  "*List of directories to search for executables on remote host.
For every remote host, this variable will be set buffer local,
keeping the list of existing directories on that host.

You can use `~' in this list, but when searching for a shell which groks
tilde expansion, all directory names starting with `~' will be ignored.

`Default Directories' represent the list of directories given by
the command \"getconf PATH\".  It is recommended to use this
entry on top of this list, because these are the default
directories for POSIX compatible commands.

`Private Directories' are the settings of the $PATH environment,
as given in your `~/.profile'."
  :group 'tramp
  :type '(repeat (choice
		  (const :tag "Default Directories" tramp-default-remote-path)
		  (const :tag "Private Directories" tramp-own-remote-path)
		  (string :tag "Directory"))))

(defcustom tramp-remote-process-environment
  `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
    ,(format "TERM=%s" tramp-terminal-type)
    "EMACS=t" ;; Deprecated.
    ,(format "INSIDE_EMACS='%s,tramp:%s'" emacs-version tramp-version)
    "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
    "autocorrect=" "correct=")

  "*List of environment variables to be set on the remote host.

Each element should be a string of the form ENVVARNAME=VALUE.  An
entry ENVVARNAME= diables the corresponding environment variable,
which might have been set in the init files like ~/.profile.

Special handling is applied to the PATH environment, which should
not be set here. Instead of, it should be set via `tramp-remote-path'."
  :group 'tramp
  :type '(repeat string))

(defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
  "*Alist specifying extra arguments to pass to the remote shell.
Entries are (REGEXP . ARGS) where REGEXP is a regular expression
matching the shell file name and ARGS is a string specifying the
arguments.

This variable is only used when Tramp needs to start up another shell
for tilde expansion.  The extra arguments should typically prevent the
shell from reading its init file."
  :group 'tramp
  ;; This might be the wrong way to test whether the widget type
  ;; `alist' is available.  Who knows the right way to test it?
  :type (if (get 'alist 'widget-type)
	    '(alist :key-type string :value-type string)
	  '(repeat (cons string string))))

(defconst tramp-actions-before-shell
  '((tramp-login-prompt-regexp tramp-action-login)
    (tramp-password-prompt-regexp tramp-action-password)
    (tramp-wrong-passwd-regexp tramp-action-permission-denied)
    (shell-prompt-pattern tramp-action-succeed)
    (tramp-shell-prompt-pattern tramp-action-succeed)
    (tramp-yesno-prompt-regexp tramp-action-yesno)
    (tramp-yn-prompt-regexp tramp-action-yn)
    (tramp-terminal-prompt-regexp tramp-action-terminal)
    (tramp-process-alive-regexp tramp-action-process-alive))
  "List of pattern/action pairs.
Whenever a pattern matches, the corresponding action is performed.
Each item looks like (PATTERN ACTION).

The PATTERN should be a symbol, a variable.  The value of this
variable gives the regular expression to search for.  Note that the
regexp must match at the end of the buffer, \"\\'\" is implicitly
appended to it.

The ACTION should also be a symbol, but a function.  When the
corresponding PATTERN matches, the ACTION function is called.")

(defconst tramp-actions-copy-out-of-band
  '((tramp-password-prompt-regexp tramp-action-password)
    (tramp-wrong-passwd-regexp tramp-action-permission-denied)
    (tramp-copy-failed-regexp tramp-action-permission-denied)
    (tramp-process-alive-regexp tramp-action-out-of-band))
  "List of pattern/action pairs.
This list is used for copying/renaming with out-of-band methods.

See `tramp-actions-before-shell' for more info.")

(defconst tramp-uudecode
  "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
cat /tmp/tramp.$$
rm -f /tmp/tramp.$$"
  "Shell function to implement `uudecode' to standard output.
Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
for this or `uudecode -p', but some systems don't, and for them
we have this shell function.")

(defconst tramp-perl-file-truename
  "%s -e '
use File::Spec;
use Cwd \"realpath\";

sub recursive {
    my ($volume, @dirs) = @_;
    my $real = realpath(File::Spec->catpath(
                   $volume, File::Spec->catdir(@dirs), \"\"));
    if ($real) {
        my ($vol, $dir) = File::Spec->splitpath($real, 1);
        return ($vol, File::Spec->splitdir($dir));
    }
    else {
        my $last = pop(@dirs);
        ($volume, @dirs) = recursive($volume, @dirs);
        push(@dirs, $last);
        return ($volume, @dirs);
    }
}

$result = realpath($ARGV[0]);
if (!$result) {
    my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
    ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));

    $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
}

if ($ARGV[0] =~ /\\/$/) {
    $result = $result . \"/\";
}

print \"\\\"$result\\\"\\n\";
' \"$1\" 2>/dev/null"
  "Perl script to produce output suitable for use with `file-truename'
on the remote file system.
Escape sequence %s is replaced with name of Perl binary.
This string is passed to `format', so percent characters need to be doubled.")

(defconst tramp-perl-file-name-all-completions
  "%s -e 'sub case {
 my $str = shift;
 if ($ARGV[2]) {
  return lc($str);
 }
 else {
  return $str;
 }
}
opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
@files = readdir(d); closedir(d);
foreach $f (@files) {
 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
  if (-d \"$ARGV[0]/$f\") {
   print \"$f/\\n\";
  }
  else {
   print \"$f\\n\";
  }
 }
}
print \"ok\\n\"
' \"$1\" \"$2\" \"$3\" 2>/dev/null"
  "Perl script to produce output suitable for use with
`file-name-all-completions' on the remote file system.  Escape
sequence %s is replaced with name of Perl binary.  This string is
passed to `format', so percent characters need to be doubled.")

;; Perl script to implement `file-attributes' in a Lisp `read'able
;; output.  If you are hacking on this, note that you get *no* output
;; unless this spits out a complete line, including the '\n' at the
;; end.
;; The device number is returned as "-1", because there will be a virtual
645
;; device number set in `tramp-sh-handle-file-attributes'.
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
(defconst tramp-perl-file-attributes
  "%s -e '
@stat = lstat($ARGV[0]);
if (!@stat) {
    print \"nil\\n\";
    exit 0;
}
if (($stat[2] & 0170000) == 0120000)
{
    $type = readlink($ARGV[0]);
    $type = \"\\\"$type\\\"\";
}
elsif (($stat[2] & 0170000) == 040000)
{
    $type = \"t\";
}
else
{
    $type = \"nil\"
};
$uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
$gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
printf(
    \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
    $type,
    $stat[3],
    $uid,
    $gid,
    $stat[8] >> 16 & 0xffff,
    $stat[8] & 0xffff,
    $stat[9] >> 16 & 0xffff,
    $stat[9] & 0xffff,
    $stat[10] >> 16 & 0xffff,
    $stat[10] & 0xffff,
    $stat[7],
    $stat[2],
    $stat[1] >> 16 & 0xffff,
    $stat[1] & 0xffff
);' \"$1\" \"$2\" 2>/dev/null"
  "Perl script to produce output suitable for use with `file-attributes'
on the remote file system.
Escape sequence %s is replaced with name of Perl binary.
This string is passed to `format', so percent characters need to be doubled.")

(defconst tramp-perl-directory-files-and-attributes
  "%s -e '
chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
@list = readdir(DIR);
closedir(DIR);
$n = scalar(@list);
printf(\"(\\n\");
for($i = 0; $i < $n; $i++)
{
    $filename = $list[$i];
    @stat = lstat($filename);
    if (($stat[2] & 0170000) == 0120000)
    {
        $type = readlink($filename);
        $type = \"\\\"$type\\\"\";
    }
    elsif (($stat[2] & 0170000) == 040000)
    {
        $type = \"t\";
    }
    else
    {
        $type = \"nil\"
    };
    $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
    $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
    printf(
        \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
        $filename,
        $type,
        $stat[3],
        $uid,
        $gid,
        $stat[8] >> 16 & 0xffff,
        $stat[8] & 0xffff,
        $stat[9] >> 16 & 0xffff,
        $stat[9] & 0xffff,
        $stat[10] >> 16 & 0xffff,
        $stat[10] & 0xffff,
        $stat[7],
        $stat[2],
        $stat[1] >> 16 & 0xffff,
        $stat[1] & 0xffff,
        $stat[0] >> 16 & 0xffff,
        $stat[0] & 0xffff);
}
printf(\")\\n\");' \"$1\" \"$2\" 2>/dev/null"
  "Perl script implementing `directory-files-attributes' as Lisp `read'able
output.
Escape sequence %s is replaced with name of Perl binary.
This string is passed to `format', so percent characters need to be doubled.")

;; These two use base64 encoding.
(defconst tramp-perl-encode-with-module
  "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
  "Perl program to use for encoding a file.
Escape sequence %s is replaced with name of Perl binary.
This string is passed to `format', so percent characters need to be doubled.
This implementation requires the MIME::Base64 Perl module to be installed
on the remote host.")

(defconst tramp-perl-decode-with-module
  "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
  "Perl program to use for decoding a file.
Escape sequence %s is replaced with name of Perl binary.
This string is passed to `format', so percent characters need to be doubled.
This implementation requires the MIME::Base64 Perl module to be installed
on the remote host.")

(defconst tramp-perl-encode
  "%s -e '
# This script contributed by Juanma Barranquero <lektu@terra.es>.
763
# Copyright (C) 2002-2011 Free Software Foundation, Inc.
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
use strict;

my %%trans = do {
    my $i = 0;
    map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
      split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
};

binmode(\\*STDIN);

# We read in chunks of 54 bytes, to generate output lines
# of 72 chars (plus end of line)
$/ = \\54;

while (my $data = <STDIN>) {
    my $pad = q();

    # Only for the last chunk, and only if did not fill the last three-byte packet
    if (eof) {
        my $mod = length($data) %% 3;
        $pad = q(=) x (3 - $mod) if $mod;
    }

    # Not the fastest method, but it is simple: unpack to binary string, split
    # by groups of 6 bits and convert back from binary to byte; then map into
    # the translation table
    print
      join q(),
        map($trans{$_},
            (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
              $pad,
                qq(\\n);
}' 2>/dev/null"
  "Perl program to use for encoding a file.
Escape sequence %s is replaced with name of Perl binary.
This string is passed to `format', so percent characters need to be doubled.")

(defconst tramp-perl-decode
  "%s -e '
# This script contributed by Juanma Barranquero <lektu@terra.es>.
804
# Copyright (C) 2002-2011 Free Software Foundation, Inc.
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 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 886 887 888 889
use strict;

my %%trans = do {
    my $i = 0;
    map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
      split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
};

my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;

binmode(\\*STDOUT);

# We are going to accumulate into $pending to accept any line length
# (we do not check they are <= 76 chars as the RFC says)
my $pending = q();

while (my $data = <STDIN>) {
    chomp $data;

    # If we find one or two =, we have reached the end and
    # any following data is to be discarded
    my $finished = $data =~ s/(==?).*/$1/;
    $pending .= $data;

    my $len = length($pending);
    my $chunk = substr($pending, 0, $len & ~3);
    $pending = substr($pending, $len & ~3 + 1);

    # Easy method: translate from chars to (pregenerated) six-bit packets, join,
    # split in 8-bit chunks and convert back to char.
    print join q(),
      map $bytes{$_},
        ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);

    last if $finished;
}' 2>/dev/null"
  "Perl program to use for decoding a file.
Escape sequence %s is replaced with name of Perl binary.
This string is passed to `format', so percent characters need to be doubled.")

(defconst tramp-vc-registered-read-file-names
  "echo \"(\"
while read file; do
    if %s \"$file\"; then
	echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
    else
	echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
    fi
    if %s \"$file\"; then
	echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
    else
	echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
    fi
done
echo \")\""
  "Script to check existence of VC related files.
It must be send formatted with two strings; the tests for file
existence, and file readability.  Input shall be read via
here-document, otherwise the command could exceed maximum length
of command line.")

(defconst tramp-file-mode-type-map
  '((0  . "-")  ; Normal file (SVID-v2 and XPG2)
    (1  . "p")  ; fifo
    (2  . "c")  ; character device
    (3  . "m")  ; multiplexed character device (v7)
    (4  . "d")  ; directory
    (5  . "?")  ; Named special file (XENIX)
    (6  . "b")  ; block device
    (7  . "?")  ; multiplexed block device (v7)
    (8  . "-")  ; regular file
    (9  . "n")  ; network special file (HP-UX)
    (10 . "l")  ; symlink
    (11 . "?")  ; ACL shadow inode (Solaris, not userspace)
    (12 . "s")  ; socket
    (13 . "D")  ; door special (Solaris)
    (14 . "w")) ; whiteout (BSD)
  "A list of file types returned from the `stat' system call.
This is used to map a mode number to a permission string.")

;; New handlers should be added here.  The following operations can be
;; handled using the normal primitives: file-name-sans-versions,
;; get-file-buffer.
(defconst tramp-sh-file-name-handler-alist
  '((load . tramp-handle-load)
890
    (make-symbolic-link . tramp-sh-handle-make-symbolic-link)
891 892 893
    (file-name-as-directory . tramp-handle-file-name-as-directory)
    (file-name-directory . tramp-handle-file-name-directory)
    (file-name-nondirectory . tramp-handle-file-name-nondirectory)
894 895 896 897 898
    (file-truename . tramp-sh-handle-file-truename)
    (file-exists-p . tramp-sh-handle-file-exists-p)
    (file-directory-p . tramp-sh-handle-file-directory-p)
    (file-executable-p . tramp-sh-handle-file-executable-p)
    (file-readable-p . tramp-sh-handle-file-readable-p)
899 900
    (file-regular-p . tramp-handle-file-regular-p)
    (file-symlink-p . tramp-handle-file-symlink-p)
901 902 903 904
    (file-writable-p . tramp-sh-handle-file-writable-p)
    (file-ownership-preserved-p . tramp-sh-handle-file-ownership-preserved-p)
    (file-newer-than-file-p . tramp-sh-handle-file-newer-than-file-p)
    (file-attributes . tramp-sh-handle-file-attributes)
905 906
    (file-modes . tramp-handle-file-modes)
    (directory-files . tramp-handle-directory-files)
907 908 909
    (directory-files-and-attributes
     . tramp-sh-handle-directory-files-and-attributes)
    (file-name-all-completions . tramp-sh-handle-file-name-all-completions)
910
    (file-name-completion . tramp-handle-file-name-completion)
911 912 913 914 915 916 917 918 919
    (add-name-to-file . tramp-sh-handle-add-name-to-file)
    (copy-file . tramp-sh-handle-copy-file)
    (copy-directory . tramp-sh-handle-copy-directory)
    (rename-file . tramp-sh-handle-rename-file)
    (set-file-modes . tramp-sh-handle-set-file-modes)
    (set-file-times . tramp-sh-handle-set-file-times)
    (make-directory . tramp-sh-handle-make-directory)
    (delete-directory . tramp-sh-handle-delete-directory)
    (delete-file . tramp-sh-handle-delete-file)
920 921
    (directory-file-name . tramp-handle-directory-file-name)
    ;; `executable-find' is not official yet.
922 923 924 925 926 927
    (executable-find . tramp-sh-handle-executable-find)
    (start-file-process . tramp-sh-handle-start-file-process)
    (process-file . tramp-sh-handle-process-file)
    (shell-command . tramp-sh-handle-shell-command)
    (insert-directory . tramp-sh-handle-insert-directory)
    (expand-file-name . tramp-sh-handle-expand-file-name)
928
    (substitute-in-file-name . tramp-handle-substitute-in-file-name)
929
    (file-local-copy . tramp-sh-handle-file-local-copy)
930 931 932
    (file-remote-p . tramp-handle-file-remote-p)
    (insert-file-contents . tramp-handle-insert-file-contents)
    (insert-file-contents-literally
933 934
     . tramp-sh-handle-insert-file-contents-literally)
    (write-region . tramp-sh-handle-write-region)
935
    (find-backup-file-name . tramp-handle-find-backup-file-name)
936
    (make-auto-save-file-name . tramp-sh-handle-make-auto-save-file-name)
937
    (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
938
    (dired-compress-file . tramp-sh-handle-dired-compress-file)
939
    (dired-recursive-delete-directory
940
     . tramp-sh-handle-dired-recursive-delete-directory)
941
    (dired-uncache . tramp-handle-dired-uncache)
942 943 944 945 946
    (set-visited-file-modtime . tramp-sh-handle-set-visited-file-modtime)
    (verify-visited-file-modtime . tramp-sh-handle-verify-visited-file-modtime)
    (file-selinux-context . tramp-sh-handle-file-selinux-context)
    (set-file-selinux-context . tramp-sh-handle-set-file-selinux-context)
    (vc-registered . tramp-sh-handle-vc-registered))
947 948 949 950 951 952 953 954 955 956
  "Alist of handler functions.
Operations not mentioned here will be handled by the normal Emacs functions.")

;; This must be the last entry, because `identity' always matches.
;;;###tramp-autoload
(add-to-list 'tramp-foreign-file-name-handler-alist
	     '(identity . tramp-sh-file-name-handler) 'append)

;;; File Name Handler Functions:

957
(defun tramp-sh-handle-make-symbolic-link
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 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 1009 1010 1011
  (filename linkname &optional ok-if-already-exists)
  "Like `make-symbolic-link' for Tramp files.
If LINKNAME is a non-Tramp file, it is used verbatim as the target of
the symlink.  If LINKNAME is a Tramp file, only the localname component is
used as the target of the symlink.

If LINKNAME is a Tramp file and the localname component is relative, then
it is expanded first, before the localname component is taken.  Note that
this can give surprising results if the user/host for the source and
target of the symlink differ."
  (with-parsed-tramp-file-name linkname l
    (let ((ln (tramp-get-remote-ln l))
	  (cwd (tramp-run-real-handler
		'file-name-directory (list l-localname))))
      (unless ln
	(tramp-error
	 l 'file-error
	 "Making a symbolic link.  ln(1) does not exist on the remote host."))

      ;; Do the 'confirm if exists' thing.
      (when (file-exists-p linkname)
	;; What to do?
	(if (or (null ok-if-already-exists) ; not allowed to exist
		(and (numberp ok-if-already-exists)
		     (not (yes-or-no-p
			   (format
			    "File %s already exists; make it a link anyway? "
			    l-localname)))))
	    (tramp-error
	     l 'file-already-exists "File %s already exists" l-localname)
	  (delete-file linkname)))

      ;; If FILENAME is a Tramp name, use just the localname component.
      (when (tramp-tramp-file-p filename)
	(setq filename
	      (tramp-file-name-localname
	       (tramp-dissect-file-name (expand-file-name filename)))))

      (tramp-flush-file-property l (file-name-directory l-localname))
      (tramp-flush-file-property l l-localname)

      ;; Right, they are on the same host, regardless of user, method, etc.
      ;; We now make the link on the remote machine. This will occur as the user
      ;; that FILENAME belongs to.
      (tramp-send-command-and-check
       l
       (format
	"cd %s && %s -sf %s %s"
	(tramp-shell-quote-argument cwd)
	ln
	(tramp-shell-quote-argument filename)
	(tramp-shell-quote-argument l-localname))
       t))))

1012
(defun tramp-sh-handle-file-truename (filename &optional counter prev-dirs)
1013 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 1089 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
  "Like `file-truename' for Tramp files."
  (with-parsed-tramp-file-name (expand-file-name filename) nil
    (with-file-property v localname "file-truename"
      (let ((result nil))			; result steps in reverse order
	(tramp-message v 4 "Finding true name for `%s'" filename)
	(cond
	 ;; Use GNU readlink --canonicalize-missing where available.
	 ((tramp-get-remote-readlink v)
	  (setq result
		(tramp-send-command-and-read
		 v
		 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
			 (tramp-get-remote-readlink v)
			 (tramp-shell-quote-argument localname)))))

	 ;; Use Perl implementation.
	 ((and (tramp-get-remote-perl v)
	       (tramp-get-connection-property v "perl-file-spec" nil)
	       (tramp-get-connection-property v "perl-cwd-realpath" nil))
	  (tramp-maybe-send-script
	   v tramp-perl-file-truename "tramp_perl_file_truename")
	  (setq result
		(tramp-send-command-and-read
		 v
		 (format "tramp_perl_file_truename %s"
			 (tramp-shell-quote-argument localname)))))

	 ;; Do it yourself.  We bind `directory-sep-char' here for
	 ;; XEmacs on Windows, which would otherwise use backslash.
	 (t (let* ((directory-sep-char ?/)
		   (steps (tramp-compat-split-string localname "/"))
		   (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
		      (nth 0 (file-attributes
			      (tramp-make-tramp-file-name
			       method user host
			       (mapconcat 'identity
					  (append '("")
						  (reverse result)
						  (list thisstep))
					  "/")))))
		(cond ((string= "." thisstep)
		       (tramp-message v 5 "Ignoring step `.'"))
		      ((string= ".." thisstep)
		       (tramp-message v 5 "Processing step `..'")
		       (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
			    "Symlink target `%s' on wrong host" symlink-target))
			 (setq symlink-target localname))
		       (setq steps
			     (append (tramp-compat-split-string
				      symlink-target "/")
				     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 "/"))))))

        (tramp-message v 4 "True name of `%s' is `%s'" filename result)
        (tramp-make-tramp-file-name method user host result)))))

;; Basic functions.

1118
(defun tramp-sh-handle-file-exists-p (filename)
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
  "Like `file-exists-p' for Tramp files."
  (with-parsed-tramp-file-name filename nil
    (with-file-property v localname "file-exists-p"
      (or (not (null (tramp-get-file-property
                      v localname "file-attributes-integer" nil)))
          (not (null (tramp-get-file-property
                      v localname "file-attributes-string" nil)))
	  (tramp-send-command-and-check
	   v
	   (format
	    "%s %s"
	    (tramp-get-file-exists-command v)
	    (tramp-shell-quote-argument localname)))))))

;; CCC: This should check for an error condition and signal failure
;;      when something goes wrong.
;; Daniel Pittman <daniel@danann.net>
1136
(defun tramp-sh-handle-file-attributes (filename &optional id-format)
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
  "Like `file-attributes' for Tramp files."
  (unless id-format (setq id-format 'integer))
  ;; Don't modify `last-coding-system-used' by accident.
  (let ((last-coding-system-used last-coding-system-used))
    (with-parsed-tramp-file-name (expand-file-name filename) nil
      (with-file-property v localname (format "file-attributes-%s" id-format)
	(save-excursion
	  (tramp-convert-file-attributes
	   v
	   (cond
	    ((tramp-get-remote-stat v)
	     (tramp-do-file-attributes-with-stat v localname id-format))
	    ((tramp-get-remote-perl v)
	     (tramp-do-file-attributes-with-perl v localname id-format))
	    (t
	     (tramp-do-file-attributes-with-ls v localname id-format)))))))))

(defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
  "Implement `file-attributes' for Tramp files using the ls(1) command."
  (let (symlinkp dirp
		 res-inode res-filemodes res-numlinks
		 res-uid res-gid res-size res-symlink-target)
    (tramp-message vec 5 "file attributes with ls: %s" localname)
    (tramp-send-command
     vec
     (format "(%s %s || %s -h %s) && %s %s %s"
	     (tramp-get-file-exists-command vec)
	     (tramp-shell-quote-argument localname)
	     (tramp-get-test-command vec)
	     (tramp-shell-quote-argument localname)
	     (tramp-get-ls-command vec)
	     (if (eq id-format 'integer) "-ildn" "-ild")
	     (tramp-shell-quote-argument localname)))
    ;; parse `ls -l' output ...
    (with-current-buffer (tramp-get-buffer vec)
      (when (> (buffer-size) 0)
        (goto-char (point-min))
        ;; ... inode
        (setq res-inode
              (condition-case err
                  (read (current-buffer))
                (invalid-read-syntax
                 (when (and (equal (cadr err)
                                   "Integer constant overflow in reader")
                            (string-match
                             "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
                             (car (cddr err))))
                   (let* ((big (read (substring (car (cddr err)) 0
                                                (match-beginning 1))))
                          (small (read (match-string 1 (car (cddr err)))))
                          (twiddle (/ small 65536)))
                     (cons (+ big twiddle)
                           (- small (* twiddle 65536))))))))
        ;; ... file mode flags
        (setq res-filemodes (symbol-name (read (current-buffer))))
        ;; ... number links
        (setq res-numlinks (read (current-buffer)))
        ;; ... uid and gid
        (setq res-uid (read (current-buffer)))
        (setq res-gid (read (current-buffer)))
        (if (eq id-format 'integer)
            (progn
              (unless (numberp res-uid) (setq res-uid -1))
              (unless (numberp res-gid) (setq res-gid -1)))
          (progn
            (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
            (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
        ;; ... size
        (setq res-size (read (current-buffer)))
        ;; From the file modes, figure out other stuff.
        (setq symlinkp (eq ?l (aref res-filemodes 0)))
        (setq dirp (eq ?d (aref res-filemodes 0)))
        ;; if symlink, find out file name pointed to
        (when symlinkp
          (search-forward "-> ")
1212
          (setq res-symlink-target (buffer-substring (point) (point-at-eol))))
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
        ;; return data gathered
        (list
         ;; 0. t for directory, string (name linked to) for symbolic
         ;; link, or nil.
         (or dirp res-symlink-target)
         ;; 1. Number of links to file.
         res-numlinks
         ;; 2. File uid.
         res-uid
         ;; 3. File gid.
         res-gid
         ;; 4. Last access time, as a list of two integers. First
         ;; integer has high-order 16 bits of time, second has low 16
         ;; bits.
         ;; 5. Last modification time, likewise.
         ;; 6. Last status change time, likewise.
         '(0 0) '(0 0) '(0 0)		;CCC how to find out?
         ;; 7. Size in bytes (-1, if number is out of range).
         res-size
         ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
         res-filemodes
         ;; 9. t if file's gid would change if file were deleted and
         ;; recreated.  Will be set in `tramp-convert-file-attributes'
         t
         ;; 10. inode number.
         res-inode
         ;; 11. Device number.  Will be replaced by a virtual device number.
         -1
         )))))

(defun tramp-do-file-attributes-with-perl
  (vec localname &optional id-format)
  "Implement `file-attributes' for Tramp files using a Perl script."
  (tramp-message vec 5 "file attributes with perl: %s" localname)
  (tramp-maybe-send-script
   vec tramp-perl-file-attributes "tramp_perl_file_attributes")
  (tramp-send-command-and-read
   vec
   (format "tramp_perl_file_attributes %s %s"
	   (tramp-shell-quote-argument localname) id-format)))

(defun tramp-do-file-attributes-with-stat
  (vec localname &optional id-format)
  "Implement `file-attributes' for Tramp files using stat(1) command."
  (tramp-message vec 5 "file attributes with stat: %s" localname)
  (tramp-send-command-and-read
   vec
   (format
    ;; On Opsware, pdksh (which is the true name of ksh there) doesn't
    ;; parse correctly the sequence "((".  Therefore, we add a space.
1263
    "( (%s %s || %s -h %s) && %s -c '((\"%%N\") %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 \"%%A\" t %%ie0 -1)' %s || echo nil)"
1264 1265 1266 1267 1268 1269 1270 1271 1272
    (tramp-get-file-exists-command vec)
    (tramp-shell-quote-argument localname)
    (tramp-get-test-command vec)
    (tramp-shell-quote-argument localname)
    (tramp-get-remote-stat vec)
    (if (eq id-format 'integer) "%u" "\"%U\"")
    (if (eq id-format 'integer) "%g" "\"%G\"")
    (tramp-shell-quote-argument localname))))

1273
(defun tramp-sh-handle-set-visited-file-modtime (&optional time-list)
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
  "Like `set-visited-file-modtime' for Tramp files."
  (unless (buffer-file-name)
    (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
	   (buffer-name)))
  (if time-list
      (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
    (let ((f (buffer-file-name))
	  coding-system-used)
      (with-parsed-tramp-file-name f nil
	(let* ((attr (file-attributes f))
	       ;; '(-1 65535) means file doesn't exists yet.
	       (modtime (or (nth 5 attr) '(-1 65535))))
	  (when (boundp 'last-coding-system-used)
	    (setq coding-system-used (symbol-value 'last-coding-system-used)))
	  ;; We use '(0 0) as a don't-know value.  See also
	  ;; `tramp-do-file-attributes-with-ls'.
	  (if (not (equal modtime '(0 0)))
	      (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
	    (progn
	      (tramp-send-command
	       v
	       (format "%s -ild %s"
		       (tramp-get-ls-command v)
		       (tramp-shell-quote-argument localname)))
	      (setq attr (buffer-substring (point)
					   (progn (end-of-line) (point)))))
	    (tramp-set-file-property
	     v localname "visited-file-modtime-ild" attr))
	  (when (boundp 'last-coding-system-used)
	    (set 'last-coding-system-used coding-system-used))
	  nil)))))

;; This function makes the same assumption as
1307 1308
;; `tramp-sh-handle-set-visited-file-modtime'.
(defun tramp-sh-handle-verify-visited-file-modtime (buf)
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
  "Like `verify-visited-file-modtime' for Tramp files.
At the time `verify-visited-file-modtime' calls this function, we
already know that the buffer is visiting a file and that
`visited-file-modtime' does not return 0.  Do not call this
function directly, unless those two cases are already taken care
of."
  (with-current-buffer buf
    (let ((f (buffer-file-name)))
      ;; There is no file visiting the buffer, or the buffer has no
      ;; recorded last modification time, or there is no established
      ;; connection.
      (if (or (not f)
	      (eq (visited-file-modtime) 0)
	      (not (tramp-file-name-handler 'file-remote-p f nil 'connected)))
	  t
	(with-parsed-tramp-file-name f nil
1325 1326
	  (let* ((remote-file-name-inhibit-cache t)
		 (attr (file-attributes f))
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
		 (modtime (nth 5 attr))
		 (mt (visited-file-modtime)))

	    (cond
	     ;; File exists, and has a known modtime.
	     ((and attr (not (equal modtime '(0 0))))
	      (< (abs (tramp-time-diff
		       modtime
		       ;; For compatibility, deal with both the old
		       ;; (HIGH . LOW) and the new (HIGH LOW) return
		       ;; values of `visited-file-modtime'.
		       (if (atom (cdr mt))
			   (list (car mt) (cdr mt))
			 mt)))
		 2))
	     ;; Modtime has the don't know value.
	     (attr
	      (tramp-send-command
	       v
	       (format "%s -ild %s"
		       (tramp-get-ls-command v)
		       (tramp-shell-quote-argument localname)))
	      (with-current-buffer (tramp-get-buffer v)
		(setq attr (buffer-substring
			    (point) (progn (end-of-line) (point)))))
	      (equal
	       attr
	       (tramp-get-file-property
		v localname "visited-file-modtime-ild" "")))
	     ;; If file does not exist, say it is not modified if and
	     ;; only if that agrees with the buffer's record.
	     (t (equal mt '(-1 65535))))))))))

1360
(defun tramp-sh-handle-set-file-modes (filename mode)
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
  "Like `set-file-modes' for Tramp files."
  (with-parsed-tramp-file-name filename nil
    (tramp-flush-file-property v localname)
    ;; FIXME: extract the proper text from chmod's stderr.
    (tramp-barf-unless-okay
     v
     (format "chmod %s %s"
	     (tramp-compat-decimal-to-octal mode)
	     (tramp-shell-quote-argument localname))
     "Error while changing file's mode %s" filename)))

1372
(defun tramp-sh-handle-set-file-times (filename &optional time)
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
  "Like `set-file-times' for Tramp files."
  (if (file-remote-p filename)
      (with-parsed-tramp-file-name filename nil
	(tramp-flush-file-property v localname)
	(let ((time (if (or (null time) (equal time '(0 0)))
			(current-time)
		      time))
	      ;; With GNU Emacs, `format-time-string' has an optional
	      ;; parameter UNIVERSAL.  This is preferred, because we
	      ;; could handle the case when the remote host is located
	      ;; in a different time zone as the local host.
	      (utc (not (featurep 'xemacs))))
	  (tramp-send-command-and-check
	   v (format "%s touch -t %s %s"
		     (if utc "TZ=UTC; export TZ;" "")
		     (if utc
			 (format-time-string "%Y%m%d%H%M.%S" time t)
		       (format-time-string "%Y%m%d%H%M.%S" time))
		     (tramp-shell-quote-argument localname)))))

    ;; We handle also the local part, because in older Emacsen,
    ;; without `set-file-times', this function is an alias for this.
    ;; We are local, so we don't need the UTC settings.
    (zerop
     (tramp-compat-call-process
      "touch" nil nil nil "-t"
      (format-time-string "%Y%m%d%H%M.%S" time)
      (tramp-shell-quote-argument filename)))))

(defun tramp-set-file-uid-gid (filename &optional uid gid)
  "Set the ownership for FILENAME.
If UID and GID are provided, these values are used; otherwise uid
and gid of the corresponding user is taken.  Both parameters must be integers."
  ;; Modern Unices allow chown only for root.  So we might need
  ;; another implementation, see `dired-do-chown'.  OTOH, it is mostly
  ;; working with su(do)? when it is needed, so it shall succeed in
  ;; the majority of cases.
  ;; Don't modify `last-coding-system-used' by accident.
  (let ((last-coding-system-used last-coding-system-used))
    (if (file-remote-p filename)
	(with-parsed-tramp-file-name filename nil
	  (if (and (zerop (user-uid)) (tramp-local-host-p v))
	      ;; If we are root on the local host, we can do it directly.
	      (tramp-set-file-uid-gid localname uid gid)
	    (let ((uid (or (and (integerp uid) uid)
			   (tramp-get-remote-uid v 'integer)))
		  (gid (or (and (integerp gid) gid)
			   (tramp-get-remote-gid v 'integer))))
	      (tramp-send-command
	       v (format
		  "chown %d:%d %s" uid gid
		  (tramp-shell-quote-argument localname))))))

      ;; We handle also the local part, because there doesn't exist
      ;; `set-file-uid-gid'.  On W32 "chown" might not work.
      (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
	    (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
	(tramp-compat-call-process
	 "chown" nil nil nil
         (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))

(defun tramp-remote-selinux-p (vec)
  "Check, whether SELINUX is enabled on the remote host."
  (with-connection-property (tramp-get-connection-process vec) "selinux-p"
    (let ((result (tramp-find-executable
		   vec "getenforce" (tramp-get-remote-path vec) t t)))
      (and result
	   (string-equal
	    (tramp-send-command-and-read
	     vec (format "echo \\\"`%S`\\\"" result))
	    "Enforcing")))))

1445
(defun tramp-sh-handle-file-selinux-context (filename)
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
  "Like `file-selinux-context' for Tramp files."
  (with-parsed-tramp-file-name filename nil
    (with-file-property v localname "file-selinux-context"
      (let ((context '(nil nil nil nil))
	    (regexp (concat "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\):"
			    "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\)")))
	(when (and (tramp-remote-selinux-p v)
		   (tramp-send-command-and-check
		    v (format
		       "%s -d -Z %s"
		       (tramp-get-ls-command v)
		       (tramp-shell-quote-argument localname))))
	  (with-current-buffer (tramp-get-connection-buffer v)
	    (goto-char (point-min))
1460
	    (when (re-search-forward regexp (point-at-eol) t)
1461 1462 1463 1464 1465
	      (setq context (list (match-string 1) (match-string 2)
				  (match-string 3) (match-string 4))))))
	;; Return the context.
	context))))

1466
(defun tramp-sh-handle-set-file-selinux-context (filename context)
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
  "Like `set-file-selinux-context' for Tramp files."
  (with-parsed-tramp-file-name filename nil
    (if (and (consp context)
	     (tramp-remote-selinux-p v)
	     (tramp-send-command-and-check
	      v (format "chcon %s %s %s %s %s"
			(if (stringp (nth 0 context))
			    (format "--user=%s" (nth 0 context)) "")
			(if (stringp (nth 1 context))
			    (format "--role=%s" (nth 1 context)) "")
			(if (stringp (nth 2 context))
			    (format "--type=%s" (nth 2 context)) "")
			(if (stringp (nth 3 context))
			    (format "--range=%s" (nth 3 context)) "")
			(tramp-shell-quote-argument localname))))
	(tramp-set-file-property v localname "file-selinux-context" context)
      (tramp-set-file-property v localname "file-selinux-context" 'undef)))
  ;; We always return nil.
  nil)

;; Simple functions using the `test' command.

1489
(defun tramp-sh-handle-file-executable-p (filename)
1490 1491 1492 1493 1494 1495 1496 1497
  "Like `file-executable-p' for Tramp files."
  (with-parsed-tramp-file-name filename nil
    (with-file-property v localname "file-executable-p"
      ;; Examine `file-attributes' cache to see if request can be
      ;; satisfied without remote operation.
      (or (tramp-check-cached-permissions v ?x)
	  (tramp-run-test "-x" filename)))))

1498
(defun tramp-sh-handle-file-readable-p (filename)
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
  "Like `file-readable-p' for Tramp files."
  (with-parsed-tramp-file-name filename nil
    (with-file-property v localname "file-readable-p"
      ;; Examine `file-attributes' cache to see if request can be
      ;; satisfied without remote operation.
      (or (tramp-check-cached-permissions v ?r)
	  (tramp-run-test "-r" filename)))))

;; When the remote shell is started, it looks for a shell which groks
;; tilde expansion.  Here, we assume that all shells which grok tilde
;; expansion will also provide a `test' command which groks `-nt' (for
;; newer than).  If this breaks, tell me about it and I'll try to do
;; something smarter about it.
1512
(defun tramp-sh-handle-file-newer-than-file-p (file1 file2)
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
  "Like `file-newer-than-file-p' for Tramp files."
  (cond ((not (file-exists-p file1))
         nil)
        ((not (file-exists-p file2))
         t)
        ;; We are sure both files exist at this point.
        (t
         (save-excursion
	   ;; We try to get the mtime of both files.  If they are not
	   ;; equal to the "dont-know" value, then we subtract the times
	   ;; and obtain the result.
	   (let ((fa1 (file-attributes file1))
		 (fa2 (file-attributes file2)))
	     (if (and (not (equal (nth 5 fa1) '(0 0)))
		      (not (equal (nth 5 fa2) '(0 0))))
		 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
	       ;; If one of them is the dont-know value, then we can
	       ;; still try to run a shell command on the remote host.
	       ;; However, this only works if both files are Tramp
	       ;; files and both have the same method, same user, same
	       ;; host.
	       (unless (tramp-equal-remote file1 file2)
		 (with-parsed-tramp-file-name
		     (if (tramp-tramp-file-p file1) file1 file2) nil
		   (tramp-error
		    v 'file-error
		    "Files %s and %s must have same method, user, host"
		    file1 file2)))
	       (with-parsed-tramp-file-name file1 nil
		 (tramp-run-test2
		  (tramp-get-test-nt-command v) file1 file2))))))))

;; Functions implemented using the basic functions above.

1547
(defun tramp-sh-handle-file-directory-p (filename)
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
  "Like `file-directory-p' for Tramp files."
  ;; Care must be taken that this function returns `t' for symlinks
  ;; pointing to directories.  Surely the most obvious implementation
  ;; would be `test -d', but that returns false for such symlinks.
  ;; CCC: Stefan Monnier says that `test -d' follows symlinks.  And
  ;; I now think he's right.  So we could be using `test -d', couldn't
  ;; we?
  ;;
  ;; Alternatives: `cd %s', `test -d %s'
  (with-parsed-tramp-file-name filename nil
    (with-file-property v localname "file-directory-p"
      (tramp-run-test "-d" filename))))

1561
(defun tramp-sh-handle-file-writable-p (filename)
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
  "Like `file-writable-p' for Tramp files."
  (with-parsed-tramp-file-name filename nil
    (with-file-property v localname "file-writable-p"
      (if (file-exists-p filename)
	  ;; Examine `file-attributes' cache to see if request can be
	  ;; satisfied without remote operation.
          (or (tramp-check-cached-permissions v ?w)
	      (tramp-run-test "-w" filename))
	;; If file doesn't exist, check if directory is writable.
	(and (tramp-run-test "-d" (file-name-directory filename))
	     (tramp-run-test "-w" (file-name-directory filename)))))))

1574
(defun tramp-sh-handle-file-ownership-preserved-p (filename)
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
  "Like `file-ownership-preserved-p' for Tramp files."
  (with-parsed-tramp-file-name filename nil
    (with-file-property v localname "file-ownership-preserved-p"
      (let ((attributes (file-attributes filename)))
	;; Return t if the file doesn't exist, since it's true that no
	;; information would be lost by an (attempted) delete and create.
	(or (null attributes)
	    (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))

;; Directory listings.

1586
(defun tramp-sh-handle-directory-files-and-attributes
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
  (directory &optional full match nosort id-format)
  "Like `directory-files-and-attributes' for Tramp files."
  (unless id-format (setq id-format 'integer))
  (when (file-directory-p directory)
    (setq directory (expand-file-name directory))
    (let* ((temp
	    (copy-tree
	     (with-parsed-tramp-file-name directory nil
	       (with-file-property
		   v localname
		   (format "directory-files-and-attributes-%s" id-format)
		 (save-excursion
		   (mapcar
		    (lambda (x)
		      (cons (car x)
			    (tramp-convert-file-attributes v (cdr x))))
		    (cond
		     ((tramp-get-remote-stat v)
		      (tramp-do-directory-files-and-attributes-with-stat
		       v localname id-format))
		     ((tramp-get-remote-perl v)
		      (tramp-do-directory-files-and-attributes-with-perl
		       v localname id-format)))))))))
	   result item)

      (while temp
	(setq item (pop temp))
	(when (or (null match) (string-match match (car item)))
	  (when full
	    (setcar item (expand-file-name (car item) directory)))
	  (push item result)))

      (if nosort
	  result
	(sort result (lambda (x y) (string< (car x) (car y))))))))

(defun tramp-do-directory-files-and-attributes-with-perl
  (vec localname &optional id-format)
  "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
  (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
  (tramp-maybe-send-script
   vec tramp-perl-directory-files-and-attributes
   "tramp_perl_directory_files_and_attributes")
  (let ((object
	 (tramp-send-command-and-read
	  vec
	  (format "tramp_perl_directory_files_and_attributes %s %s"
		  (tramp-shell-quote-argument localname) id-format))))
    (when (stringp object) (tramp-error vec 'file-error object))
    object))

(defun tramp-do-directory-files-and-attributes-with-stat
  (vec localname &optional id-format)
  "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
  (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
  (tramp-send-command-and-read
   vec
   (format
    (concat
     ;; We must care about filenames with spaces, or starting with
     ;; "-"; this would confuse xargs.  "ls -aQ" might be a solution,
     ;; but it does not work on all remote systems.  Therefore, we
     ;; quote the filenames via sed.
     "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
1651
     "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 \"%%A\" t %%ie0 -1)'); "
1652 1653 1654 1655 1656 1657 1658 1659 1660
     "echo \")\"")
    (tramp-shell-quote-argument localname)
    (tramp-get-ls-command vec)
    (tramp-get-remote-stat vec)
    (if (eq id-format 'integer) "%u" "\"%U\"")
    (if (eq id-format 'integer) "%g" "\"%G\""))))

;; This function should return "foo/" for directories and "bar" for
;; files.
1661
(defun tramp-sh-handle-file-name-all-completions (filename directory)
1662 1663 1664 1665 1666 1667 1668 1669 1670
  "Like `file-name-all-completions' for Tramp files."
  (unless (save-match-data (string-match "/" filename))
    (with-parsed-tramp-file-name (expand-file-name directory) nil

      (all-completions
       filename
       (mapcar
	'list
        (or
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
	 ;; Try cache entries for filename, filename with last
	 ;; character removed, filename with last two characters
	 ;; removed, ..., and finally the empty string - all
	 ;; concatenated to the local directory name.
         (let ((remote-file-name-inhibit-cache
		(or remote-file-name-inhibit-cache
		    tramp-completion-reread-directory-timeout)))

	   ;; This is inefficient for very long filenames, pity
	   ;; `reduce' is not available...
	   (car
	    (apply
	     'append
	     (mapcar
	      (lambda (x)
		(let ((cache-hit
		       (tramp-get-file-property
			v
			(concat localname (substring filename 0 x))
			"file-name-all-completions"
			nil)))
		  (when cache-hit (list cache-hit))))
	      (tramp-compat-number-sequence (length filename) 0 -1)))))
1694 1695

         ;; Cache expired or no matching cache entry found so we need
1696
         ;; to perform a remote operation.
1697 1698 1699 1700 1701 1702
         (let (result)
           ;; Get a list of directories and files, including reliably
           ;; tagging the directories with a trailing '/'.  Because I
           ;; rock.  --daniel@danann.net

           ;; Changed to perform `cd' in the same remote op and only
1703
           ;; get entries starting with `filename'.  Capture any `cd'
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
           ;; error messages.  Ensure any `cd' and `echo' aliases are
           ;; ignored.
           (tramp-send-command
            v
            (if (tramp-get-remote-perl v)
                (progn
                  (tramp-maybe-send-script
                   v tramp-perl-file-name-all-completions
                   "tramp_perl_file_name_all_completions")
                  (format "tramp_perl_file_name_all_completions %s %s %d"
                          (tramp-shell-quote-argument localname)
                          (tramp-shell-quote-argument filename)
                          (if (symbol-value
			       ;; `read-file-name-completion-ignore-case'
			       ;; is introduced with Emacs 22.1.
			       (if (boundp
				    'read-file-name-completion-ignore-case)
				   'read-file-name-completion-ignore-case
				 'completion-ignore-case))
			      1 0)))

              (format (concat
                       "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
                       ;; `ls' with wildcard might fail with `Argument
                       ;; list too long' error in some corner cases; if
                       ;; `ls' fails after `cd' succeeded, chances are
                       ;; that's the case, so let's retry without
                       ;; wildcard.  This will return "too many" entries
                       ;; but that isn't harmful.
                       " || %s -a 2>/dev/null)"
                       " | while read f; do"
                       " if %s -d \"$f\" 2>/dev/null;"
                       " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
                       " && \\echo ok) || \\echo fail")
                      (tramp-shell-quote-argument localname)
                      (tramp-get-ls-command v)
                      ;; When `filename' is empty, just `ls' without
                      ;; filename argument is more efficient than `ls *'
                      ;; for very large directories and might avoid the
                      ;; `Argument list too long' error.
                      ;;
                      ;; With and only with wildcard, we need to add
                      ;; `-d' to prevent `ls' from descending into
                      ;; sub-directories.
                      (if (zerop (length filename))
                          "."
                        (concat (tramp-shell-quote-argument filename) "* -d"))
                      (tramp-get-ls-command v)
                      (tramp-get-test-command v))))

           ;; Now grab the output.
           (with-current-buffer (tramp-get-buffer v)
             (goto-char (point-max))

             ;; Check result code, found in last line of output
             (forward-line -1)
             (if (looking-at "^fail$")
                 (progn
                   ;; Grab error message from line before last line
                   ;; (it was put there by `cd 2>&1')
                   (forward-line -1)
                   (tramp-error
                    v 'file-error
1767
                    "tramp-sh-handle-file-name-all-completions: %s"
1768
                    (buffer-substring (point) (point-at-eol))))
1769 1770 1771 1772 1773 1774 1775 1776
               ;; For peace of mind, if buffer doesn't end in `fail'
               ;; then it should end in `ok'.  If neither are in the
               ;; buffer something went seriously wrong on the remote
               ;; side.
               (unless (looking-at "^ok$")
                 (tramp-error
                  v 'file-error
                  "\
1777
tramp-sh-handle-file-name-all-completions: internal error accessing `%s': `%s'"
1778 1779 1780
                  (tramp-shell-quote-argument localname) (buffer-string))))

             (while (zerop (forward-line -1))
1781
               (push (buffer-substring (point) (point-at-eol)) result)))
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802

           ;; Because the remote op went through OK we know the
           ;; directory we `cd'-ed to exists
           (tramp-set-file-property
            v localname "file-exists-p" t)

           ;; Because the remote op went through OK we know every
           ;; file listed by `ls' exists.
           (mapc (lambda (entry)
		   (tramp-set-file-property
		    v (concat localname entry) "file-exists-p" t))
		 result)

           ;; Store result in the cache
           (tramp-set-file-property
            v (concat localname filename)
            "file-name-all-completions"
            result))))))))

;; cp, mv and ln

1803
(defun tramp-sh-handle-add-name-to-file
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
  (filename newname &optional ok-if-already-exists)
  "Like `add-name-to-file' for Tramp files."
  (unless (tramp-equal-remote filename newname)
    (with-parsed-tramp-file-name
	(if (tramp-tramp-file-p filename) filename newname) nil
      (tramp-error
       v 'file-error
       "add-name-to-file: %s"
       "only implemented for same method, same user, same host")))
  (with-parsed-tramp-file-name filename v1
    (with-parsed-tramp-file-name newname v2
      (let ((ln (when v1 (tramp-get-remote-ln v1))))
	(when (and (not ok-if-already-exists)
		   (file-exists-p newname)
		   (not (numberp ok-if-already-exists))
		   (y-or-n-p
		    (format
		     "File %s already exists; make it a new name anyway? "
		     newname)))
	  (tramp-error
	   v2 'file-error
	   "add-name-to-file: file %s already exists" newname))
	(tramp-flush-file-property v2 (file-name-directory v2-localname))
	(tramp-flush-file-property v2 v2-localname)
	(tramp-barf-unless-okay
	 v1
	 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
		 (tramp-shell-quote-argument v2-localname))
	 "error with add-name-to-file, see buffer `%s' for details"
	 (buffer-name))))))

1835
(defun tramp-sh-handle-copy-file
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
  (filename newname &optional ok-if-already-exists keep-date
	    preserve-uid-gid preserve-selinux-context)
  "Like `copy-file' for Tramp files."
  (setq filename (expand-file-name filename))
  (setq newname (expand-file-name newname))
  (cond
   ;; At least one file a Tramp file?
   ((or (tramp-tramp-file-p filename)
	(tramp-tramp-file-p newname))
    (tramp-do-copy-or-rename-file
     'copy filename newname ok-if-already-exists keep-date
     preserve-uid-gid preserve-selinux-context))
   ;; Compat section.
   (preserve-selinux-context
    (tramp-run-real-handler
     'copy-file
     (list filename newname ok-if-already-exists keep-date
	   preserve-uid-gid preserve-selinux-context)))
   (preserve-uid-gid
    (tramp-run-real-handler
     'copy-file
     (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
   (t
    (tramp-run-real-handler
     'copy-file (list filename newname ok-if-already-exists keep-date)))))

1862 1863
(defun tramp-sh-handle-copy-directory
  (dirname newname &optional keep-date parents)
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
  "Like `copy-directory' for Tramp files."
  (let ((t1 (tramp-tramp-file-p dirname))
	(t2 (tramp-tramp-file-p newname)))
    (with-parsed-tramp-file-name (if t1 dirname newname) nil
      (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
	       ;; When DIRNAME and NEWNAME are remote, they must have
	       ;; the same method.
	       (or (null t1) (null t2)
		   (string-equal
		    (tramp-file-name-method (tramp-dissect-file-name dirname))
		    (tramp-file-name-method (tramp-dissect-file-name newname)))))
	  ;; scp or rsync DTRT.
	  (progn
	    (setq dirname (directory-file-name (expand-file-name dirname))
		  newname (directory-file-name (expand-file-name newname)))
	    (if (and (file-directory-p newname)
		     (not (string-equal (file-name-nondirectory dirname)
					(file-name-nondirectory newname))))
		(setq newname
		      (expand-file-name
		       (file-name-nondirectory dirname) newname)))
	    (if (not (file-directory-p (file-name-directory newname)))
		(make-directory (file-name-directory newname) parents))
	    (tramp-do-copy-or-rename-file-out-of-band
	     'copy dirname newname keep-date))
	;; We must do it file-wise.
	(tramp-run-real-handler
	 'copy-directory (list dirname newname keep-date parents)))

      ;; When newname did exist, we have wrong cached values.
      (when t2
	(with-parsed-tramp-file-name newname nil
	  (tramp-flush-file-property v (file-name-directory localname))
	  (tramp-flush-file-property v localname))))))

1899
(defun tramp-sh-handle-rename-file
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
  (filename newname &optional ok-if-already-exists)
  "Like `rename-file' for Tramp files."
  ;; Check if both files are local -- invoke normal rename-file.
  ;; Otherwise, use Tramp from local system.
  (setq filename (expand-file-name filename))
  (setq newname (expand-file-name newname))
  ;; At least one file a Tramp file?
  (if (or (tramp-tramp-file-p filename)
          (tramp-tramp-file-p newname))
      (tramp-do-copy-or-rename-file
       'rename filename newname ok-if-already-exists t t)
    (tramp-run-real-handler
     'rename-file (list filename newname ok-if-already-exists))))

(defun tramp-do-copy-or-rename-file
  (op filename newname &optional ok-if-already-exists keep-date
      preserve-uid-gid preserve-selinux-context)
  "Copy or rename a remote file.
OP must be `copy' or `rename' and indicates the operation to perform.
FILENAME specifies the file to copy or rename, NEWNAME is the name of
the new file (for copy) or the new name of the file (for rename).
OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
KEEP-DATE means to make sure that NEWNAME has the same timestamp
as FILENAME.  PRESERVE-UID-GID, when non-nil, instructs to keep
the uid and gid if both files are on the same host.
PRESERVE-SELINUX-CONTEXT activates selinux commands.

1927 1928 1929 1930
This function is invoked by `tramp-sh-handle-copy-file' and
`tramp-sh-handle-rename-file'.  It is an error if OP is neither
of `copy' and `rename'.  FILENAME and NEWNAME must be absolute
file names."
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
  (unless (memq op '(copy rename))
    (error "Unknown operation `%s', must be `copy' or `rename'" op))
  (let ((t1 (tramp-tramp-file-p filename))
	(t2 (tramp-tramp-file-p newname))
	(context (and preserve-selinux-context
		      (apply 'file-selinux-context (list filename))))
	pr tm)

    (with-parsed-tramp-file-name (if t1 filename newname) nil
      (when (and (not ok-if-already-exists) (file-exists-p newname))
	(tramp-error
	 v 'file-already-exists "File %s already exists" newname))

      (with-progress-reporter
	  v 0 (format "%s %s to %s"
		      (if (eq op 'copy) "Copying" "Renaming")
		      filename newname)

	(cond
	 ;; Both are Tramp files.
	 ((and t1 t2)
	  (with-parsed-tramp-file-name filename v1
	    (with-parsed-tramp-file-name newname v2
	      (cond
	       ;; Shortcut: if method, host, user are the same for
	       ;; both files, we invoke `cp' or `mv' on the remote
	       ;; host directly.
	       ((tramp-equal-remote filename newname)
		(tramp-do-copy-or-rename-file-directly
		 op filename newname
		 ok-if-already-exists keep-date preserve-uid-gid))

	       ;; Try out-of-band operation.
	       ((tramp-method-out-of-band-p
1965
		 v1 (nth 7 (file-attributes (file-truename filename))))
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
		(tramp-do-copy-or-rename-file-out-of-band
		 op filename newname keep-date))

	       ;; No shortcut was possible.  So we copy the file
	       ;; first.  If the operation was `rename', we go back
	       ;; and delete the original file (if the copy was
	       ;; successful).  The approach is simple-minded: we
	       ;; create a new buffer, insert the contents of the
	       ;; source file into it, then write out the buffer to
	       ;; the target file.  The advantage is that it doesn't
	       ;; matter which filename handlers are used for the
	       ;; source and target file.
	       (t
		(tramp-do-copy-or-rename-file-via-buffer
		 op filename newname keep-date))))))

	 ;; One file is a Tramp file, the other one is local.
	 ((or t1 t2)
	  (cond
	   ;; Fast track on local machine.
	   ((tramp-local-host-p v)
	    (tramp-do-copy-or-rename-file-directly
	     op filename newname
	     ok-if-already-exists keep-date preserve-uid-gid))

	   ;; If the Tramp file has an out-of-band method, the
	   ;; corresponding copy-program can be invoked.
1993 1994
	   ((tramp-method-out-of-band-p
	     v (nth 7 (file-attributes (file-truename filename))))
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
	    (tramp-do-copy-or-rename-file-out-of-band
	     op filename newname keep-date))

	   ;; Use the inline method via a Tramp buffer.
	   (t (tramp-do-copy-or-rename-file-via-buffer
	       op filename newname keep-date))))

	 (t
	  ;; One of them must be a Tramp file.
	  (error "Tramp implementation says this cannot happen")))

	;; Handle `preserve-selinux-context'.
	(when context (apply 'set-file-selinux-context (list newname context)))

	;; In case of `rename', we must flush the cache of the source file.
	(when (and t1 (eq op 'rename))
	  (with-parsed-tramp-file-name filename v1
	    (tramp-flush-file-property v1 (file-name-directory localname))
	    (tramp-flush-file-property v1 localname)))

	;; When newname did exist, we have wrong cached values.
	(when t2
	  (with-parsed-tramp-file-name newname v2
	    (tramp-flush-file-property v2 (file-name-directory localname))
	    (tramp-flush-file-property v2 localname)))))))

(defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
  "Use an Emacs buffer to copy or rename a file.
First arg OP is either `copy' or `rename' and indicates the operation.
FILENAME is the source file, NEWNAME the target file.
KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
  (with-temp-buffer
    ;; We must disable multibyte, because binary data shall not be
    ;; converted.
    (set-buffer-multibyte nil)
    (let ((coding-system-for-read 'binary)
	  (jka-compr-inhibit t))
      (insert-file-contents-literally filename))
    ;; We don't want the target file to be compressed, so we let-bind
    ;; `jka-compr-inhibit' to t.
    (let ((coding-system-for-write 'binary)
	  (jka-compr-inhibit t))
      (write-region (point-min) (point-max) newname)))
  ;; KEEP-DATE handling.
  (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
  ;; Set the mode.
  (set-file-modes newname (tramp-default-file-modes filename))
  ;; If the operation was `rename', delete the original file.
  (unless (eq op 'copy) (delete-file filename)))

(defun tramp-do-copy-or-rename-file-directly
 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
  "Invokes `cp' or `mv' on the remote system.
OP must be one of `copy' or `rename', indicating `cp' or `mv',
respectively.  FILENAME specifies the file to copy or rename,
NEWNAME is the name of the new file (for copy) or the new name of
the file (for rename).  Both files must reside on the same host.
KEEP-DATE means to make sure that NEWNAME has the same timestamp
as FILENAME.  PRESERVE-UID-GID, when non-nil, instructs to keep
the uid and gid from FILENAME."
  (let ((t1 (tramp-tramp-file-p filename))
	(t2 (tramp-tramp-file-p newname))
	(file-times (nth 5 (file-attributes filename)))
	(file-modes (tramp-default-file-modes filename)))
    (with-parsed-tramp-file-name (if t1 filename newname) nil
      (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
			((eq op 'copy) "cp -f")
			((eq op 'rename) "mv -f")
			(t (tramp-error
			    v 'file-error
			    "Unknown operation `%s', must be `copy' or `rename'"
			    op))))
	     (localname1
	      (if t1
		  (tramp-file-name-handler 'file-remote-p filename 'localname)
		filename))
	     (localname2
	      (if t2
		  (tramp-file-name-handler 'file-remote-p newname 'localname)
		newname))
	     (prefix (file-remote-p (if t1 filename newname)))
             cmd-result)

	(cond
	 ;; Both files are on a remote host, with same user.
	 ((and t1 t2)
          (setq cmd-result
                (tramp-send-command-and-check
                 v (format "%s %s %s" cmd
			   (tramp-shell-quote-argument localname1)
			   (tramp-shell-quote-argument localname2))))
	  (with-current-buffer (tramp-get-buffer v)
	    (goto-char (point-min))
	    (unless
		(or
		 (and keep-date
		      ;; Mask cp -f error.
		      (re-search-forward
		       tramp-operation-not-permitted-regexp nil t))
		 cmd-result)
	      (tramp-error-with-buffer
	       nil v 'file-error
	       "Copying directly failed, see buffer `%s' for details."
	       (buffer-name)))))

	 ;; We are on the local host.
	 ((or t1 t2)
	  (cond
	   ;; We can do it directly.
	   ((let (file-name-handler-alist)
	      (and (file-readable-p localname1)
		   (file-writable-p (file-name-directory localname2))
		   (or (file-directory-p localname2)
		       (file-writable-p localname2))))
	    (if (eq op 'copy)
		(tramp-compat-copy-file
		 localname1 localname2 ok-if-already-exists
		 keep-date preserve-uid-gid)
	      (tramp-run-real-handler
	       'rename-file (list localname1 localname2 ok-if-already-exists))))

	   ;; We can do it directly with `tramp-send-command'
	   ((and (file-readable-p (concat prefix localname1))
		 (file-writable-p
		  (file-name-directory (concat prefix localname2)))
		 (or (file-directory-p (concat prefix localname2))
		     (file-writable-p (concat prefix localname2))))
	    (tramp-do-copy-or-rename-file-directly
	     op (concat prefix localname1) (concat prefix localname2)
	     ok-if-already-exists keep-date t)
	    ;; We must change the ownership to the local user.
	    (tramp-set-file-uid-gid
	     (concat prefix localname2)
	     (tramp-get-local-uid 'integer)
	     (tramp-get-local-gid 'integer)))

	   ;; We need a temporary file in between.
	   (t
	    ;; Create the temporary file.
	    (let ((tmpfile (tramp-compat-make-temp-file localname1)))
	      (unwind-protect
		  (progn
		    (cond
		     (t1
		      (tramp-barf-unless-okay
		       v (format
			  "%s %s %s" cmd
			  (tramp-shell-quote-argument localname1)
			  (tramp-shell-quote-argument tmpfile))
		       "Copying directly failed, see buffer `%s' for details."
		       (tramp-get-buffer v))
		      ;; We must change the ownership as remote user.
		      ;; Since this does not work reliable, we also
		      ;; give read permissions.
		      (set-file-modes
		       (concat prefix tmpfile)
		       (tramp-compat-octal-to-decimal "0777"))
		      (tramp-set-file-uid-gid
		       (concat prefix tmpfile)
		       (tramp-get-local-uid 'integer)
		       (tramp-get-local-gid 'integer)))
		     (t2
		      (if (eq op 'copy)
			  (tramp-compat-copy-file
			   localname1 tmpfile t
			   keep-date preserve-uid-gid)
			(tramp-run-real-handler
			 'rename-file
			 (list localname1 tmpfile t)))
		      ;; We must change the ownership as local user.
		      ;; Since this does not work reliable, we also
		      ;; give read permissions.
		      (set-file-modes
		       tmpfile (tramp-compat-octal-to-decimal "0777"))
		      (tramp-set-file-uid-gid
		       tmpfile
		       (tramp-get-remote-uid v 'integer)
		       (tramp-get-remote-gid v 'integer))))

		    ;; Move the temporary file to its destination.
		    (cond
		     (t2
		      (tramp-barf-unless-okay
		       v (format
			  "cp -f -p %s %s"
			  (tramp-shell-quote-argument tmpfile)
			  (tramp-shell-quote-argument localname2))
		       "Copying directly failed, see buffer `%s' for details."
		       (tramp-get-buffer v)))
		     (t1
		      (tramp-run-real-handler
		       'rename-file
		       (list tmpfile localname2 ok-if-already-exists)))))

		;; Save exit.
Michael Albinus's avatar
Michael Albinus committed
2190
		(ignore-errors (delete-file tmpfile)))))))))
2191 2192

      ;; Set the time and mode. Mask possible errors.
Michael Albinus's avatar
Michael Albinus committed
2193
      (ignore-errors
2194 2195
	  (when keep-date
	    (set-file-times newname file-times)
Michael Albinus's avatar
Michael Albinus committed
2196
	    (set-file-modes newname file-modes))))))
2197 2198 2199 2200

(defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
  "Invoke rcp program to copy.
The method used must be an out-of-band method."
2201 2202 2203 2204 2205
  (let* ((t1 (tramp-tramp-file-p filename))
	 (t2 (tramp-tramp-file-p newname))
	 (orig-vec (tramp-dissect-file-name (if t1 filename newname)))
	 copy-program copy-args copy-env copy-keep-date port spec
	 source target)
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224

    (with-parsed-tramp-file-name (if t1 filename newname) nil
      (if (and t1 t2)

	  ;; Both are Tramp files.  We shall optimize it, when the
	  ;; methods for filename and newname are the same.
	  (let* ((dir-flag (file-directory-p filename))
		 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
	    (if dir-flag
		(setq tmpfile
		      (expand-file-name
		       (file-name-nondirectory newname) tmpfile)))
	    (unwind-protect
		(progn
		  (tramp-do-copy-or-rename-file-out-of-band
		   op filename tmpfile keep-date)
		  (tramp-do-copy-or-rename-file-out-of-band
		   'rename tmpfile newname keep-date))
	      ;; Save exit.
Michael Albinus's avatar
Michael Albinus committed
2225 2226 2227 2228 2229
	      (ignore-errors
		(if dir-flag
		    (tramp-compat-delete-directory
		     (expand-file-name ".." tmpfile) 'recursive)
		  (delete-file tmpfile)))))
2230

2231 2232 2233 2234 2235 2236
	;; Set variables for computing the prompt for reading
	;; password.
	(setq tramp-current-method (tramp-file-name-method v)
	      tramp-current-user   (tramp-file-name-user v)
	      tramp-current-host   (tramp-file-name-host v))

2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
	;; Expand hops.  Might be necessary for gateway methods.
	(setq v (car (tramp-compute-multi-hops v)))
	(aset v 3 localname)

	;; Check which ones of source and target are Tramp files.
	(setq source (if t1 (tramp-make-copy-program-file-name v) filename)
	      target (funcall
		      (if (and (file-directory-p filename)
			       (string-equal
				(file-name-nondirectory filename)
				(file-name-nondirectory newname)))
			  'file-name-directory
			'identity)
		      (if t2 (tramp-make-copy-program-file-name v) newname)))

	;; Check for port number.  Until now, there's no need for handling
	;; like method, user, host.
	(setq host (tramp-file-name-real-host v)
	      port (tramp-file-name-port v)
	      port (or (and port (number-to-string port)) ""))

	;; Compose copy command.
	(setq spec (format-spec-make
		    ?h host ?u user ?p port
		    ?t (tramp-get-connection-property
			(tramp-get-connection-process v) "temp-file" "")
		    ?k (if keep-date " " ""))
	      copy-program (tramp-get-method-parameter
			    method 'tramp-copy-program)
	      copy-keep-date (tramp-get-method-parameter
			      method 'tramp-copy-keep-date)
	      copy-args
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
	      (delete
	       ;; " " has either been a replacement of "%k" (when
	       ;; keep-date argument is non-nil), or a replacemtent
	       ;; for the whole keep-date sublist.
	       " "
	       (dolist
		   (x
		    (tramp-get-method-parameter method 'tramp-copy-args)
		    copy-args)
		 (setq copy-args
		       (append
			copy-args
			(let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
			  (if (zerop (length (ca