scpserver.c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  1. /*
  2. * Server side of the old-school SCP protocol.
  3. */
  4. #include <assert.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include "putty.h"
  8. #include "ssh.h"
  9. #include "sshcr.h"
  10. #include "channel.h"
  11. #include "sftp.h"
  12. /*
  13. * I think it's worth actually documenting my understanding of what
  14. * this protocol _is_, since I don't know of any other documentation
  15. * of it anywhere.
  16. *
  17. * Format of data stream
  18. * ---------------------
  19. *
  20. * The sending side of an SCP connection - the client, if you're
  21. * uploading files, or the server if you're downloading - sends a data
  22. * stream consisting of a sequence of 'commands', or header records,
  23. * or whatever you want to call them, interleaved with file data.
  24. *
  25. * Each command starts with a letter indicating what type it is, and
  26. * ends with a \n.
  27. *
  28. * The 'C' command introduces an actual file. It is followed by an
  29. * octal file-permissions mask, then a space, then a decimal file
  30. * size, then a space, then the file name up to the termating newline.
  31. * For example, "C0644 12345 filename.txt\n" would be a plausible C
  32. * command.
  33. *
  34. * After the 'C' command, the sending side will transmit exactly as
  35. * many bytes of file data as specified by the size field in the
  36. * header line, followed by a single zero byte.
  37. *
  38. * The 'D' command introduces a subdirectory. Its format is identical
  39. * to 'C', including the size field, but the size field is sent as
  40. * zero.
  41. *
  42. * After the 'D' command, all subsequent C and D commands are taken to
  43. * indicate files that should be placed inside that subdirectory,
  44. * until a terminating 'E' command.
  45. *
  46. * The 'E' command indicates the end of a subdirectory. It has no
  47. * arguments at all (its format is always just "E\n"). After the E
  48. * command, the receiver should revert to placing further downloaded
  49. * files in whatever directory it was placing them before the
  50. * subdirectory opened by the just-closed D.
  51. *
  52. * D and E commands match like parentheses: if you send, say,
  53. *
  54. * C0644 123 foo.txt ( followed by data )
  55. * D0755 0 subdir
  56. * C0644 123 bar.txt ( followed by data )
  57. * D0755 0 subsubdir
  58. * C0644 123 baz.txt ( followed by data )
  59. * E
  60. * C0644 123 quux.txt ( followed by data )
  61. * E
  62. * C0644 123 wibble.txt ( followed by data )
  63. *
  64. * then foo.txt, subdir and wibble.txt go in the top-level destination
  65. * directory; bar.txt, subsubdir and quux.txt go in 'subdir'; and
  66. * baz.txt goes in 'subdir/subsubdir'.
  67. *
  68. * The sender terminates the data stream with EOF when it has no more
  69. * files to send. I believe it is not _required_ for all D to be
  70. * closed by an E before this happens - you can elide a trailing
  71. * sequence of E commands without provoking an error message from the
  72. * receiver.
  73. *
  74. * Finally, the 'T' command is sent immediately before a C or D. It is
  75. * followed by four space-separated decimal integers giving an mtime
  76. * and atime to be applied to the file or directory created by the
  77. * following C or D command. The first two integers give the mtime,
  78. * encoded as seconds and microseconds (respectively) since the Unix
  79. * epoch; the next two give the atime, encoded similarly. So
  80. * "T1540373455 0 1540373457 0\n" is an example of a valid T command.
  81. *
  82. * Acknowledgments
  83. * ---------------
  84. *
  85. * The sending side waits for an ack from the receiving side before
  86. * sending each command; before beginning to send the file data
  87. * following a C command; and before sending the final EOF.
  88. *
  89. * (In particular, the receiving side is expected to send an initial
  90. * ack before _anything_ is sent.)
  91. *
  92. * Normally an ack consists of a single zero byte. It's also allowable
  93. * to send a byte with value 1 or 2 followed by a \n-terminated error
  94. * message (where 1 means a non-fatal error and 2 means a fatal one).
  95. * I have to suppose that sending an error message from client to
  96. * server is of limited use, but apparently it's allowed.
  97. *
  98. * Initiation
  99. * ----------
  100. *
  101. * The protocol is begun by the client sending a command string to the
  102. * server via the SSH-2 "exec" request (or the analogous
  103. * SSH1_CMSG_EXEC_CMD), which indicates that this is an scp session
  104. * rather than any other thing; specifies the direction of transfer;
  105. * says what file(s) are to be sent by the server, or where the server
  106. * should put files that the client is about to send; and a couple of
  107. * other options.
  108. *
  109. * The command string takes the following form:
  110. *
  111. * Start with prefix "scp ", indicating that this is an SCP command at
  112. * all. Otherwise it's a request to run some completely different
  113. * command in the SSH session.
  114. *
  115. * Next the command can contain zero or more of the following options,
  116. * each followed by a space:
  117. *
  118. * "-v" turns on verbose server diagnostics. Of course a server is not
  119. * required to actually produce any, but this is an invitation for it
  120. * to send any it might have available. Diagnostics are free-form, and
  121. * sent as SSH standard-error extended data, so that they are separate
  122. * from the actual data stream as described above.
  123. *
  124. * (Servers can send standard-error output anyway if they like, and in
  125. * case of an actual error, they probably will with or without -v.)
  126. *
  127. * "-r" indicates recursive file transfer, i.e. potentially including
  128. * subdirectories. For a download, this indicates that the client is
  129. * willing to receive subdirectories (a D/E command pair bracketing
  130. * further files and subdirs); without it, the server should only send
  131. * C commands for individual files, followed by EOF.
  132. *
  133. * This flag must also be specified for a recursive upload, because I
  134. * believe at least one server will reject D/E pairs sent by the
  135. * client if the command didn't have -r in it. (Probably a consequence
  136. * of sharing code between download and upload.)
  137. *
  138. * "-p" means preserve file times. In a download, this requests the
  139. * server to send a T command before each C or D. I don't know whether
  140. * any server will insist on having seen this option from the client
  141. * before accepting T commands in an upload, but it is probably
  142. * sensible to send it anyway.
  143. *
  144. * "-d", in an upload, means that the destination pathname (see below)
  145. * is expected to be a directory, and that uploaded files (and
  146. * subdirs) should be put inside it. Without -d, the semantics are
  147. * that _if_ the destination exists and is a directory, then files
  148. * will be put in it, whereas if it is not, then just a single file
  149. * (or subdir) upload is expected, which will be placed at that exact
  150. * pathname.
  151. *
  152. * In a download, I observe that clients tend to send -d if they are
  153. * requesting multiple files or a wildcard, but as far as I know,
  154. * servers ignore it.
  155. *
  156. * After all those optional options, there is a single mandatory
  157. * option indicating the direction of transfer, which is either "-f"
  158. * or "-t". "-f" indicates a download; "-t" indicates an upload.
  159. *
  160. * After that mandatory option, there is a single space, followed by
  161. * the name(s) of files to transfer.
  162. *
  163. * This file name field is transmitted with NO QUOTING, in spite of
  164. * the fact that a server will typically interpret it as a shell
  165. * command. You'd think this couldn't possibly work, in the face of
  166. * almost any filename with an interesting character in it - and you'd
  167. * be right. Or rather (you might argue), it works 'as designed', but
  168. * it's designed in a weird way, in that it's the user's
  169. * responsibility to apply quoting on the client command line to get
  170. * the filename through the shell that will decode things on the
  171. * server side.
  172. *
  173. * But one effect of this is that if you issue a download command
  174. * including a wildcard, say "scp -f somedir/foo*.txt", then the shell
  175. * will expand the wildcard, and actually run the server-side scp
  176. * program with multiple arguments, say "somedir/foo.txt
  177. * somedir/quux.txt", leading to the download sending multiple C
  178. * commands. This clearly _is_ intended: it's how a command such as
  179. * 'scp server:somedir/foo*.txt destdir' can work at all.
  180. *
  181. * (You would think, given that, that it might also be legal to send
  182. * multiple space-separated filenames in order to trigger a download
  183. * of exactly those files. Given how scp is invoked in practice on a
  184. * typical server, this would surely actually work, but my observation
  185. * is that scp clients don't in fact try this - if you run OpenSSH's
  186. * scp by saying 'scp server:foo server:bar destdir' then it will make
  187. * two separate connections to the server for the two files, rather
  188. * than sending a single space-separated remote command. PSCP won't
  189. * even do that, and will make you do it in two separate runs.)
  190. *
  191. * So, some examples:
  192. *
  193. * - "scp -f filename.txt"
  194. *
  195. * Server should send a single C command (plus data) for that file.
  196. * Client ought to ignore the filename in the C command, in favour
  197. * of saving the file under the name implied by the user's command
  198. * line.
  199. *
  200. * - "scp -f file*.txt"
  201. *
  202. * Server sends zero or more C commands, then EOF. Client will have
  203. * been given a target directory to put them all in, and will name
  204. * each one according to the name in the C command.
  205. *
  206. * (You'd like the client to validate the filenames against the
  207. * wildcard it sent, to ensure a malicious server didn't try to
  208. * overwrite some path like ".bashrc" when you thought you were
  209. * downloading only normal text files. But wildcard semantics are
  210. * chosen by the server, so this is essentially hopeless to do
  211. * rigorously.)
  212. *
  213. * - "scp -f -r somedir"
  214. *
  215. * Assuming somedir is actually a directory, server sends a D/E
  216. * pair, in between which are the contents of the directory
  217. * (perhaps including further nested D/E pairs). Client probably
  218. * ignores the name field of the outermost D
  219. *
  220. * - "scp -f -r some*wild*card*"
  221. *
  222. * Server sends multiple C or D-stuff-E, one for each top-level
  223. * thing matching the wildcard, whether it's a file or a directory.
  224. *
  225. * - "scp -t -d some_dir"
  226. *
  227. * Client sends stuff, and server deposits each file at
  228. * some_dir/<name from the C command>.
  229. *
  230. * - "scp -t some_path_name"
  231. *
  232. * Client sends one C command, and server deposits it at
  233. * some_path_name itself, or in some_path_name/<name from C
  234. * command>, depending whether some_path_name was already a
  235. * directory or not.
  236. */
  237. /*
  238. * Here's a useful debugging aid: run over a binary file containing
  239. * the complete contents of the sender's data stream (e.g. extracted
  240. * by contrib/logparse.pl -d), it removes the file contents, leaving
  241. * only the list of commands, so you can see what the server sent.
  242. *
  243. * perl -pe 'read ARGV,$x,1+$1 if/^C\S+ (\d+)/'
  244. */
  245. /* ----------------------------------------------------------------------
  246. * Shared system for receiving replies from the SftpServer, and
  247. * putting them into a set of ordinary variables rather than
  248. * marshalling them into actual SFTP reply packets that we'd only have
  249. * to unmarshal again.
  250. */
  251. typedef struct ScpReplyReceiver ScpReplyReceiver;
  252. struct ScpReplyReceiver {
  253. bool err;
  254. unsigned code;
  255. char *errmsg;
  256. struct fxp_attrs attrs;
  257. ptrlen name, handle, data;
  258. SftpReplyBuilder srb;
  259. };
  260. static void scp_reply_ok(SftpReplyBuilder *srb)
  261. {
  262. ScpReplyReceiver *reply = container_of(srb, ScpReplyReceiver, srb);
  263. reply->err = false;
  264. }
  265. static void scp_reply_error(
  266. SftpReplyBuilder *srb, unsigned code, const char *msg)
  267. {
  268. ScpReplyReceiver *reply = container_of(srb, ScpReplyReceiver, srb);
  269. reply->err = true;
  270. reply->code = code;
  271. sfree(reply->errmsg);
  272. reply->errmsg = dupstr(msg);
  273. }
  274. static void scp_reply_name_count(SftpReplyBuilder *srb, unsigned count)
  275. {
  276. ScpReplyReceiver *reply = container_of(srb, ScpReplyReceiver, srb);
  277. reply->err = false;
  278. }
  279. static void scp_reply_full_name(
  280. SftpReplyBuilder *srb, ptrlen name,
  281. ptrlen longname, struct fxp_attrs attrs)
  282. {
  283. ScpReplyReceiver *reply = container_of(srb, ScpReplyReceiver, srb);
  284. char *p;
  285. reply->err = false;
  286. sfree((void *)reply->name.ptr);
  287. reply->name.ptr = p = mkstr(name);
  288. reply->name.len = name.len;
  289. reply->attrs = attrs;
  290. }
  291. static void scp_reply_simple_name(SftpReplyBuilder *srb, ptrlen name)
  292. {
  293. ScpReplyReceiver *reply = container_of(srb, ScpReplyReceiver, srb);
  294. reply->err = false;
  295. }
  296. static void scp_reply_handle(SftpReplyBuilder *srb, ptrlen handle)
  297. {
  298. ScpReplyReceiver *reply = container_of(srb, ScpReplyReceiver, srb);
  299. char *p;
  300. reply->err = false;
  301. sfree((void *)reply->handle.ptr);
  302. reply->handle.ptr = p = mkstr(handle);
  303. reply->handle.len = handle.len;
  304. }
  305. static void scp_reply_data(SftpReplyBuilder *srb, ptrlen data)
  306. {
  307. ScpReplyReceiver *reply = container_of(srb, ScpReplyReceiver, srb);
  308. char *p;
  309. reply->err = false;
  310. sfree((void *)reply->data.ptr);
  311. reply->data.ptr = p = mkstr(data);
  312. reply->data.len = data.len;
  313. }
  314. static void scp_reply_attrs(
  315. SftpReplyBuilder *srb, struct fxp_attrs attrs)
  316. {
  317. ScpReplyReceiver *reply = container_of(srb, ScpReplyReceiver, srb);
  318. reply->err = false;
  319. reply->attrs = attrs;
  320. }
  321. static const SftpReplyBuilderVtable ScpReplyReceiver_vt = {
  322. .reply_ok = scp_reply_ok,
  323. .reply_error = scp_reply_error,
  324. .reply_simple_name = scp_reply_simple_name,
  325. .reply_name_count = scp_reply_name_count,
  326. .reply_full_name = scp_reply_full_name,
  327. .reply_handle = scp_reply_handle,
  328. .reply_data = scp_reply_data,
  329. .reply_attrs = scp_reply_attrs,
  330. };
  331. static void scp_reply_setup(ScpReplyReceiver *reply)
  332. {
  333. memset(reply, 0, sizeof(*reply));
  334. reply->srb.vt = &ScpReplyReceiver_vt;
  335. }
  336. static void scp_reply_cleanup(ScpReplyReceiver *reply)
  337. {
  338. sfree(reply->errmsg);
  339. sfree((void *)reply->name.ptr);
  340. sfree((void *)reply->handle.ptr);
  341. sfree((void *)reply->data.ptr);
  342. }
  343. /* ----------------------------------------------------------------------
  344. * Source end of the SCP protocol.
  345. */
  346. #define SCP_MAX_BACKLOG 65536
  347. typedef struct ScpSource ScpSource;
  348. typedef struct ScpSourceStackEntry ScpSourceStackEntry;
  349. struct ScpSource {
  350. SftpServer *sf;
  351. int acks;
  352. bool expect_newline, eof, throttled, finished;
  353. SshChannel *sc;
  354. ScpSourceStackEntry *head;
  355. bool recursive;
  356. bool send_file_times;
  357. strbuf *pending_commands[3];
  358. int n_pending_commands;
  359. uint64_t file_offset, file_size;
  360. ScpReplyReceiver reply;
  361. ScpServer scpserver;
  362. };
  363. typedef enum ScpSourceNodeType ScpSourceNodeType;
  364. enum ScpSourceNodeType { SCP_ROOTPATH, SCP_NAME, SCP_READDIR, SCP_READFILE };
  365. struct ScpSourceStackEntry {
  366. ScpSourceStackEntry *next;
  367. ScpSourceNodeType type;
  368. ptrlen pathname, handle;
  369. const char *wildcard;
  370. struct fxp_attrs attrs;
  371. };
  372. static void scp_source_push(ScpSource *scp, ScpSourceNodeType type,
  373. ptrlen pathname, ptrlen handle,
  374. const struct fxp_attrs *attrs, const char *wc)
  375. {
  376. size_t wc_len = wc ? strlen(wc)+1 : 0;
  377. ScpSourceStackEntry *node = snew_plus(
  378. ScpSourceStackEntry, pathname.len + handle.len + wc_len);
  379. char *namebuf = snew_plus_get_aux(node);
  380. memcpy(namebuf, pathname.ptr, pathname.len);
  381. node->pathname = make_ptrlen(namebuf, pathname.len);
  382. memcpy(namebuf + pathname.len, handle.ptr, handle.len);
  383. node->handle = make_ptrlen(namebuf + pathname.len, handle.len);
  384. if (wc) {
  385. strcpy(namebuf + pathname.len + handle.len, wc);
  386. node->wildcard = namebuf + pathname.len + handle.len;
  387. } else {
  388. node->wildcard = NULL;
  389. }
  390. node->attrs = attrs ? *attrs : no_attrs;
  391. node->type = type;
  392. node->next = scp->head;
  393. scp->head = node;
  394. }
  395. static char *scp_source_err_base(ScpSource *scp, const char *fmt, va_list ap)
  396. {
  397. char *msg = dupvprintf(fmt, ap);
  398. sshfwd_write_ext(scp->sc, true, msg, strlen(msg));
  399. sshfwd_write_ext(scp->sc, true, "\012", 1);
  400. return msg;
  401. }
  402. static PRINTF_LIKE(2, 3) void scp_source_err(
  403. ScpSource *scp, const char *fmt, ...)
  404. {
  405. va_list ap;
  406. va_start(ap, fmt);
  407. sfree(scp_source_err_base(scp, fmt, ap));
  408. va_end(ap);
  409. }
  410. static PRINTF_LIKE(2, 3) void scp_source_abort(
  411. ScpSource *scp, const char *fmt, ...)
  412. {
  413. va_list ap;
  414. char *msg;
  415. va_start(ap, fmt);
  416. msg = scp_source_err_base(scp, fmt, ap);
  417. va_end(ap);
  418. sshfwd_send_exit_status(scp->sc, 1);
  419. sshfwd_write_eof(scp->sc);
  420. sshfwd_initiate_close(scp->sc, msg);
  421. scp->finished = true;
  422. }
  423. static void scp_source_push_name(
  424. ScpSource *scp, ptrlen pathname, struct fxp_attrs attrs, const char *wc)
  425. {
  426. if (!(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
  427. scp_source_err(scp, "unable to read file permissions for %.*s",
  428. PTRLEN_PRINTF(pathname));
  429. return;
  430. }
  431. if (attrs.permissions & PERMS_DIRECTORY) {
  432. if (!scp->recursive && !wc) {
  433. scp_source_err(scp, "%.*s: is a directory",
  434. PTRLEN_PRINTF(pathname));
  435. return;
  436. }
  437. } else {
  438. if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) {
  439. scp_source_err(scp, "unable to read file size for %.*s",
  440. PTRLEN_PRINTF(pathname));
  441. return;
  442. }
  443. }
  444. scp_source_push(scp, SCP_NAME, pathname, PTRLEN_LITERAL(""), &attrs, wc);
  445. }
  446. static void scp_source_free(ScpServer *s);
  447. static size_t scp_source_send(ScpServer *s, const void *data, size_t length);
  448. static void scp_source_eof(ScpServer *s);
  449. static void scp_source_throttle(ScpServer *s, bool throttled);
  450. static const ScpServerVtable ScpSource_ScpServer_vt = {
  451. .free = scp_source_free,
  452. .send = scp_source_send,
  453. .throttle = scp_source_throttle,
  454. .eof = scp_source_eof,
  455. };
  456. static ScpSource *scp_source_new(
  457. SshChannel *sc, const SftpServerVtable *sftpserver_vt, ptrlen pathname)
  458. {
  459. ScpSource *scp = snew(ScpSource);
  460. memset(scp, 0, sizeof(*scp));
  461. scp->scpserver.vt = &ScpSource_ScpServer_vt;
  462. scp_reply_setup(&scp->reply);
  463. scp->sc = sc;
  464. scp->sf = sftpsrv_new(sftpserver_vt);
  465. scp->n_pending_commands = 0;
  466. scp_source_push(scp, SCP_ROOTPATH, pathname, PTRLEN_LITERAL(""),
  467. NULL, NULL);
  468. return scp;
  469. }
  470. static void scp_source_free(ScpServer *s)
  471. {
  472. ScpSource *scp = container_of(s, ScpSource, scpserver);
  473. scp_reply_cleanup(&scp->reply);
  474. while (scp->n_pending_commands > 0)
  475. strbuf_free(scp->pending_commands[--scp->n_pending_commands]);
  476. while (scp->head) {
  477. ScpSourceStackEntry *node = scp->head;
  478. scp->head = node->next;
  479. sfree(node);
  480. }
  481. delete_callbacks_for_context(scp);
  482. sfree(scp);
  483. }
  484. static void scp_source_send_E(ScpSource *scp)
  485. {
  486. strbuf *cmd;
  487. assert(scp->n_pending_commands == 0);
  488. scp->pending_commands[scp->n_pending_commands++] = cmd = strbuf_new();
  489. put_fmt(cmd, "E\012");
  490. }
  491. static void scp_source_send_CD(
  492. ScpSource *scp, char cmdchar,
  493. struct fxp_attrs attrs, uint64_t size, ptrlen name)
  494. {
  495. strbuf *cmd;
  496. assert(scp->n_pending_commands == 0);
  497. if (scp->send_file_times && (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
  498. scp->pending_commands[scp->n_pending_commands++] = cmd = strbuf_new();
  499. /* Our SFTP-based filesystem API doesn't support microsecond times */
  500. put_fmt(cmd, "T%lu 0 %lu 0\012", attrs.mtime, attrs.atime);
  501. }
  502. const char *slash;
  503. while ((slash = memchr(name.ptr, '/', name.len)) != NULL)
  504. name = make_ptrlen(
  505. slash+1, name.len - (slash+1 - (const char *)name.ptr));
  506. scp->pending_commands[scp->n_pending_commands++] = cmd = strbuf_new();
  507. put_fmt(cmd, "%c%04o %"PRIu64" %.*s\012", cmdchar,
  508. (unsigned)(attrs.permissions & 07777),
  509. size, PTRLEN_PRINTF(name));
  510. if (cmdchar == 'C') {
  511. /* We'll also wait for an ack before sending the file data,
  512. * which we record by saving a zero-length 'command' to be
  513. * sent after the C. */
  514. scp->pending_commands[scp->n_pending_commands++] = cmd = strbuf_new();
  515. }
  516. }
  517. static void scp_source_process_stack(ScpSource *scp);
  518. static void scp_source_process_stack_cb(void *vscp)
  519. {
  520. ScpSource *scp = (ScpSource *)vscp;
  521. if (scp->finished)
  522. return; /* this callback is out of date */
  523. scp_source_process_stack(scp);
  524. }
  525. static void scp_requeue(ScpSource *scp)
  526. {
  527. queue_toplevel_callback(scp_source_process_stack_cb, scp);
  528. }
  529. static void scp_source_process_stack(ScpSource *scp)
  530. {
  531. if (scp->throttled)
  532. return;
  533. while (scp->n_pending_commands > 0) {
  534. /* Expect an ack, and consume it */
  535. if (scp->eof) {
  536. scp_source_abort(
  537. scp, "scp: received client EOF, abandoning transfer");
  538. return;
  539. }
  540. if (scp->acks == 0)
  541. return;
  542. scp->acks--;
  543. /*
  544. * Now send the actual command (unless it was the phony
  545. * zero-length one that indicates our need for an ack before
  546. * beginning to send file data).
  547. */
  548. if (scp->pending_commands[0]->len)
  549. sshfwd_write(scp->sc, scp->pending_commands[0]->s,
  550. scp->pending_commands[0]->len);
  551. strbuf_free(scp->pending_commands[0]);
  552. scp->n_pending_commands--;
  553. if (scp->n_pending_commands > 0) {
  554. /*
  555. * We still have at least one pending command to send, so
  556. * move up the queue.
  557. *
  558. * (We do that with a bodgy memmove, because there are at
  559. * most a bounded number of commands ever pending at once,
  560. * so no need to worry about quadratic time.)
  561. */
  562. memmove(scp->pending_commands, scp->pending_commands+1,
  563. scp->n_pending_commands * sizeof(*scp->pending_commands));
  564. }
  565. }
  566. /*
  567. * Mostly, we start by waiting for an ack byte from the receiver.
  568. */
  569. if (scp->head && scp->head->type == SCP_READFILE && scp->file_offset) {
  570. /*
  571. * Exception: if we're already in the middle of transferring a
  572. * file, we'll be called back here because the channel backlog
  573. * has cleared; we don't need to wait for an ack.
  574. */
  575. } else if (scp->head && scp->head->type == SCP_ROOTPATH) {
  576. /*
  577. * Another exception: the initial action node that makes us
  578. * stat the root path. We'll translate it into an SCP_NAME,
  579. * and _that_ will require an ack.
  580. */
  581. ScpSourceStackEntry *node = scp->head;
  582. scp->head = node->next;
  583. /*
  584. * Start by checking if there's a wildcard involved in the
  585. * root path.
  586. */
  587. char *rootpath_str = mkstr(node->pathname);
  588. char *rootpath_unesc = snewn(1+node->pathname.len, char);
  589. ptrlen pathname;
  590. const char *wildcard;
  591. if (wc_unescape(rootpath_unesc, rootpath_str)) {
  592. /*
  593. * We successfully removed instances of the escape
  594. * character used in our wildcard syntax, without
  595. * encountering any actual wildcard chars - i.e. this is
  596. * not a wildcard, just a single file. The simple case.
  597. */
  598. pathname = ptrlen_from_asciz(rootpath_str);
  599. wildcard = NULL;
  600. } else {
  601. /*
  602. * This is a wildcard. Separate it into a directory name
  603. * (which we enforce mustn't contain wc characters, for
  604. * simplicity) and a wildcard to match leaf names.
  605. */
  606. char *last_slash = strrchr(rootpath_str, '/');
  607. if (last_slash) {
  608. wildcard = last_slash + 1;
  609. *last_slash = '\0';
  610. if (!wc_unescape(rootpath_unesc, rootpath_str)) {
  611. scp_source_abort(scp, "scp: wildcards in path components "
  612. "before the file name not supported");
  613. sfree(rootpath_str);
  614. sfree(rootpath_unesc);
  615. return;
  616. }
  617. pathname = ptrlen_from_asciz(rootpath_unesc);
  618. } else {
  619. pathname = PTRLEN_LITERAL(".");
  620. wildcard = rootpath_str;
  621. }
  622. }
  623. /*
  624. * Now we know what directory we're scanning, and what
  625. * wildcard (if any) we're using to match the filenames we get
  626. * back.
  627. */
  628. sftpsrv_stat(scp->sf, &scp->reply.srb, pathname, true);
  629. if (scp->reply.err) {
  630. scp_source_abort(
  631. scp, "%.*s: unable to access: %s",
  632. PTRLEN_PRINTF(pathname), scp->reply.errmsg);
  633. sfree(rootpath_str);
  634. sfree(rootpath_unesc);
  635. sfree(node);
  636. return;
  637. }
  638. scp_source_push_name(scp, pathname, scp->reply.attrs, wildcard);
  639. sfree(rootpath_str);
  640. sfree(rootpath_unesc);
  641. sfree(node);
  642. scp_requeue(scp);
  643. return;
  644. } else {
  645. }
  646. if (scp->head && scp->head->type == SCP_READFILE) {
  647. /*
  648. * Transfer file data if our backlog hasn't filled up.
  649. */
  650. int backlog;
  651. uint64_t limit = scp->file_size - scp->file_offset;
  652. if (limit > 4096)
  653. limit = 4096;
  654. if (limit > 0) {
  655. sftpsrv_read(scp->sf, &scp->reply.srb, scp->head->handle,
  656. scp->file_offset, limit);
  657. if (scp->reply.err) {
  658. scp_source_abort(
  659. scp, "%.*s: unable to read: %s",
  660. PTRLEN_PRINTF(scp->head->pathname), scp->reply.errmsg);
  661. return;
  662. }
  663. backlog = sshfwd_write(
  664. scp->sc, scp->reply.data.ptr, scp->reply.data.len);
  665. scp->file_offset += scp->reply.data.len;
  666. if (backlog < SCP_MAX_BACKLOG)
  667. scp_requeue(scp);
  668. return;
  669. }
  670. /*
  671. * If we're done, send a terminating zero byte, close our file
  672. * handle, and pop the stack.
  673. */
  674. sshfwd_write(scp->sc, "\0", 1);
  675. sftpsrv_close(scp->sf, &scp->reply.srb, scp->head->handle);
  676. ScpSourceStackEntry *node = scp->head;
  677. scp->head = node->next;
  678. sfree(node);
  679. scp_requeue(scp);
  680. return;
  681. }
  682. /*
  683. * If our queue is actually empty, send outgoing EOF.
  684. */
  685. if (!scp->head) {
  686. sshfwd_send_exit_status(scp->sc, 0);
  687. sshfwd_write_eof(scp->sc);
  688. sshfwd_initiate_close(scp->sc, NULL);
  689. scp->finished = true;
  690. return;
  691. }
  692. /*
  693. * Otherwise, handle a command.
  694. */
  695. ScpSourceStackEntry *node = scp->head;
  696. scp->head = node->next;
  697. if (node->type == SCP_READDIR) {
  698. sftpsrv_readdir(scp->sf, &scp->reply.srb, node->handle, 1, true);
  699. if (scp->reply.err) {
  700. if (scp->reply.code != SSH_FX_EOF)
  701. scp_source_err(scp, "%.*s: unable to list directory: %s",
  702. PTRLEN_PRINTF(node->pathname),
  703. scp->reply.errmsg);
  704. sftpsrv_close(scp->sf, &scp->reply.srb, node->handle);
  705. if (!node->wildcard) {
  706. /*
  707. * Send 'pop stack' or 'end of directory' command,
  708. * unless this was the topmost READDIR in a
  709. * wildcard-based retrieval (in which case we didn't
  710. * send a D command to start, so an E now would have
  711. * no stack entry to pop).
  712. */
  713. scp_source_send_E(scp);
  714. }
  715. } else if (ptrlen_eq_string(scp->reply.name, ".") ||
  716. ptrlen_eq_string(scp->reply.name, "..") ||
  717. (node->wildcard &&
  718. !wc_match_pl(node->wildcard, scp->reply.name))) {
  719. /* Skip special directory names . and .., and anything
  720. * that doesn't match our wildcard (if we have one). */
  721. scp->head = node; /* put back the unfinished READDIR */
  722. node = NULL; /* and prevent it being freed */
  723. } else {
  724. strbuf *subpath = strbuf_new();
  725. put_datapl(subpath, node->pathname);
  726. put_byte(subpath, '/');
  727. put_datapl(subpath, scp->reply.name);
  728. scp->head = node; /* put back the unfinished READDIR */
  729. node = NULL; /* and prevent it being freed */
  730. scp_source_push_name(scp, ptrlen_from_strbuf(subpath),
  731. scp->reply.attrs, NULL);
  732. strbuf_free(subpath);
  733. }
  734. } else if (node->attrs.permissions & PERMS_DIRECTORY) {
  735. assert(scp->recursive || node->wildcard);
  736. if (!node->wildcard)
  737. scp_source_send_CD(scp, 'D', node->attrs, 0, node->pathname);
  738. sftpsrv_opendir(scp->sf, &scp->reply.srb, node->pathname);
  739. if (scp->reply.err) {
  740. scp_source_err(
  741. scp, "%.*s: unable to access: %s",
  742. PTRLEN_PRINTF(node->pathname), scp->reply.errmsg);
  743. if (!node->wildcard) {
  744. /* Send 'pop stack' or 'end of directory' command. */
  745. scp_source_send_E(scp);
  746. }
  747. } else {
  748. scp_source_push(
  749. scp, SCP_READDIR, node->pathname,
  750. scp->reply.handle, NULL, node->wildcard);
  751. }
  752. } else {
  753. sftpsrv_open(scp->sf, &scp->reply.srb,
  754. node->pathname, SSH_FXF_READ, no_attrs);
  755. if (scp->reply.err) {
  756. scp_source_err(
  757. scp, "%.*s: unable to open: %s",
  758. PTRLEN_PRINTF(node->pathname), scp->reply.errmsg);
  759. scp_requeue(scp);
  760. return;
  761. }
  762. sftpsrv_fstat(scp->sf, &scp->reply.srb, scp->reply.handle);
  763. if (scp->reply.err) {
  764. scp_source_err(
  765. scp, "%.*s: unable to stat: %s",
  766. PTRLEN_PRINTF(node->pathname), scp->reply.errmsg);
  767. sftpsrv_close(scp->sf, &scp->reply.srb, scp->reply.handle);
  768. scp_requeue(scp);
  769. return;
  770. }
  771. scp->file_offset = 0;
  772. scp->file_size = scp->reply.attrs.size;
  773. scp_source_send_CD(scp, 'C', node->attrs,
  774. scp->file_size, node->pathname);
  775. scp_source_push(
  776. scp, SCP_READFILE, node->pathname, scp->reply.handle, NULL, NULL);
  777. }
  778. sfree(node);
  779. scp_requeue(scp);
  780. }
  781. static size_t scp_source_send(ScpServer *s, const void *vdata, size_t length)
  782. {
  783. ScpSource *scp = container_of(s, ScpSource, scpserver);
  784. const char *data = (const char *)vdata;
  785. size_t i;
  786. if (scp->finished)
  787. return 0;
  788. for (i = 0; i < length; i++) {
  789. if (scp->expect_newline) {
  790. if (data[i] == '\012') {
  791. /* End of an error message following a 1 byte */
  792. scp->expect_newline = false;
  793. scp->acks++;
  794. }
  795. } else {
  796. switch (data[i]) {
  797. case 0: /* ordinary ack */
  798. scp->acks++;
  799. break;
  800. case 1: /* non-fatal error; consume it */
  801. scp->expect_newline = true;
  802. break;
  803. case 2:
  804. scp_source_abort(
  805. scp, "terminating on fatal error from client");
  806. return 0;
  807. default:
  808. scp_source_abort(
  809. scp, "unrecognised response code from client");
  810. return 0;
  811. }
  812. }
  813. }
  814. scp_source_process_stack(scp);
  815. return 0;
  816. }
  817. static void scp_source_throttle(ScpServer *s, bool throttled)
  818. {
  819. ScpSource *scp = container_of(s, ScpSource, scpserver);
  820. if (scp->finished)
  821. return;
  822. scp->throttled = throttled;
  823. if (!throttled)
  824. scp_source_process_stack(scp);
  825. }
  826. static void scp_source_eof(ScpServer *s)
  827. {
  828. ScpSource *scp = container_of(s, ScpSource, scpserver);
  829. if (scp->finished)
  830. return;
  831. scp->eof = true;
  832. scp_source_process_stack(scp);
  833. }
  834. /* ----------------------------------------------------------------------
  835. * Sink end of the SCP protocol.
  836. */
  837. typedef struct ScpSink ScpSink;
  838. typedef struct ScpSinkStackEntry ScpSinkStackEntry;
  839. struct ScpSink {
  840. SftpServer *sf;
  841. SshChannel *sc;
  842. ScpSinkStackEntry *head;
  843. uint64_t file_offset, file_size;
  844. unsigned long atime, mtime;
  845. bool got_file_times;
  846. bufchain data;
  847. bool input_eof;
  848. strbuf *command;
  849. char command_chr;
  850. strbuf *filename_sb;
  851. ptrlen filename;
  852. struct fxp_attrs attrs;
  853. char *errmsg;
  854. int crState;
  855. ScpReplyReceiver reply;
  856. ScpServer scpserver;
  857. };
  858. struct ScpSinkStackEntry {
  859. ScpSinkStackEntry *next;
  860. ptrlen destpath;
  861. /*
  862. * If isdir is true, then destpath identifies a directory that the
  863. * files we receive should be created inside. If it's false, then
  864. * it identifies the exact pathname the next file we receive
  865. * should be created _as_ - regardless of the filename in the 'C'
  866. * command.
  867. */
  868. bool isdir;
  869. };
  870. static void scp_sink_push(ScpSink *scp, ptrlen pathname, bool isdir)
  871. {
  872. ScpSinkStackEntry *node = snew_plus(ScpSinkStackEntry, pathname.len);
  873. char *p = snew_plus_get_aux(node);
  874. node->destpath.ptr = p;
  875. node->destpath.len = pathname.len;
  876. memcpy(p, pathname.ptr, pathname.len);
  877. node->isdir = isdir;
  878. node->next = scp->head;
  879. scp->head = node;
  880. }
  881. static void scp_sink_pop(ScpSink *scp)
  882. {
  883. ScpSinkStackEntry *node = scp->head;
  884. scp->head = node->next;
  885. sfree(node);
  886. }
  887. static void scp_sink_free(ScpServer *s);
  888. static size_t scp_sink_send(ScpServer *s, const void *data, size_t length);
  889. static void scp_sink_eof(ScpServer *s);
  890. static void scp_sink_throttle(ScpServer *s, bool throttled) {}
  891. static const ScpServerVtable ScpSink_ScpServer_vt = {
  892. .free = scp_sink_free,
  893. .send = scp_sink_send,
  894. .throttle = scp_sink_throttle,
  895. .eof = scp_sink_eof,
  896. };
  897. static void scp_sink_coroutine(ScpSink *scp);
  898. static void scp_sink_start_callback(void *vscp)
  899. {
  900. scp_sink_coroutine((ScpSink *)vscp);
  901. }
  902. static ScpSink *scp_sink_new(
  903. SshChannel *sc, const SftpServerVtable *sftpserver_vt, ptrlen pathname,
  904. bool pathname_is_definitely_dir)
  905. {
  906. ScpSink *scp = snew(ScpSink);
  907. memset(scp, 0, sizeof(*scp));
  908. scp->scpserver.vt = &ScpSink_ScpServer_vt;
  909. scp_reply_setup(&scp->reply);
  910. scp->sc = sc;
  911. scp->sf = sftpsrv_new(sftpserver_vt);
  912. bufchain_init(&scp->data);
  913. scp->command = strbuf_new();
  914. scp->filename_sb = strbuf_new();
  915. if (!pathname_is_definitely_dir) {
  916. /*
  917. * If our root pathname is not already expected to be a
  918. * directory because of the -d option in the command line,
  919. * test it ourself to see whether it is or not.
  920. */
  921. sftpsrv_stat(scp->sf, &scp->reply.srb, pathname, true);
  922. if (!scp->reply.err &&
  923. (scp->reply.attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
  924. (scp->reply.attrs.permissions & PERMS_DIRECTORY))
  925. pathname_is_definitely_dir = true;
  926. }
  927. scp_sink_push(scp, pathname, pathname_is_definitely_dir);
  928. queue_toplevel_callback(scp_sink_start_callback, scp);
  929. return scp;
  930. }
  931. static void scp_sink_free(ScpServer *s)
  932. {
  933. ScpSink *scp = container_of(s, ScpSink, scpserver);
  934. scp_reply_cleanup(&scp->reply);
  935. bufchain_clear(&scp->data);
  936. strbuf_free(scp->command);
  937. strbuf_free(scp->filename_sb);
  938. while (scp->head)
  939. scp_sink_pop(scp);
  940. sfree(scp->errmsg);
  941. delete_callbacks_for_context(scp);
  942. sfree(scp);
  943. }
  944. static void scp_sink_coroutine(ScpSink *scp)
  945. {
  946. crBegin(scp->crState);
  947. while (1) {
  948. /*
  949. * Send an ack, and read a command.
  950. */
  951. sshfwd_write(scp->sc, "\0", 1);
  952. strbuf_clear(scp->command);
  953. while (1) {
  954. crMaybeWaitUntilV(scp->input_eof || bufchain_size(&scp->data) > 0);
  955. if (scp->input_eof)
  956. goto done;
  957. ptrlen data = bufchain_prefix(&scp->data);
  958. const char *cdata = data.ptr;
  959. const char *newline = memchr(cdata, '\012', data.len);
  960. if (newline)
  961. data.len = (int)(newline+1 - cdata);
  962. put_data(scp->command, cdata, data.len);
  963. bufchain_consume(&scp->data, data.len);
  964. if (newline)
  965. break;
  966. }
  967. /*
  968. * Parse the command.
  969. */
  970. strbuf_chomp(scp->command, '\n');
  971. scp->command_chr = scp->command->len > 0 ? scp->command->s[0] : '\0';
  972. if (scp->command_chr == 'T') {
  973. unsigned long dummy1, dummy2;
  974. if (sscanf(scp->command->s, "T%lu %lu %lu %lu",
  975. &scp->mtime, &dummy1, &scp->atime, &dummy2) != 4)
  976. goto parse_error;
  977. scp->got_file_times = true;
  978. } else if (scp->command_chr == 'C' || scp->command_chr == 'D') {
  979. /*
  980. * Common handling of the start of this case, because the
  981. * messages are parsed similarly. We diverge later.
  982. */
  983. const char *q, *p = scp->command->s + 1; /* skip the 'C' */
  984. scp->attrs.flags = SSH_FILEXFER_ATTR_PERMISSIONS;
  985. scp->attrs.permissions = 0;
  986. while (*p >= '0' && *p <= '7') {
  987. scp->attrs.permissions =
  988. scp->attrs.permissions * 8 + (*p - '0');
  989. p++;
  990. }
  991. if (*p != ' ')
  992. goto parse_error;
  993. p++;
  994. q = p;
  995. while (*p >= '0' && *p <= '9')
  996. p++;
  997. if (*p != ' ')
  998. goto parse_error;
  999. p++;
  1000. scp->file_size = strtoull(q, NULL, 10);
  1001. ptrlen leafname = make_ptrlen(
  1002. p, scp->command->len - (p - scp->command->s));
  1003. strbuf_clear(scp->filename_sb);
  1004. put_datapl(scp->filename_sb, scp->head->destpath);
  1005. if (scp->head->isdir) {
  1006. if (scp->filename_sb->len > 0 &&
  1007. scp->filename_sb->s[scp->filename_sb->len-1]
  1008. != '/')
  1009. put_byte(scp->filename_sb, '/');
  1010. put_datapl(scp->filename_sb, leafname);
  1011. }
  1012. scp->filename = ptrlen_from_strbuf(scp->filename_sb);
  1013. if (scp->got_file_times) {
  1014. scp->attrs.mtime = scp->mtime;
  1015. scp->attrs.atime = scp->atime;
  1016. scp->attrs.flags |= SSH_FILEXFER_ATTR_ACMODTIME;
  1017. }
  1018. scp->got_file_times = false;
  1019. if (scp->command_chr == 'D') {
  1020. sftpsrv_mkdir(scp->sf, &scp->reply.srb,
  1021. scp->filename, scp->attrs);
  1022. if (scp->reply.err) {
  1023. scp->errmsg = dupprintf(
  1024. "'%.*s': unable to create directory: %s",
  1025. PTRLEN_PRINTF(scp->filename), scp->reply.errmsg);
  1026. goto done;
  1027. }
  1028. scp_sink_push(scp, scp->filename, true);
  1029. } else {
  1030. sftpsrv_open(scp->sf, &scp->reply.srb, scp->filename,
  1031. SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC,
  1032. scp->attrs);
  1033. if (scp->reply.err) {
  1034. scp->errmsg = dupprintf(
  1035. "'%.*s': unable to open file: %s",
  1036. PTRLEN_PRINTF(scp->filename), scp->reply.errmsg);
  1037. goto done;
  1038. }
  1039. /*
  1040. * Now send an ack, and read the file data.
  1041. */
  1042. sshfwd_write(scp->sc, "\0", 1);
  1043. scp->file_offset = 0;
  1044. while (scp->file_offset < scp->file_size) {
  1045. ptrlen data;
  1046. uint64_t this_len, remaining;
  1047. crMaybeWaitUntilV(
  1048. scp->input_eof || bufchain_size(&scp->data) > 0);
  1049. if (scp->input_eof) {
  1050. sftpsrv_close(scp->sf, &scp->reply.srb,
  1051. scp->reply.handle);
  1052. goto done;
  1053. }
  1054. data = bufchain_prefix(&scp->data);
  1055. this_len = data.len;
  1056. remaining = scp->file_size - scp->file_offset;
  1057. if (this_len > remaining)
  1058. this_len = remaining;
  1059. sftpsrv_write(scp->sf, &scp->reply.srb,
  1060. scp->reply.handle, scp->file_offset,
  1061. make_ptrlen(data.ptr, this_len));
  1062. if (scp->reply.err) {
  1063. scp->errmsg = dupprintf(
  1064. "'%.*s': unable to write to file: %s",
  1065. PTRLEN_PRINTF(scp->filename), scp->reply.errmsg);
  1066. goto done;
  1067. }
  1068. bufchain_consume(&scp->data, this_len);
  1069. scp->file_offset += this_len;
  1070. }
  1071. /*
  1072. * Wait for the trailing NUL byte.
  1073. */
  1074. crMaybeWaitUntilV(
  1075. scp->input_eof || bufchain_size(&scp->data) > 0);
  1076. if (scp->input_eof) {
  1077. sftpsrv_close(scp->sf, &scp->reply.srb,
  1078. scp->reply.handle);
  1079. goto done;
  1080. }
  1081. bufchain_consume(&scp->data, 1);
  1082. }
  1083. } else if (scp->command_chr == 'E') {
  1084. if (!scp->head) {
  1085. scp->errmsg = dupstr("received E command without matching D");
  1086. goto done;
  1087. }
  1088. scp_sink_pop(scp);
  1089. scp->got_file_times = false;
  1090. } else {
  1091. ptrlen cmd_pl;
  1092. /*
  1093. * Also come here if any of the above cases run into
  1094. * parsing difficulties.
  1095. */
  1096. parse_error:
  1097. cmd_pl = ptrlen_from_strbuf(scp->command);
  1098. scp->errmsg = dupprintf("unrecognised scp command '%.*s'",
  1099. PTRLEN_PRINTF(cmd_pl));
  1100. goto done;
  1101. }
  1102. }
  1103. done:
  1104. if (scp->errmsg) {
  1105. sshfwd_write_ext(scp->sc, true, scp->errmsg, strlen(scp->errmsg));
  1106. sshfwd_write_ext(scp->sc, true, "\012", 1);
  1107. sshfwd_send_exit_status(scp->sc, 1);
  1108. } else {
  1109. sshfwd_send_exit_status(scp->sc, 0);
  1110. }
  1111. sshfwd_write_eof(scp->sc);
  1112. sshfwd_initiate_close(scp->sc, scp->errmsg);
  1113. while (1) crReturnV;
  1114. crFinishV;
  1115. }
  1116. static size_t scp_sink_send(ScpServer *s, const void *data, size_t length)
  1117. {
  1118. ScpSink *scp = container_of(s, ScpSink, scpserver);
  1119. if (!scp->input_eof) {
  1120. bufchain_add(&scp->data, data, length);
  1121. scp_sink_coroutine(scp);
  1122. }
  1123. return 0;
  1124. }
  1125. static void scp_sink_eof(ScpServer *s)
  1126. {
  1127. ScpSink *scp = container_of(s, ScpSink, scpserver);
  1128. scp->input_eof = true;
  1129. scp_sink_coroutine(scp);
  1130. }
  1131. /* ----------------------------------------------------------------------
  1132. * Top-level error handler, instantiated in the case where the user
  1133. * sent a command starting with "scp " that we couldn't make sense of.
  1134. */
  1135. typedef struct ScpError ScpError;
  1136. struct ScpError {
  1137. SshChannel *sc;
  1138. char *message;
  1139. ScpServer scpserver;
  1140. };
  1141. static void scp_error_free(ScpServer *s);
  1142. static size_t scp_error_send(ScpServer *s, const void *data, size_t length)
  1143. { return 0; }
  1144. static void scp_error_eof(ScpServer *s) {}
  1145. static void scp_error_throttle(ScpServer *s, bool throttled) {}
  1146. static const ScpServerVtable ScpError_ScpServer_vt = {
  1147. .free = scp_error_free,
  1148. .send = scp_error_send,
  1149. .throttle = scp_error_throttle,
  1150. .eof = scp_error_eof,
  1151. };
  1152. static void scp_error_send_message_cb(void *vscp)
  1153. {
  1154. ScpError *scp = (ScpError *)vscp;
  1155. sshfwd_write_ext(scp->sc, true, scp->message, strlen(scp->message));
  1156. sshfwd_write_ext(scp->sc, true, "\n", 1);
  1157. sshfwd_send_exit_status(scp->sc, 1);
  1158. sshfwd_write_eof(scp->sc);
  1159. sshfwd_initiate_close(scp->sc, scp->message);
  1160. }
  1161. static PRINTF_LIKE(2, 3) ScpError *scp_error_new(
  1162. SshChannel *sc, const char *fmt, ...)
  1163. {
  1164. va_list ap;
  1165. ScpError *scp = snew(ScpError);
  1166. memset(scp, 0, sizeof(*scp));
  1167. scp->scpserver.vt = &ScpError_ScpServer_vt;
  1168. scp->sc = sc;
  1169. va_start(ap, fmt);
  1170. scp->message = dupvprintf(fmt, ap);
  1171. va_end(ap);
  1172. queue_toplevel_callback(scp_error_send_message_cb, scp);
  1173. return scp;
  1174. }
  1175. static void scp_error_free(ScpServer *s)
  1176. {
  1177. ScpError *scp = container_of(s, ScpError, scpserver);
  1178. sfree(scp->message);
  1179. delete_callbacks_for_context(scp);
  1180. sfree(scp);
  1181. }
  1182. /* ----------------------------------------------------------------------
  1183. * Top-level entry point, which parses a command sent from the SSH
  1184. * client, and if it recognises it as an scp command, instantiates an
  1185. * appropriate ScpServer implementation and returns it.
  1186. */
  1187. ScpServer *scp_recognise_exec(
  1188. SshChannel *sc, const SftpServerVtable *sftpserver_vt, ptrlen command)
  1189. {
  1190. bool recursive = false, preserve = false;
  1191. bool targetshouldbedirectory = false;
  1192. ptrlen command_orig = command;
  1193. if (!ptrlen_startswith(command, PTRLEN_LITERAL("scp "), &command))
  1194. return NULL;
  1195. while (1) {
  1196. if (ptrlen_startswith(command, PTRLEN_LITERAL("-v "), &command)) {
  1197. /* Enable verbose mode in the server, which we ignore */
  1198. continue;
  1199. }
  1200. if (ptrlen_startswith(command, PTRLEN_LITERAL("-r "), &command)) {
  1201. recursive = true;
  1202. continue;
  1203. }
  1204. if (ptrlen_startswith(command, PTRLEN_LITERAL("-p "), &command)) {
  1205. preserve = true;
  1206. continue;
  1207. }
  1208. if (ptrlen_startswith(command, PTRLEN_LITERAL("-d "), &command)) {
  1209. targetshouldbedirectory = true;
  1210. continue;
  1211. }
  1212. break;
  1213. }
  1214. if (ptrlen_startswith(command, PTRLEN_LITERAL("-t "), &command)) {
  1215. ScpSink *scp = scp_sink_new(sc, sftpserver_vt, command,
  1216. targetshouldbedirectory);
  1217. return &scp->scpserver;
  1218. } else if (ptrlen_startswith(command, PTRLEN_LITERAL("-f "), &command)) {
  1219. ScpSource *scp = scp_source_new(sc, sftpserver_vt, command);
  1220. scp->recursive = recursive;
  1221. scp->send_file_times = preserve;
  1222. return &scp->scpserver;
  1223. } else {
  1224. ScpError *scp = scp_error_new(
  1225. sc, "Unable to parse scp command: '%.*s'",
  1226. PTRLEN_PRINTF(command_orig));
  1227. return &scp->scpserver;
  1228. }
  1229. }