scp.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757
  1. /* $OpenBSD: scp.c,v 1.212 2020/08/03 02:43:41 djm Exp $ */
  2. /*
  3. * scp - secure remote copy. This is basically patched BSD rcp which
  4. * uses ssh to do the data transfer (instead of using rcmd).
  5. *
  6. * NOTE: This version should NOT be suid root. (This uses ssh to
  7. * do the transfer and ssh has the necessary privileges.)
  8. *
  9. * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
  10. *
  11. * As far as I am concerned, the code I have written for this software
  12. * can be used freely for any purpose. Any derived versions of this
  13. * software must be clearly marked as such, and if the derived work is
  14. * incompatible with the protocol description in the RFC file, it must be
  15. * called by a name other than "ssh" or "Secure Shell".
  16. */
  17. /*
  18. * Copyright (c) 1999 Theo de Raadt. All rights reserved.
  19. * Copyright (c) 1999 Aaron Campbell. All rights reserved.
  20. *
  21. * Redistribution and use in source and binary forms, with or without
  22. * modification, are permitted provided that the following conditions
  23. * are met:
  24. * 1. Redistributions of source code must retain the above copyright
  25. * notice, this list of conditions and the following disclaimer.
  26. * 2. Redistributions in binary form must reproduce the above copyright
  27. * notice, this list of conditions and the following disclaimer in the
  28. * documentation and/or other materials provided with the distribution.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  31. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  33. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  34. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  35. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  36. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  37. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  38. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  39. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  40. */
  41. /*
  42. * Parts from:
  43. *
  44. * Copyright (c) 1983, 1990, 1992, 1993, 1995
  45. * The Regents of the University of California. All rights reserved.
  46. *
  47. * Redistribution and use in source and binary forms, with or without
  48. * modification, are permitted provided that the following conditions
  49. * are met:
  50. * 1. Redistributions of source code must retain the above copyright
  51. * notice, this list of conditions and the following disclaimer.
  52. * 2. Redistributions in binary form must reproduce the above copyright
  53. * notice, this list of conditions and the following disclaimer in the
  54. * documentation and/or other materials provided with the distribution.
  55. * 3. Neither the name of the University nor the names of its contributors
  56. * may be used to endorse or promote products derived from this software
  57. * without specific prior written permission.
  58. *
  59. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  60. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  61. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  62. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  63. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  64. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  65. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  66. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  67. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  68. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  69. * SUCH DAMAGE.
  70. *
  71. */
  72. #include "includes.h"
  73. #include <sys/types.h>
  74. #ifdef HAVE_SYS_STAT_H
  75. # include <sys/stat.h>
  76. #endif
  77. #ifdef HAVE_POLL_H
  78. #include <poll.h>
  79. #else
  80. # ifdef HAVE_SYS_POLL_H
  81. # include <sys/poll.h>
  82. # endif
  83. #endif
  84. #ifdef HAVE_SYS_TIME_H
  85. # include <sys/time.h>
  86. #endif
  87. #include <sys/wait.h>
  88. #include <sys/uio.h>
  89. #include <ctype.h>
  90. #include <dirent.h>
  91. #include <errno.h>
  92. #include <fcntl.h>
  93. #ifdef HAVE_FNMATCH_H
  94. #include <fnmatch.h>
  95. #endif
  96. #include <limits.h>
  97. #include <locale.h>
  98. #include <pwd.h>
  99. #include <signal.h>
  100. #include <stdarg.h>
  101. #ifdef HAVE_STDINT_H
  102. # include <stdint.h>
  103. #endif
  104. #include <stdio.h>
  105. #include <stdlib.h>
  106. #include <string.h>
  107. #include <time.h>
  108. #include <unistd.h>
  109. #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
  110. #include <vis.h>
  111. #endif
  112. #include "xmalloc.h"
  113. #include "ssh.h"
  114. #include "atomicio.h"
  115. #include "pathnames.h"
  116. #include "log.h"
  117. #include "misc.h"
  118. #include "progressmeter.h"
  119. #include "utf8.h"
  120. extern char *__progname;
  121. #define COPY_BUFLEN 16384
  122. int do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout);
  123. int do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout);
  124. /* Struct for addargs */
  125. arglist args;
  126. arglist remote_remote_args;
  127. /* Bandwidth limit */
  128. long long limit_kbps = 0;
  129. struct bwlimit bwlimit;
  130. /* Name of current file being transferred. */
  131. char *curfile;
  132. /* This is set to non-zero to enable verbose mode. */
  133. int verbose_mode = 0;
  134. /* This is set to zero if the progressmeter is not desired. */
  135. int showprogress = 1;
  136. /*
  137. * This is set to non-zero if remote-remote copy should be piped
  138. * through this process.
  139. */
  140. int throughlocal = 0;
  141. /* Non-standard port to use for the ssh connection or -1. */
  142. int sshport = -1;
  143. /* This is the program to execute for the secured connection. ("ssh" or -S) */
  144. char *ssh_program = _PATH_SSH_PROGRAM;
  145. /* This is used to store the pid of ssh_program */
  146. pid_t do_cmd_pid = -1;
  147. static void
  148. killchild(int signo)
  149. {
  150. if (do_cmd_pid > 1) {
  151. kill(do_cmd_pid, signo ? signo : SIGTERM);
  152. (void) waitpid(do_cmd_pid, NULL, 0);
  153. }
  154. if (signo)
  155. _exit(1);
  156. exit(1);
  157. }
  158. static void
  159. suspchild(int signo)
  160. {
  161. int status;
  162. if (do_cmd_pid > 1) {
  163. kill(do_cmd_pid, signo);
  164. while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
  165. errno == EINTR)
  166. ;
  167. kill(getpid(), SIGSTOP);
  168. }
  169. }
  170. static int
  171. do_local_cmd(arglist *a)
  172. {
  173. u_int i;
  174. int status;
  175. pid_t pid;
  176. if (a->num == 0)
  177. fatal("do_local_cmd: no arguments");
  178. if (verbose_mode) {
  179. fprintf(stderr, "Executing:");
  180. for (i = 0; i < a->num; i++) {
  181. if (i == 0)
  182. fmprintf(stderr, " %s", a->list[i]);
  183. else
  184. /*
  185. * TODO: misbehaves if a->list[i] contains a
  186. * single quote
  187. */
  188. fmprintf(stderr, " '%s'", a->list[i]);
  189. }
  190. fprintf(stderr, "\n");
  191. }
  192. if ((pid = fork()) == -1)
  193. fatal("do_local_cmd: fork: %s", strerror(errno));
  194. if (pid == 0) {
  195. execvp(a->list[0], a->list);
  196. perror(a->list[0]);
  197. exit(1);
  198. }
  199. do_cmd_pid = pid;
  200. ssh_signal(SIGTERM, killchild);
  201. ssh_signal(SIGINT, killchild);
  202. ssh_signal(SIGHUP, killchild);
  203. while (waitpid(pid, &status, 0) == -1)
  204. if (errno != EINTR)
  205. fatal("do_local_cmd: waitpid: %s", strerror(errno));
  206. do_cmd_pid = -1;
  207. if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
  208. return (-1);
  209. return (0);
  210. }
  211. /*
  212. * This function executes the given command as the specified user on the
  213. * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
  214. * assigns the input and output file descriptors on success.
  215. */
  216. int
  217. do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout)
  218. {
  219. int pin[2], pout[2], reserved[2];
  220. if (verbose_mode)
  221. fmprintf(stderr,
  222. "Executing: program %s host %s, user %s, command %s\n",
  223. ssh_program, host,
  224. remuser ? remuser : "(unspecified)", cmd);
  225. if (port == -1)
  226. port = sshport;
  227. /*
  228. * Reserve two descriptors so that the real pipes won't get
  229. * descriptors 0 and 1 because that will screw up dup2 below.
  230. */
  231. if (pipe(reserved) == -1)
  232. fatal("pipe: %s", strerror(errno));
  233. /* Create a socket pair for communicating with ssh. */
  234. if (pipe(pin) == -1)
  235. fatal("pipe: %s", strerror(errno));
  236. if (pipe(pout) == -1)
  237. fatal("pipe: %s", strerror(errno));
  238. /* Free the reserved descriptors. */
  239. close(reserved[0]);
  240. close(reserved[1]);
  241. ssh_signal(SIGTSTP, suspchild);
  242. ssh_signal(SIGTTIN, suspchild);
  243. ssh_signal(SIGTTOU, suspchild);
  244. /* Fork a child to execute the command on the remote host using ssh. */
  245. do_cmd_pid = fork();
  246. if (do_cmd_pid == 0) {
  247. /* Child. */
  248. close(pin[1]);
  249. close(pout[0]);
  250. dup2(pin[0], 0);
  251. dup2(pout[1], 1);
  252. close(pin[0]);
  253. close(pout[1]);
  254. replacearg(&args, 0, "%s", ssh_program);
  255. if (port != -1) {
  256. addargs(&args, "-p");
  257. addargs(&args, "%d", port);
  258. }
  259. if (remuser != NULL) {
  260. addargs(&args, "-l");
  261. addargs(&args, "%s", remuser);
  262. }
  263. addargs(&args, "--");
  264. addargs(&args, "%s", host);
  265. addargs(&args, "%s", cmd);
  266. execvp(ssh_program, args.list);
  267. perror(ssh_program);
  268. exit(1);
  269. } else if (do_cmd_pid == -1) {
  270. fatal("fork: %s", strerror(errno));
  271. }
  272. /* Parent. Close the other side, and return the local side. */
  273. close(pin[0]);
  274. *fdout = pin[1];
  275. close(pout[1]);
  276. *fdin = pout[0];
  277. ssh_signal(SIGTERM, killchild);
  278. ssh_signal(SIGINT, killchild);
  279. ssh_signal(SIGHUP, killchild);
  280. return 0;
  281. }
  282. /*
  283. * This function executes a command similar to do_cmd(), but expects the
  284. * input and output descriptors to be setup by a previous call to do_cmd().
  285. * This way the input and output of two commands can be connected.
  286. */
  287. int
  288. do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout)
  289. {
  290. pid_t pid;
  291. int status;
  292. if (verbose_mode)
  293. fmprintf(stderr,
  294. "Executing: 2nd program %s host %s, user %s, command %s\n",
  295. ssh_program, host,
  296. remuser ? remuser : "(unspecified)", cmd);
  297. if (port == -1)
  298. port = sshport;
  299. /* Fork a child to execute the command on the remote host using ssh. */
  300. pid = fork();
  301. if (pid == 0) {
  302. dup2(fdin, 0);
  303. dup2(fdout, 1);
  304. replacearg(&args, 0, "%s", ssh_program);
  305. if (port != -1) {
  306. addargs(&args, "-p");
  307. addargs(&args, "%d", port);
  308. }
  309. if (remuser != NULL) {
  310. addargs(&args, "-l");
  311. addargs(&args, "%s", remuser);
  312. }
  313. addargs(&args, "-oBatchMode=yes");
  314. addargs(&args, "--");
  315. addargs(&args, "%s", host);
  316. addargs(&args, "%s", cmd);
  317. execvp(ssh_program, args.list);
  318. perror(ssh_program);
  319. exit(1);
  320. } else if (pid == -1) {
  321. fatal("fork: %s", strerror(errno));
  322. }
  323. while (waitpid(pid, &status, 0) == -1)
  324. if (errno != EINTR)
  325. fatal("do_cmd2: waitpid: %s", strerror(errno));
  326. return 0;
  327. }
  328. typedef struct {
  329. size_t cnt;
  330. char *buf;
  331. } BUF;
  332. BUF *allocbuf(BUF *, int, int);
  333. void lostconn(int);
  334. int okname(char *);
  335. void run_err(const char *,...)
  336. __attribute__((__format__ (printf, 1, 2)))
  337. __attribute__((__nonnull__ (1)));
  338. int note_err(const char *,...)
  339. __attribute__((__format__ (printf, 1, 2)));
  340. void verifydir(char *);
  341. struct passwd *pwd;
  342. uid_t userid;
  343. int errs, remin, remout;
  344. int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
  345. #define CMDNEEDS 64
  346. char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
  347. int response(void);
  348. void rsource(char *, struct stat *);
  349. void sink(int, char *[], const char *);
  350. void source(int, char *[]);
  351. void tolocal(int, char *[]);
  352. void toremote(int, char *[]);
  353. void usage(void);
  354. int
  355. main(int argc, char **argv)
  356. {
  357. int ch, fflag, tflag, status, n;
  358. char **newargv;
  359. const char *errstr;
  360. extern char *optarg;
  361. extern int optind;
  362. /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
  363. sanitise_stdfd();
  364. seed_rng();
  365. msetlocale();
  366. /* Copy argv, because we modify it */
  367. newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
  368. for (n = 0; n < argc; n++)
  369. newargv[n] = xstrdup(argv[n]);
  370. argv = newargv;
  371. __progname = ssh_get_progname(argv[0]);
  372. memset(&args, '\0', sizeof(args));
  373. memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
  374. args.list = remote_remote_args.list = NULL;
  375. addargs(&args, "%s", ssh_program);
  376. addargs(&args, "-x");
  377. addargs(&args, "-oPermitLocalCommand=no");
  378. addargs(&args, "-oClearAllForwardings=yes");
  379. addargs(&args, "-oRemoteCommand=none");
  380. addargs(&args, "-oRequestTTY=no");
  381. fflag = Tflag = tflag = 0;
  382. while ((ch = getopt(argc, argv,
  383. "12346ABCTdfpqrtvF:J:P:S:c:i:l:o:")) != -1) {
  384. switch (ch) {
  385. /* User-visible flags. */
  386. case '1':
  387. fatal("SSH protocol v.1 is no longer supported");
  388. break;
  389. case '2':
  390. /* Ignored */
  391. break;
  392. case 'A':
  393. case '4':
  394. case '6':
  395. case 'C':
  396. addargs(&args, "-%c", ch);
  397. addargs(&remote_remote_args, "-%c", ch);
  398. break;
  399. case '3':
  400. throughlocal = 1;
  401. break;
  402. case 'o':
  403. case 'c':
  404. case 'i':
  405. case 'F':
  406. case 'J':
  407. addargs(&remote_remote_args, "-%c", ch);
  408. addargs(&remote_remote_args, "%s", optarg);
  409. addargs(&args, "-%c", ch);
  410. addargs(&args, "%s", optarg);
  411. break;
  412. case 'P':
  413. sshport = a2port(optarg);
  414. if (sshport <= 0)
  415. fatal("bad port \"%s\"\n", optarg);
  416. break;
  417. case 'B':
  418. addargs(&remote_remote_args, "-oBatchmode=yes");
  419. addargs(&args, "-oBatchmode=yes");
  420. break;
  421. case 'l':
  422. limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
  423. &errstr);
  424. if (errstr != NULL)
  425. usage();
  426. limit_kbps *= 1024; /* kbps */
  427. bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
  428. break;
  429. case 'p':
  430. pflag = 1;
  431. break;
  432. case 'r':
  433. iamrecursive = 1;
  434. break;
  435. case 'S':
  436. ssh_program = xstrdup(optarg);
  437. break;
  438. case 'v':
  439. addargs(&args, "-v");
  440. addargs(&remote_remote_args, "-v");
  441. verbose_mode = 1;
  442. break;
  443. case 'q':
  444. addargs(&args, "-q");
  445. addargs(&remote_remote_args, "-q");
  446. showprogress = 0;
  447. break;
  448. /* Server options. */
  449. case 'd':
  450. targetshouldbedirectory = 1;
  451. break;
  452. case 'f': /* "from" */
  453. iamremote = 1;
  454. fflag = 1;
  455. break;
  456. case 't': /* "to" */
  457. iamremote = 1;
  458. tflag = 1;
  459. #ifdef HAVE_CYGWIN
  460. setmode(0, O_BINARY);
  461. #endif
  462. break;
  463. case 'T':
  464. Tflag = 1;
  465. break;
  466. default:
  467. usage();
  468. }
  469. }
  470. argc -= optind;
  471. argv += optind;
  472. /* Do this last because we want the user to be able to override it */
  473. addargs(&args, "-oForwardAgent=no");
  474. if ((pwd = getpwuid(userid = getuid())) == NULL)
  475. fatal("unknown user %u", (u_int) userid);
  476. if (!isatty(STDOUT_FILENO))
  477. showprogress = 0;
  478. if (pflag) {
  479. /* Cannot pledge: -p allows setuid/setgid files... */
  480. } else {
  481. if (pledge("stdio rpath wpath cpath fattr tty proc exec",
  482. NULL) == -1) {
  483. perror("pledge");
  484. exit(1);
  485. }
  486. }
  487. remin = STDIN_FILENO;
  488. remout = STDOUT_FILENO;
  489. if (fflag) {
  490. /* Follow "protocol", send data. */
  491. (void) response();
  492. source(argc, argv);
  493. exit(errs != 0);
  494. }
  495. if (tflag) {
  496. /* Receive data. */
  497. sink(argc, argv, NULL);
  498. exit(errs != 0);
  499. }
  500. if (argc < 2)
  501. usage();
  502. if (argc > 2)
  503. targetshouldbedirectory = 1;
  504. remin = remout = -1;
  505. do_cmd_pid = -1;
  506. /* Command to be executed on remote system using "ssh". */
  507. (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
  508. verbose_mode ? " -v" : "",
  509. iamrecursive ? " -r" : "", pflag ? " -p" : "",
  510. targetshouldbedirectory ? " -d" : "");
  511. (void) ssh_signal(SIGPIPE, lostconn);
  512. if (colon(argv[argc - 1])) /* Dest is remote host. */
  513. toremote(argc, argv);
  514. else {
  515. if (targetshouldbedirectory)
  516. verifydir(argv[argc - 1]);
  517. tolocal(argc, argv); /* Dest is local host. */
  518. }
  519. /*
  520. * Finally check the exit status of the ssh process, if one was forked
  521. * and no error has occurred yet
  522. */
  523. if (do_cmd_pid != -1 && errs == 0) {
  524. if (remin != -1)
  525. (void) close(remin);
  526. if (remout != -1)
  527. (void) close(remout);
  528. if (waitpid(do_cmd_pid, &status, 0) == -1)
  529. errs = 1;
  530. else {
  531. if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
  532. errs = 1;
  533. }
  534. }
  535. exit(errs != 0);
  536. }
  537. /* Callback from atomicio6 to update progress meter and limit bandwidth */
  538. static int
  539. scpio(void *_cnt, size_t s)
  540. {
  541. off_t *cnt = (off_t *)_cnt;
  542. *cnt += s;
  543. refresh_progress_meter(0);
  544. if (limit_kbps > 0)
  545. bandwidth_limit(&bwlimit, s);
  546. return 0;
  547. }
  548. static int
  549. do_times(int fd, int verb, const struct stat *sb)
  550. {
  551. /* strlen(2^64) == 20; strlen(10^6) == 7 */
  552. char buf[(20 + 7 + 2) * 2 + 2];
  553. (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
  554. (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
  555. (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
  556. if (verb) {
  557. fprintf(stderr, "File mtime %lld atime %lld\n",
  558. (long long)sb->st_mtime, (long long)sb->st_atime);
  559. fprintf(stderr, "Sending file timestamps: %s", buf);
  560. }
  561. (void) atomicio(vwrite, fd, buf, strlen(buf));
  562. return (response());
  563. }
  564. static int
  565. parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
  566. char **pathp)
  567. {
  568. int r;
  569. r = parse_uri("scp", uri, userp, hostp, portp, pathp);
  570. if (r == 0 && *pathp == NULL)
  571. *pathp = xstrdup(".");
  572. return r;
  573. }
  574. /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
  575. static int
  576. append(char *cp, char ***ap, size_t *np)
  577. {
  578. char **tmp;
  579. if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
  580. return -1;
  581. tmp[(*np)] = cp;
  582. (*np)++;
  583. *ap = tmp;
  584. return 0;
  585. }
  586. /*
  587. * Finds the start and end of the first brace pair in the pattern.
  588. * returns 0 on success or -1 for invalid patterns.
  589. */
  590. static int
  591. find_brace(const char *pattern, int *startp, int *endp)
  592. {
  593. int i;
  594. int in_bracket, brace_level;
  595. *startp = *endp = -1;
  596. in_bracket = brace_level = 0;
  597. for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) {
  598. switch (pattern[i]) {
  599. case '\\':
  600. /* skip next character */
  601. if (pattern[i + 1] != '\0')
  602. i++;
  603. break;
  604. case '[':
  605. in_bracket = 1;
  606. break;
  607. case ']':
  608. in_bracket = 0;
  609. break;
  610. case '{':
  611. if (in_bracket)
  612. break;
  613. if (pattern[i + 1] == '}') {
  614. /* Protect a single {}, for find(1), like csh */
  615. i++; /* skip */
  616. break;
  617. }
  618. if (*startp == -1)
  619. *startp = i;
  620. brace_level++;
  621. break;
  622. case '}':
  623. if (in_bracket)
  624. break;
  625. if (*startp < 0) {
  626. /* Unbalanced brace */
  627. return -1;
  628. }
  629. if (--brace_level <= 0)
  630. *endp = i;
  631. break;
  632. }
  633. }
  634. /* unbalanced brackets/braces */
  635. if (*endp < 0 && (*startp >= 0 || in_bracket))
  636. return -1;
  637. return 0;
  638. }
  639. /*
  640. * Assembles and records a successfully-expanded pattern, returns -1 on
  641. * alloc failure.
  642. */
  643. static int
  644. emit_expansion(const char *pattern, int brace_start, int brace_end,
  645. int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
  646. {
  647. char *cp;
  648. int o = 0, tail_len = strlen(pattern + brace_end + 1);
  649. if ((cp = malloc(brace_start + (sel_end - sel_start) +
  650. tail_len + 1)) == NULL)
  651. return -1;
  652. /* Pattern before initial brace */
  653. if (brace_start > 0) {
  654. memcpy(cp, pattern, brace_start);
  655. o = brace_start;
  656. }
  657. /* Current braced selection */
  658. if (sel_end - sel_start > 0) {
  659. memcpy(cp + o, pattern + sel_start,
  660. sel_end - sel_start);
  661. o += sel_end - sel_start;
  662. }
  663. /* Remainder of pattern after closing brace */
  664. if (tail_len > 0) {
  665. memcpy(cp + o, pattern + brace_end + 1, tail_len);
  666. o += tail_len;
  667. }
  668. cp[o] = '\0';
  669. if (append(cp, patternsp, npatternsp) != 0) {
  670. free(cp);
  671. return -1;
  672. }
  673. return 0;
  674. }
  675. /*
  676. * Expand the first encountered brace in pattern, appending the expanded
  677. * patterns it yielded to the *patternsp array.
  678. *
  679. * Returns 0 on success or -1 on allocation failure.
  680. *
  681. * Signals whether expansion was performed via *expanded and whether
  682. * pattern was invalid via *invalid.
  683. */
  684. static int
  685. brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
  686. int *expanded, int *invalid)
  687. {
  688. int i;
  689. int in_bracket, brace_start, brace_end, brace_level;
  690. int sel_start, sel_end;
  691. *invalid = *expanded = 0;
  692. if (find_brace(pattern, &brace_start, &brace_end) != 0) {
  693. *invalid = 1;
  694. return 0;
  695. } else if (brace_start == -1)
  696. return 0;
  697. in_bracket = brace_level = 0;
  698. for (i = sel_start = brace_start + 1; i < brace_end; i++) {
  699. switch (pattern[i]) {
  700. case '{':
  701. if (in_bracket)
  702. break;
  703. brace_level++;
  704. break;
  705. case '}':
  706. if (in_bracket)
  707. break;
  708. brace_level--;
  709. break;
  710. case '[':
  711. in_bracket = 1;
  712. break;
  713. case ']':
  714. in_bracket = 0;
  715. break;
  716. case '\\':
  717. if (i < brace_end - 1)
  718. i++; /* skip */
  719. break;
  720. }
  721. if (pattern[i] == ',' || i == brace_end - 1) {
  722. if (in_bracket || brace_level > 0)
  723. continue;
  724. /* End of a selection, emit an expanded pattern */
  725. /* Adjust end index for last selection */
  726. sel_end = (i == brace_end - 1) ? brace_end : i;
  727. if (emit_expansion(pattern, brace_start, brace_end,
  728. sel_start, sel_end, patternsp, npatternsp) != 0)
  729. return -1;
  730. /* move on to the next selection */
  731. sel_start = i + 1;
  732. continue;
  733. }
  734. }
  735. if (in_bracket || brace_level > 0) {
  736. *invalid = 1;
  737. return 0;
  738. }
  739. /* success */
  740. *expanded = 1;
  741. return 0;
  742. }
  743. /* Expand braces from pattern. Returns 0 on success, -1 on failure */
  744. static int
  745. brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
  746. {
  747. char *cp, *cp2, **active = NULL, **done = NULL;
  748. size_t i, nactive = 0, ndone = 0;
  749. int ret = -1, invalid = 0, expanded = 0;
  750. *patternsp = NULL;
  751. *npatternsp = 0;
  752. /* Start the worklist with the original pattern */
  753. if ((cp = strdup(pattern)) == NULL)
  754. return -1;
  755. if (append(cp, &active, &nactive) != 0) {
  756. free(cp);
  757. return -1;
  758. }
  759. while (nactive > 0) {
  760. cp = active[nactive - 1];
  761. nactive--;
  762. if (brace_expand_one(cp, &active, &nactive,
  763. &expanded, &invalid) == -1) {
  764. free(cp);
  765. goto fail;
  766. }
  767. if (invalid)
  768. fatal("%s: invalid brace pattern \"%s\"", __func__, cp);
  769. if (expanded) {
  770. /*
  771. * Current entry expanded to new entries on the
  772. * active list; discard the progenitor pattern.
  773. */
  774. free(cp);
  775. continue;
  776. }
  777. /*
  778. * Pattern did not expand; append the finename component to
  779. * the completed list
  780. */
  781. if ((cp2 = strrchr(cp, '/')) != NULL)
  782. *cp2++ = '\0';
  783. else
  784. cp2 = cp;
  785. if (append(xstrdup(cp2), &done, &ndone) != 0) {
  786. free(cp);
  787. goto fail;
  788. }
  789. free(cp);
  790. }
  791. /* success */
  792. *patternsp = done;
  793. *npatternsp = ndone;
  794. done = NULL;
  795. ndone = 0;
  796. ret = 0;
  797. fail:
  798. for (i = 0; i < nactive; i++)
  799. free(active[i]);
  800. free(active);
  801. for (i = 0; i < ndone; i++)
  802. free(done[i]);
  803. free(done);
  804. return ret;
  805. }
  806. void
  807. toremote(int argc, char **argv)
  808. {
  809. char *suser = NULL, *host = NULL, *src = NULL;
  810. char *bp, *tuser, *thost, *targ;
  811. int sport = -1, tport = -1;
  812. arglist alist;
  813. int i, r;
  814. u_int j;
  815. memset(&alist, '\0', sizeof(alist));
  816. alist.list = NULL;
  817. /* Parse target */
  818. r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
  819. if (r == -1) {
  820. fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
  821. ++errs;
  822. goto out;
  823. }
  824. if (r != 0) {
  825. if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
  826. &targ) == -1) {
  827. fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
  828. ++errs;
  829. goto out;
  830. }
  831. }
  832. if (tuser != NULL && !okname(tuser)) {
  833. ++errs;
  834. goto out;
  835. }
  836. /* Parse source files */
  837. for (i = 0; i < argc - 1; i++) {
  838. free(suser);
  839. free(host);
  840. free(src);
  841. r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
  842. if (r == -1) {
  843. fmprintf(stderr, "%s: invalid uri\n", argv[i]);
  844. ++errs;
  845. continue;
  846. }
  847. if (r != 0) {
  848. parse_user_host_path(argv[i], &suser, &host, &src);
  849. }
  850. if (suser != NULL && !okname(suser)) {
  851. ++errs;
  852. continue;
  853. }
  854. if (host && throughlocal) { /* extended remote to remote */
  855. xasprintf(&bp, "%s -f %s%s", cmd,
  856. *src == '-' ? "-- " : "", src);
  857. if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
  858. exit(1);
  859. free(bp);
  860. xasprintf(&bp, "%s -t %s%s", cmd,
  861. *targ == '-' ? "-- " : "", targ);
  862. if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
  863. exit(1);
  864. free(bp);
  865. (void) close(remin);
  866. (void) close(remout);
  867. remin = remout = -1;
  868. } else if (host) { /* standard remote to remote */
  869. if (tport != -1 && tport != SSH_DEFAULT_PORT) {
  870. /* This would require the remote support URIs */
  871. fatal("target port not supported with two "
  872. "remote hosts without the -3 option");
  873. }
  874. freeargs(&alist);
  875. addargs(&alist, "%s", ssh_program);
  876. addargs(&alist, "-x");
  877. addargs(&alist, "-oClearAllForwardings=yes");
  878. if (isatty(fileno(stdin)))
  879. addargs(&alist, "-t");
  880. else
  881. addargs(&alist, "-n");
  882. for (j = 0; j < remote_remote_args.num; j++) {
  883. addargs(&alist, "%s",
  884. remote_remote_args.list[j]);
  885. }
  886. if (sport != -1) {
  887. addargs(&alist, "-p");
  888. addargs(&alist, "%d", sport);
  889. }
  890. if (suser) {
  891. addargs(&alist, "-l");
  892. addargs(&alist, "%s", suser);
  893. }
  894. addargs(&alist, "--");
  895. addargs(&alist, "%s", host);
  896. addargs(&alist, "%s", cmd);
  897. addargs(&alist, "%s", src);
  898. addargs(&alist,
  899. /* IPv6 address needs to be enclosed with sqare brackets */
  900. strchr(host, ':') != NULL ? "%s%s[%s]:%s" : "%s%s%s:%s",
  901. tuser ? tuser : "", tuser ? "@" : "",
  902. thost, targ);
  903. if (do_local_cmd(&alist) != 0)
  904. errs = 1;
  905. } else { /* local to remote */
  906. if (remin == -1) {
  907. xasprintf(&bp, "%s -t %s%s", cmd,
  908. *targ == '-' ? "-- " : "", targ);
  909. if (do_cmd(thost, tuser, tport, bp, &remin,
  910. &remout) < 0)
  911. exit(1);
  912. if (response() < 0)
  913. exit(1);
  914. free(bp);
  915. }
  916. source(1, argv + i);
  917. }
  918. }
  919. out:
  920. free(tuser);
  921. free(thost);
  922. free(targ);
  923. free(suser);
  924. free(host);
  925. free(src);
  926. }
  927. void
  928. tolocal(int argc, char **argv)
  929. {
  930. char *bp, *host = NULL, *src = NULL, *suser = NULL;
  931. arglist alist;
  932. int i, r, sport = -1;
  933. memset(&alist, '\0', sizeof(alist));
  934. alist.list = NULL;
  935. for (i = 0; i < argc - 1; i++) {
  936. free(suser);
  937. free(host);
  938. free(src);
  939. r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
  940. if (r == -1) {
  941. fmprintf(stderr, "%s: invalid uri\n", argv[i]);
  942. ++errs;
  943. continue;
  944. }
  945. if (r != 0)
  946. parse_user_host_path(argv[i], &suser, &host, &src);
  947. if (suser != NULL && !okname(suser)) {
  948. ++errs;
  949. continue;
  950. }
  951. if (!host) { /* Local to local. */
  952. freeargs(&alist);
  953. addargs(&alist, "%s", _PATH_CP);
  954. if (iamrecursive)
  955. addargs(&alist, "-r");
  956. if (pflag)
  957. addargs(&alist, "-p");
  958. addargs(&alist, "--");
  959. addargs(&alist, "%s", argv[i]);
  960. addargs(&alist, "%s", argv[argc-1]);
  961. if (do_local_cmd(&alist))
  962. ++errs;
  963. continue;
  964. }
  965. /* Remote to local. */
  966. xasprintf(&bp, "%s -f %s%s",
  967. cmd, *src == '-' ? "-- " : "", src);
  968. if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
  969. free(bp);
  970. ++errs;
  971. continue;
  972. }
  973. free(bp);
  974. sink(1, argv + argc - 1, src);
  975. (void) close(remin);
  976. remin = remout = -1;
  977. }
  978. free(suser);
  979. free(host);
  980. free(src);
  981. }
  982. void
  983. source(int argc, char **argv)
  984. {
  985. struct stat stb;
  986. static BUF buffer;
  987. BUF *bp;
  988. off_t i, statbytes;
  989. size_t amt, nr;
  990. int fd = -1, haderr, indx;
  991. char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
  992. int len;
  993. for (indx = 0; indx < argc; ++indx) {
  994. name = argv[indx];
  995. statbytes = 0;
  996. len = strlen(name);
  997. while (len > 1 && name[len-1] == '/')
  998. name[--len] = '\0';
  999. if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) == -1)
  1000. goto syserr;
  1001. if (strchr(name, '\n') != NULL) {
  1002. strnvis(encname, name, sizeof(encname), VIS_NL);
  1003. name = encname;
  1004. }
  1005. if (fstat(fd, &stb) == -1) {
  1006. syserr: run_err("%s: %s", name, strerror(errno));
  1007. goto next;
  1008. }
  1009. if (stb.st_size < 0) {
  1010. run_err("%s: %s", name, "Negative file size");
  1011. goto next;
  1012. }
  1013. unset_nonblock(fd);
  1014. switch (stb.st_mode & S_IFMT) {
  1015. case S_IFREG:
  1016. break;
  1017. case S_IFDIR:
  1018. if (iamrecursive) {
  1019. rsource(name, &stb);
  1020. goto next;
  1021. }
  1022. /* FALLTHROUGH */
  1023. default:
  1024. run_err("%s: not a regular file", name);
  1025. goto next;
  1026. }
  1027. if ((last = strrchr(name, '/')) == NULL)
  1028. last = name;
  1029. else
  1030. ++last;
  1031. curfile = last;
  1032. if (pflag) {
  1033. if (do_times(remout, verbose_mode, &stb) < 0)
  1034. goto next;
  1035. }
  1036. #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
  1037. snprintf(buf, sizeof buf, "C%04o %lld %s\n",
  1038. (u_int) (stb.st_mode & FILEMODEMASK),
  1039. (long long)stb.st_size, last);
  1040. if (verbose_mode)
  1041. fmprintf(stderr, "Sending file modes: %s", buf);
  1042. (void) atomicio(vwrite, remout, buf, strlen(buf));
  1043. if (response() < 0)
  1044. goto next;
  1045. if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
  1046. next: if (fd != -1) {
  1047. (void) close(fd);
  1048. fd = -1;
  1049. }
  1050. continue;
  1051. }
  1052. if (showprogress)
  1053. start_progress_meter(curfile, stb.st_size, &statbytes);
  1054. set_nonblock(remout);
  1055. for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
  1056. amt = bp->cnt;
  1057. if (i + (off_t)amt > stb.st_size)
  1058. amt = stb.st_size - i;
  1059. if (!haderr) {
  1060. if ((nr = atomicio(read, fd,
  1061. bp->buf, amt)) != amt) {
  1062. haderr = errno;
  1063. memset(bp->buf + nr, 0, amt - nr);
  1064. }
  1065. }
  1066. /* Keep writing after error to retain sync */
  1067. if (haderr) {
  1068. (void)atomicio(vwrite, remout, bp->buf, amt);
  1069. memset(bp->buf, 0, amt);
  1070. continue;
  1071. }
  1072. if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
  1073. &statbytes) != amt)
  1074. haderr = errno;
  1075. }
  1076. unset_nonblock(remout);
  1077. if (fd != -1) {
  1078. if (close(fd) == -1 && !haderr)
  1079. haderr = errno;
  1080. fd = -1;
  1081. }
  1082. if (!haderr)
  1083. (void) atomicio(vwrite, remout, "", 1);
  1084. else
  1085. run_err("%s: %s", name, strerror(haderr));
  1086. (void) response();
  1087. if (showprogress)
  1088. stop_progress_meter();
  1089. }
  1090. }
  1091. void
  1092. rsource(char *name, struct stat *statp)
  1093. {
  1094. DIR *dirp;
  1095. struct dirent *dp;
  1096. char *last, *vect[1], path[PATH_MAX];
  1097. if (!(dirp = opendir(name))) {
  1098. run_err("%s: %s", name, strerror(errno));
  1099. return;
  1100. }
  1101. last = strrchr(name, '/');
  1102. if (last == NULL)
  1103. last = name;
  1104. else
  1105. last++;
  1106. if (pflag) {
  1107. if (do_times(remout, verbose_mode, statp) < 0) {
  1108. closedir(dirp);
  1109. return;
  1110. }
  1111. }
  1112. (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
  1113. (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
  1114. if (verbose_mode)
  1115. fmprintf(stderr, "Entering directory: %s", path);
  1116. (void) atomicio(vwrite, remout, path, strlen(path));
  1117. if (response() < 0) {
  1118. closedir(dirp);
  1119. return;
  1120. }
  1121. while ((dp = readdir(dirp)) != NULL) {
  1122. if (dp->d_ino == 0)
  1123. continue;
  1124. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
  1125. continue;
  1126. if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
  1127. run_err("%s/%s: name too long", name, dp->d_name);
  1128. continue;
  1129. }
  1130. (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
  1131. vect[0] = path;
  1132. source(1, vect);
  1133. }
  1134. (void) closedir(dirp);
  1135. (void) atomicio(vwrite, remout, "E\n", 2);
  1136. (void) response();
  1137. }
  1138. #define TYPE_OVERFLOW(type, val) \
  1139. ((sizeof(type) == 4 && (val) > INT32_MAX) || \
  1140. (sizeof(type) == 8 && (val) > INT64_MAX) || \
  1141. (sizeof(type) != 4 && sizeof(type) != 8))
  1142. void
  1143. sink(int argc, char **argv, const char *src)
  1144. {
  1145. static BUF buffer;
  1146. struct stat stb;
  1147. BUF *bp;
  1148. off_t i;
  1149. size_t j, count;
  1150. int amt, exists, first, ofd;
  1151. mode_t mode, omode, mask;
  1152. off_t size, statbytes;
  1153. unsigned long long ull;
  1154. int setimes, targisdir, wrerr;
  1155. char ch, *cp, *np, *targ, *why, *vect[1], buf[16384], visbuf[16384];
  1156. char **patterns = NULL;
  1157. size_t n, npatterns = 0;
  1158. struct timeval tv[2];
  1159. #define atime tv[0]
  1160. #define mtime tv[1]
  1161. #define SCREWUP(str) { why = str; goto screwup; }
  1162. if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
  1163. SCREWUP("Unexpected off_t/time_t size");
  1164. setimes = targisdir = 0;
  1165. mask = umask(0);
  1166. if (!pflag)
  1167. (void) umask(mask);
  1168. if (argc != 1) {
  1169. run_err("ambiguous target");
  1170. exit(1);
  1171. }
  1172. targ = *argv;
  1173. if (targetshouldbedirectory)
  1174. verifydir(targ);
  1175. (void) atomicio(vwrite, remout, "", 1);
  1176. if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
  1177. targisdir = 1;
  1178. if (src != NULL && !iamrecursive && !Tflag) {
  1179. /*
  1180. * Prepare to try to restrict incoming filenames to match
  1181. * the requested destination file glob.
  1182. */
  1183. if (brace_expand(src, &patterns, &npatterns) != 0)
  1184. fatal("%s: could not expand pattern", __func__);
  1185. }
  1186. for (first = 1;; first = 0) {
  1187. cp = buf;
  1188. if (atomicio(read, remin, cp, 1) != 1)
  1189. goto done;
  1190. if (*cp++ == '\n')
  1191. SCREWUP("unexpected <newline>");
  1192. do {
  1193. if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
  1194. SCREWUP("lost connection");
  1195. *cp++ = ch;
  1196. } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
  1197. *cp = 0;
  1198. if (verbose_mode)
  1199. fmprintf(stderr, "Sink: %s", buf);
  1200. if (buf[0] == '\01' || buf[0] == '\02') {
  1201. if (iamremote == 0) {
  1202. (void) snmprintf(visbuf, sizeof(visbuf),
  1203. NULL, "%s", buf + 1);
  1204. (void) atomicio(vwrite, STDERR_FILENO,
  1205. visbuf, strlen(visbuf));
  1206. }
  1207. if (buf[0] == '\02')
  1208. exit(1);
  1209. ++errs;
  1210. continue;
  1211. }
  1212. if (buf[0] == 'E') {
  1213. (void) atomicio(vwrite, remout, "", 1);
  1214. goto done;
  1215. }
  1216. if (ch == '\n')
  1217. *--cp = 0;
  1218. cp = buf;
  1219. if (*cp == 'T') {
  1220. setimes++;
  1221. cp++;
  1222. if (!isdigit((unsigned char)*cp))
  1223. SCREWUP("mtime.sec not present");
  1224. ull = strtoull(cp, &cp, 10);
  1225. if (!cp || *cp++ != ' ')
  1226. SCREWUP("mtime.sec not delimited");
  1227. if (TYPE_OVERFLOW(time_t, ull))
  1228. setimes = 0; /* out of range */
  1229. mtime.tv_sec = ull;
  1230. mtime.tv_usec = strtol(cp, &cp, 10);
  1231. if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
  1232. mtime.tv_usec > 999999)
  1233. SCREWUP("mtime.usec not delimited");
  1234. if (!isdigit((unsigned char)*cp))
  1235. SCREWUP("atime.sec not present");
  1236. ull = strtoull(cp, &cp, 10);
  1237. if (!cp || *cp++ != ' ')
  1238. SCREWUP("atime.sec not delimited");
  1239. if (TYPE_OVERFLOW(time_t, ull))
  1240. setimes = 0; /* out of range */
  1241. atime.tv_sec = ull;
  1242. atime.tv_usec = strtol(cp, &cp, 10);
  1243. if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
  1244. atime.tv_usec > 999999)
  1245. SCREWUP("atime.usec not delimited");
  1246. (void) atomicio(vwrite, remout, "", 1);
  1247. continue;
  1248. }
  1249. if (*cp != 'C' && *cp != 'D') {
  1250. /*
  1251. * Check for the case "rcp remote:foo\* local:bar".
  1252. * In this case, the line "No match." can be returned
  1253. * by the shell before the rcp command on the remote is
  1254. * executed so the ^Aerror_message convention isn't
  1255. * followed.
  1256. */
  1257. if (first) {
  1258. run_err("%s", cp);
  1259. exit(1);
  1260. }
  1261. SCREWUP("expected control record");
  1262. }
  1263. mode = 0;
  1264. for (++cp; cp < buf + 5; cp++) {
  1265. if (*cp < '0' || *cp > '7')
  1266. SCREWUP("bad mode");
  1267. mode = (mode << 3) | (*cp - '0');
  1268. }
  1269. if (!pflag)
  1270. mode &= ~mask;
  1271. if (*cp++ != ' ')
  1272. SCREWUP("mode not delimited");
  1273. if (!isdigit((unsigned char)*cp))
  1274. SCREWUP("size not present");
  1275. ull = strtoull(cp, &cp, 10);
  1276. if (!cp || *cp++ != ' ')
  1277. SCREWUP("size not delimited");
  1278. if (TYPE_OVERFLOW(off_t, ull))
  1279. SCREWUP("size out of range");
  1280. size = (off_t)ull;
  1281. if (*cp == '\0' || strchr(cp, '/') != NULL ||
  1282. strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
  1283. run_err("error: unexpected filename: %s", cp);
  1284. exit(1);
  1285. }
  1286. if (npatterns > 0) {
  1287. for (n = 0; n < npatterns; n++) {
  1288. if (fnmatch(patterns[n], cp, 0) == 0)
  1289. break;
  1290. }
  1291. if (n >= npatterns)
  1292. SCREWUP("filename does not match request");
  1293. }
  1294. if (targisdir) {
  1295. static char *namebuf;
  1296. static size_t cursize;
  1297. size_t need;
  1298. need = strlen(targ) + strlen(cp) + 250;
  1299. if (need > cursize) {
  1300. free(namebuf);
  1301. namebuf = xmalloc(need);
  1302. cursize = need;
  1303. }
  1304. (void) snprintf(namebuf, need, "%s%s%s", targ,
  1305. strcmp(targ, "/") ? "/" : "", cp);
  1306. np = namebuf;
  1307. } else
  1308. np = targ;
  1309. curfile = cp;
  1310. exists = stat(np, &stb) == 0;
  1311. if (buf[0] == 'D') {
  1312. int mod_flag = pflag;
  1313. if (!iamrecursive)
  1314. SCREWUP("received directory without -r");
  1315. if (exists) {
  1316. if (!S_ISDIR(stb.st_mode)) {
  1317. errno = ENOTDIR;
  1318. goto bad;
  1319. }
  1320. if (pflag)
  1321. (void) chmod(np, mode);
  1322. } else {
  1323. /* Handle copying from a read-only
  1324. directory */
  1325. mod_flag = 1;
  1326. if (mkdir(np, mode | S_IRWXU) == -1)
  1327. goto bad;
  1328. }
  1329. vect[0] = xstrdup(np);
  1330. sink(1, vect, src);
  1331. if (setimes) {
  1332. setimes = 0;
  1333. (void) utimes(vect[0], tv);
  1334. }
  1335. if (mod_flag)
  1336. (void) chmod(vect[0], mode);
  1337. free(vect[0]);
  1338. continue;
  1339. }
  1340. if (buf[0] == 'C' && ! exists && np[strlen(np)-1] == '/') {
  1341. errno = ENOTDIR;
  1342. goto bad;
  1343. }
  1344. omode = mode;
  1345. mode |= S_IWUSR;
  1346. if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
  1347. bad: run_err("%s: %s", np, strerror(errno));
  1348. continue;
  1349. }
  1350. (void) atomicio(vwrite, remout, "", 1);
  1351. if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
  1352. (void) close(ofd);
  1353. continue;
  1354. }
  1355. cp = bp->buf;
  1356. wrerr = 0;
  1357. /*
  1358. * NB. do not use run_err() unless immediately followed by
  1359. * exit() below as it may send a spurious reply that might
  1360. * desyncronise us from the peer. Use note_err() instead.
  1361. */
  1362. statbytes = 0;
  1363. if (showprogress)
  1364. start_progress_meter(curfile, size, &statbytes);
  1365. set_nonblock(remin);
  1366. for (count = i = 0; i < size; i += bp->cnt) {
  1367. amt = bp->cnt;
  1368. if (i + amt > size)
  1369. amt = size - i;
  1370. count += amt;
  1371. do {
  1372. j = atomicio6(read, remin, cp, amt,
  1373. scpio, &statbytes);
  1374. if (j == 0) {
  1375. run_err("%s", j != EPIPE ?
  1376. strerror(errno) :
  1377. "dropped connection");
  1378. exit(1);
  1379. }
  1380. amt -= j;
  1381. cp += j;
  1382. } while (amt > 0);
  1383. if (count == bp->cnt) {
  1384. /* Keep reading so we stay sync'd up. */
  1385. if (!wrerr) {
  1386. if (atomicio(vwrite, ofd, bp->buf,
  1387. count) != count) {
  1388. note_err("%s: %s", np,
  1389. strerror(errno));
  1390. wrerr = 1;
  1391. }
  1392. }
  1393. count = 0;
  1394. cp = bp->buf;
  1395. }
  1396. }
  1397. unset_nonblock(remin);
  1398. if (count != 0 && !wrerr &&
  1399. atomicio(vwrite, ofd, bp->buf, count) != count) {
  1400. note_err("%s: %s", np, strerror(errno));
  1401. wrerr = 1;
  1402. }
  1403. if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
  1404. ftruncate(ofd, size) != 0)
  1405. note_err("%s: truncate: %s", np, strerror(errno));
  1406. if (pflag) {
  1407. if (exists || omode != mode)
  1408. #ifdef HAVE_FCHMOD
  1409. if (fchmod(ofd, omode)) {
  1410. #else /* HAVE_FCHMOD */
  1411. if (chmod(np, omode)) {
  1412. #endif /* HAVE_FCHMOD */
  1413. note_err("%s: set mode: %s",
  1414. np, strerror(errno));
  1415. }
  1416. } else {
  1417. if (!exists && omode != mode)
  1418. #ifdef HAVE_FCHMOD
  1419. if (fchmod(ofd, omode & ~mask)) {
  1420. #else /* HAVE_FCHMOD */
  1421. if (chmod(np, omode & ~mask)) {
  1422. #endif /* HAVE_FCHMOD */
  1423. note_err("%s: set mode: %s",
  1424. np, strerror(errno));
  1425. }
  1426. }
  1427. if (close(ofd) == -1)
  1428. note_err("%s: close: %s", np, strerror(errno));
  1429. (void) response();
  1430. if (showprogress)
  1431. stop_progress_meter();
  1432. if (setimes && !wrerr) {
  1433. setimes = 0;
  1434. if (utimes(np, tv) == -1) {
  1435. note_err("%s: set times: %s",
  1436. np, strerror(errno));
  1437. }
  1438. }
  1439. /* If no error was noted then signal success for this file */
  1440. if (note_err(NULL) == 0)
  1441. (void) atomicio(vwrite, remout, "", 1);
  1442. }
  1443. done:
  1444. for (n = 0; n < npatterns; n++)
  1445. free(patterns[n]);
  1446. free(patterns);
  1447. return;
  1448. screwup:
  1449. for (n = 0; n < npatterns; n++)
  1450. free(patterns[n]);
  1451. free(patterns);
  1452. run_err("protocol error: %s", why);
  1453. exit(1);
  1454. }
  1455. int
  1456. response(void)
  1457. {
  1458. char ch, *cp, resp, rbuf[2048], visbuf[2048];
  1459. if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
  1460. lostconn(0);
  1461. cp = rbuf;
  1462. switch (resp) {
  1463. case 0: /* ok */
  1464. return (0);
  1465. default:
  1466. *cp++ = resp;
  1467. /* FALLTHROUGH */
  1468. case 1: /* error, followed by error msg */
  1469. case 2: /* fatal error, "" */
  1470. do {
  1471. if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
  1472. lostconn(0);
  1473. *cp++ = ch;
  1474. } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
  1475. if (!iamremote) {
  1476. cp[-1] = '\0';
  1477. (void) snmprintf(visbuf, sizeof(visbuf),
  1478. NULL, "%s\n", rbuf);
  1479. (void) atomicio(vwrite, STDERR_FILENO,
  1480. visbuf, strlen(visbuf));
  1481. }
  1482. ++errs;
  1483. if (resp == 1)
  1484. return (-1);
  1485. exit(1);
  1486. }
  1487. /* NOTREACHED */
  1488. }
  1489. void
  1490. usage(void)
  1491. {
  1492. (void) fprintf(stderr,
  1493. "usage: scp [-346ABCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
  1494. " [-J destination] [-l limit] [-o ssh_option] [-P port]\n"
  1495. " [-S program] source ... target\n");
  1496. exit(1);
  1497. }
  1498. void
  1499. run_err(const char *fmt,...)
  1500. {
  1501. static FILE *fp;
  1502. va_list ap;
  1503. ++errs;
  1504. if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
  1505. (void) fprintf(fp, "%c", 0x01);
  1506. (void) fprintf(fp, "scp: ");
  1507. va_start(ap, fmt);
  1508. (void) vfprintf(fp, fmt, ap);
  1509. va_end(ap);
  1510. (void) fprintf(fp, "\n");
  1511. (void) fflush(fp);
  1512. }
  1513. if (!iamremote) {
  1514. va_start(ap, fmt);
  1515. vfmprintf(stderr, fmt, ap);
  1516. va_end(ap);
  1517. fprintf(stderr, "\n");
  1518. }
  1519. }
  1520. /*
  1521. * Notes a sink error for sending at the end of a file transfer. Returns 0 if
  1522. * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
  1523. * any active error at the end of the transfer.
  1524. */
  1525. int
  1526. note_err(const char *fmt, ...)
  1527. {
  1528. static char *emsg;
  1529. va_list ap;
  1530. /* Replay any previously-noted error */
  1531. if (fmt == NULL) {
  1532. if (emsg == NULL)
  1533. return 0;
  1534. run_err("%s", emsg);
  1535. free(emsg);
  1536. emsg = NULL;
  1537. return -1;
  1538. }
  1539. errs++;
  1540. /* Prefer first-noted error */
  1541. if (emsg != NULL)
  1542. return -1;
  1543. va_start(ap, fmt);
  1544. vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
  1545. va_end(ap);
  1546. return -1;
  1547. }
  1548. void
  1549. verifydir(char *cp)
  1550. {
  1551. struct stat stb;
  1552. if (!stat(cp, &stb)) {
  1553. if (S_ISDIR(stb.st_mode))
  1554. return;
  1555. errno = ENOTDIR;
  1556. }
  1557. run_err("%s: %s", cp, strerror(errno));
  1558. killchild(0);
  1559. }
  1560. int
  1561. okname(char *cp0)
  1562. {
  1563. int c;
  1564. char *cp;
  1565. cp = cp0;
  1566. do {
  1567. c = (int)*cp;
  1568. if (c & 0200)
  1569. goto bad;
  1570. if (!isalpha(c) && !isdigit((unsigned char)c)) {
  1571. switch (c) {
  1572. case '\'':
  1573. case '"':
  1574. case '`':
  1575. case ' ':
  1576. case '#':
  1577. goto bad;
  1578. default:
  1579. break;
  1580. }
  1581. }
  1582. } while (*++cp);
  1583. return (1);
  1584. bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
  1585. return (0);
  1586. }
  1587. BUF *
  1588. allocbuf(BUF *bp, int fd, int blksize)
  1589. {
  1590. size_t size;
  1591. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1592. struct stat stb;
  1593. if (fstat(fd, &stb) == -1) {
  1594. run_err("fstat: %s", strerror(errno));
  1595. return (0);
  1596. }
  1597. size = ROUNDUP(stb.st_blksize, blksize);
  1598. if (size == 0)
  1599. size = blksize;
  1600. #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
  1601. size = blksize;
  1602. #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
  1603. if (bp->cnt >= size)
  1604. return (bp);
  1605. bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
  1606. bp->cnt = size;
  1607. return (bp);
  1608. }
  1609. void
  1610. lostconn(int signo)
  1611. {
  1612. if (!iamremote)
  1613. (void)write(STDERR_FILENO, "lost connection\n", 16);
  1614. if (signo)
  1615. _exit(1);
  1616. else
  1617. exit(1);
  1618. }