psftp.c 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922
  1. /*
  2. * psftp.c: (platform-independent) front end for PSFTP.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <stdarg.h>
  7. #include <assert.h>
  8. #include <limits.h>
  9. #include "putty.h"
  10. #include "psftp.h"
  11. #include "storage.h"
  12. #include "ssh.h"
  13. #include "ssh/sftp.h"
  14. /*
  15. * Since SFTP is a request-response oriented protocol, it requires
  16. * no buffer management: when we send data, we stop and wait for an
  17. * acknowledgement _anyway_, and so we can't possibly overfill our
  18. * send buffer.
  19. */
  20. static int psftp_connect(char *userhost, char *user, int portnumber);
  21. static int do_sftp_init(void);
  22. static void do_sftp_cleanup(void);
  23. /* ----------------------------------------------------------------------
  24. * sftp client state.
  25. */
  26. static char *pwd, *homedir;
  27. static LogContext *psftp_logctx = NULL;
  28. static Backend *backend;
  29. static Conf *conf;
  30. static bool sent_eof = false;
  31. /* ------------------------------------------------------------
  32. * Seat vtable.
  33. */
  34. static size_t psftp_output(Seat *, SeatOutputType type, const void *, size_t);
  35. static bool psftp_eof(Seat *);
  36. static const SeatVtable psftp_seat_vt = {
  37. .output = psftp_output,
  38. .eof = psftp_eof,
  39. .sent = nullseat_sent,
  40. .banner = nullseat_banner_to_stderr,
  41. .get_userpass_input = filexfer_get_userpass_input,
  42. .notify_session_started = nullseat_notify_session_started,
  43. .notify_remote_exit = nullseat_notify_remote_exit,
  44. .notify_remote_disconnect = nullseat_notify_remote_disconnect,
  45. .connection_fatal = console_connection_fatal,
  46. .update_specials_menu = nullseat_update_specials_menu,
  47. .get_ttymode = nullseat_get_ttymode,
  48. .set_busy_status = nullseat_set_busy_status,
  49. .confirm_ssh_host_key = console_confirm_ssh_host_key,
  50. .confirm_weak_crypto_primitive = console_confirm_weak_crypto_primitive,
  51. .confirm_weak_cached_hostkey = console_confirm_weak_cached_hostkey,
  52. .prompt_descriptions = console_prompt_descriptions,
  53. .is_utf8 = nullseat_is_never_utf8,
  54. .echoedit_update = nullseat_echoedit_update,
  55. .get_x_display = nullseat_get_x_display,
  56. .get_windowid = nullseat_get_windowid,
  57. .get_window_pixel_size = nullseat_get_window_pixel_size,
  58. .stripctrl_new = console_stripctrl_new,
  59. .set_trust_status = nullseat_set_trust_status,
  60. .can_set_trust_status = nullseat_can_set_trust_status_yes,
  61. .has_mixed_input_stream = nullseat_has_mixed_input_stream_no,
  62. .verbose = cmdline_seat_verbose,
  63. .interactive = nullseat_interactive_yes,
  64. .get_cursor_position = nullseat_get_cursor_position,
  65. };
  66. static Seat psftp_seat[1] = {{ &psftp_seat_vt }};
  67. /* ----------------------------------------------------------------------
  68. * A nasty loop macro that lets me get an escape-sequence sanitised
  69. * version of a string for display, and free it automatically
  70. * afterwards.
  71. */
  72. static StripCtrlChars *string_scc;
  73. #define with_stripctrl(varname, input) \
  74. for (char *varname = stripctrl_string(string_scc, input); varname; \
  75. sfree(varname), varname = NULL)
  76. /* ----------------------------------------------------------------------
  77. * Manage sending requests and waiting for replies.
  78. */
  79. struct sftp_packet *sftp_wait_for_reply(struct sftp_request *req)
  80. {
  81. struct sftp_packet *pktin;
  82. struct sftp_request *rreq;
  83. sftp_register(req);
  84. pktin = sftp_recv();
  85. if (pktin == NULL) {
  86. seat_connection_fatal(
  87. psftp_seat, "did not receive SFTP response packet from server");
  88. }
  89. rreq = sftp_find_request(pktin);
  90. if (rreq != req) {
  91. seat_connection_fatal(
  92. psftp_seat,
  93. "unable to understand SFTP response packet from server: %s",
  94. fxp_error());
  95. }
  96. return pktin;
  97. }
  98. /* ----------------------------------------------------------------------
  99. * Higher-level helper functions used in commands.
  100. */
  101. /*
  102. * Attempt to canonify a pathname starting from the pwd. If
  103. * canonification fails, at least fall back to returning a _valid_
  104. * pathname (though it may be ugly, eg /home/simon/../foobar).
  105. */
  106. char *canonify(const char *name)
  107. {
  108. char *fullname, *canonname;
  109. struct sftp_packet *pktin;
  110. struct sftp_request *req;
  111. if (name[0] == '/') {
  112. fullname = dupstr(name);
  113. } else {
  114. const char *slash;
  115. if (pwd[strlen(pwd) - 1] == '/')
  116. slash = "";
  117. else
  118. slash = "/";
  119. fullname = dupcat(pwd, slash, name);
  120. }
  121. req = fxp_realpath_send(fullname);
  122. pktin = sftp_wait_for_reply(req);
  123. canonname = fxp_realpath_recv(pktin, req);
  124. if (canonname) {
  125. sfree(fullname);
  126. return canonname;
  127. } else {
  128. /*
  129. * Attempt number 2. Some FXP_REALPATH implementations
  130. * (glibc-based ones, in particular) require the _whole_
  131. * path to point to something that exists, whereas others
  132. * (BSD-based) only require all but the last component to
  133. * exist. So if the first call failed, we should strip off
  134. * everything from the last slash onwards and try again,
  135. * then put the final component back on.
  136. *
  137. * Special cases:
  138. *
  139. * - if the last component is "/." or "/..", then we don't
  140. * bother trying this because there's no way it can work.
  141. *
  142. * - if the thing actually ends with a "/", we remove it
  143. * before we start. Except if the string is "/" itself
  144. * (although I can't see why we'd have got here if so,
  145. * because surely "/" would have worked the first
  146. * time?), in which case we don't bother.
  147. *
  148. * - if there's no slash in the string at all, give up in
  149. * confusion (we expect at least one because of the way
  150. * we constructed the string).
  151. */
  152. int i;
  153. char *returnname;
  154. i = strlen(fullname);
  155. if (i > 2 && fullname[i - 1] == '/')
  156. fullname[--i] = '\0'; /* strip trailing / unless at pos 0 */
  157. while (i > 0 && fullname[--i] != '/');
  158. /*
  159. * Give up on special cases.
  160. */
  161. if (fullname[i] != '/' || /* no slash at all */
  162. !strcmp(fullname + i, "/.") || /* ends in /. */
  163. !strcmp(fullname + i, "/..") || /* ends in /.. */
  164. !strcmp(fullname, "/")) {
  165. return fullname;
  166. }
  167. /*
  168. * Now i points at the slash. Deal with the final special
  169. * case i==0 (ie the whole path was "/nonexistentfile").
  170. */
  171. fullname[i] = '\0'; /* separate the string */
  172. if (i == 0) {
  173. req = fxp_realpath_send("/");
  174. } else {
  175. req = fxp_realpath_send(fullname);
  176. }
  177. pktin = sftp_wait_for_reply(req);
  178. canonname = fxp_realpath_recv(pktin, req);
  179. if (!canonname) {
  180. /* Even that failed. Restore our best guess at the
  181. * constructed filename and give up */
  182. fullname[i] = '/'; /* restore slash and last component */
  183. return fullname;
  184. }
  185. /*
  186. * We have a canonical name for all but the last path
  187. * component. Concatenate the last component and return.
  188. */
  189. returnname = dupcat(canonname,
  190. (strendswith(canonname, "/") ? "" : "/"),
  191. fullname + i + 1);
  192. sfree(fullname);
  193. sfree(canonname);
  194. return returnname;
  195. }
  196. }
  197. static int bare_name_compare(const void *av, const void *bv)
  198. {
  199. const char **a = (const char **) av;
  200. const char **b = (const char **) bv;
  201. return strcmp(*a, *b);
  202. }
  203. static void not_connected(void)
  204. {
  205. printf("psftp: not connected to a host; use \"open host.name\"\n");
  206. }
  207. /* ----------------------------------------------------------------------
  208. * The meat of the `get' and `put' commands.
  209. */
  210. bool sftp_get_file(char *fname, char *outfname, bool recurse, bool restart)
  211. {
  212. struct fxp_handle *fh;
  213. struct sftp_packet *pktin;
  214. struct sftp_request *req;
  215. struct fxp_xfer *xfer;
  216. uint64_t offset;
  217. WFile *file;
  218. bool toret, shown_err = false;
  219. struct fxp_attrs attrs;
  220. /*
  221. * In recursive mode, see if we're dealing with a directory.
  222. * (If we're not in recursive mode, we need not even check: the
  223. * subsequent FXP_OPEN will return a usable error message.)
  224. */
  225. if (recurse) {
  226. bool result;
  227. req = fxp_stat_send(fname);
  228. pktin = sftp_wait_for_reply(req);
  229. result = fxp_stat_recv(pktin, req, &attrs);
  230. if (result &&
  231. (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
  232. (attrs.permissions & 0040000)) {
  233. struct fxp_handle *dirhandle;
  234. size_t nnames, namesize;
  235. struct fxp_name **ournames;
  236. struct fxp_names *names;
  237. int i;
  238. /*
  239. * First, attempt to create the destination directory,
  240. * unless it already exists.
  241. */
  242. if (file_type(outfname) != FILE_TYPE_DIRECTORY &&
  243. !create_directory(outfname)) {
  244. with_stripctrl(san, outfname)
  245. printf("%s: Cannot create directory\n", san);
  246. return false;
  247. }
  248. /*
  249. * Now get the list of filenames in the remote
  250. * directory.
  251. */
  252. req = fxp_opendir_send(fname);
  253. pktin = sftp_wait_for_reply(req);
  254. dirhandle = fxp_opendir_recv(pktin, req);
  255. if (!dirhandle) {
  256. with_stripctrl(san, fname)
  257. printf("%s: unable to open directory: %s\n",
  258. san, fxp_error());
  259. return false;
  260. }
  261. nnames = namesize = 0;
  262. ournames = NULL;
  263. while (1) {
  264. int i;
  265. req = fxp_readdir_send(dirhandle);
  266. pktin = sftp_wait_for_reply(req);
  267. names = fxp_readdir_recv(pktin, req);
  268. if (names == NULL) {
  269. if (fxp_error_type() == SSH_FX_EOF)
  270. break;
  271. with_stripctrl(san, fname)
  272. printf("%s: reading directory: %s\n",
  273. san, fxp_error());
  274. req = fxp_close_send(dirhandle);
  275. pktin = sftp_wait_for_reply(req);
  276. fxp_close_recv(pktin, req);
  277. sfree(ournames);
  278. return false;
  279. }
  280. if (names->nnames == 0) {
  281. fxp_free_names(names);
  282. break;
  283. }
  284. sgrowarrayn(ournames, namesize, nnames, names->nnames);
  285. for (i = 0; i < names->nnames; i++)
  286. if (strcmp(names->names[i].filename, ".") &&
  287. strcmp(names->names[i].filename, "..")) {
  288. if (!vet_filename(names->names[i].filename)) {
  289. with_stripctrl(san, names->names[i].filename)
  290. printf("ignoring potentially dangerous server-"
  291. "supplied filename '%s'\n", san);
  292. } else {
  293. ournames[nnames++] =
  294. fxp_dup_name(&names->names[i]);
  295. }
  296. }
  297. fxp_free_names(names);
  298. }
  299. req = fxp_close_send(dirhandle);
  300. pktin = sftp_wait_for_reply(req);
  301. fxp_close_recv(pktin, req);
  302. /*
  303. * Sort the names into a clear order. This ought to
  304. * make things more predictable when we're doing a
  305. * reget of the same directory, just in case two
  306. * readdirs on the same remote directory return a
  307. * different order.
  308. */
  309. if (nnames > 0)
  310. qsort(ournames, nnames, sizeof(*ournames), sftp_name_compare);
  311. /*
  312. * If we're in restart mode, find the last filename on
  313. * this list that already exists. We may have to do a
  314. * reget on _that_ file, but shouldn't have to do
  315. * anything on the previous files.
  316. *
  317. * If none of them exists, of course, we start at 0.
  318. */
  319. i = 0;
  320. if (restart) {
  321. while (i < nnames) {
  322. char *nextoutfname;
  323. bool nonexistent;
  324. nextoutfname = dir_file_cat(outfname,
  325. ournames[i]->filename);
  326. nonexistent = (file_type(nextoutfname) ==
  327. FILE_TYPE_NONEXISTENT);
  328. sfree(nextoutfname);
  329. if (nonexistent)
  330. break;
  331. i++;
  332. }
  333. if (i > 0)
  334. i--;
  335. }
  336. /*
  337. * Now we're ready to recurse. Starting at ournames[i]
  338. * and continuing on to the end of the list, we
  339. * construct a new source and target file name, and
  340. * call sftp_get_file again.
  341. */
  342. for (; i < nnames; i++) {
  343. char *nextfname, *nextoutfname;
  344. bool retd;
  345. nextfname = dupcat(fname, "/", ournames[i]->filename);
  346. nextoutfname = dir_file_cat(outfname, ournames[i]->filename);
  347. retd = sftp_get_file(
  348. nextfname, nextoutfname, recurse, restart);
  349. restart = false; /* after first partial file, do full */
  350. sfree(nextoutfname);
  351. sfree(nextfname);
  352. if (!retd) {
  353. for (i = 0; i < nnames; i++) {
  354. fxp_free_name(ournames[i]);
  355. }
  356. sfree(ournames);
  357. return false;
  358. }
  359. }
  360. /*
  361. * Done this recursion level. Free everything.
  362. */
  363. for (i = 0; i < nnames; i++) {
  364. fxp_free_name(ournames[i]);
  365. }
  366. sfree(ournames);
  367. return true;
  368. }
  369. }
  370. req = fxp_stat_send(fname);
  371. pktin = sftp_wait_for_reply(req);
  372. if (!fxp_stat_recv(pktin, req, &attrs))
  373. attrs.flags = 0;
  374. req = fxp_open_send(fname, SSH_FXF_READ, NULL);
  375. pktin = sftp_wait_for_reply(req);
  376. fh = fxp_open_recv(pktin, req);
  377. if (!fh) {
  378. with_stripctrl(san, fname)
  379. printf("%s: open for read: %s\n", san, fxp_error());
  380. return false;
  381. }
  382. if (restart) {
  383. file = open_existing_wfile(outfname, NULL);
  384. } else {
  385. file = open_new_file(outfname, GET_PERMISSIONS(attrs, -1));
  386. }
  387. if (!file) {
  388. with_stripctrl(san, outfname)
  389. printf("local: unable to open %s\n", san);
  390. req = fxp_close_send(fh);
  391. pktin = sftp_wait_for_reply(req);
  392. fxp_close_recv(pktin, req);
  393. return false;
  394. }
  395. if (restart) {
  396. if (seek_file(file, 0, FROM_END) == -1) {
  397. close_wfile(file);
  398. with_stripctrl(san, outfname)
  399. printf("reget: cannot restart %s - file too large\n", san);
  400. req = fxp_close_send(fh);
  401. pktin = sftp_wait_for_reply(req);
  402. fxp_close_recv(pktin, req);
  403. return false;
  404. }
  405. offset = get_file_posn(file);
  406. printf("reget: restarting at file position %"PRIu64"\n", offset);
  407. } else {
  408. offset = 0;
  409. }
  410. with_stripctrl(san, fname) {
  411. with_stripctrl(sano, outfname)
  412. printf("remote:%s => local:%s\n", san, sano);
  413. }
  414. /*
  415. * FIXME: we can use FXP_FSTAT here to get the file size, and
  416. * thus put up a progress bar.
  417. */
  418. toret = true;
  419. xfer = xfer_download_init(fh, offset);
  420. while (!xfer_done(xfer)) {
  421. void *vbuf;
  422. int retd, len;
  423. int wpos, wlen;
  424. xfer_download_queue(xfer);
  425. pktin = sftp_recv();
  426. retd = xfer_download_gotpkt(xfer, pktin);
  427. if (retd <= 0) {
  428. if (!shown_err) {
  429. printf("error while reading: %s\n", fxp_error());
  430. shown_err = true;
  431. }
  432. if (retd == INT_MIN) /* pktin not even freed */
  433. sfree(pktin);
  434. toret = false;
  435. }
  436. while (xfer_download_data(xfer, &vbuf, &len)) {
  437. unsigned char *buf = (unsigned char *)vbuf;
  438. wpos = 0;
  439. while (wpos < len) {
  440. wlen = write_to_file(file, buf + wpos, len - wpos);
  441. if (wlen <= 0) {
  442. printf("error while writing local file\n");
  443. toret = false;
  444. xfer_set_error(xfer);
  445. break;
  446. }
  447. wpos += wlen;
  448. }
  449. if (wpos < len) { /* we had an error */
  450. toret = false;
  451. xfer_set_error(xfer);
  452. }
  453. sfree(vbuf);
  454. }
  455. }
  456. xfer_cleanup(xfer);
  457. close_wfile(file);
  458. req = fxp_close_send(fh);
  459. pktin = sftp_wait_for_reply(req);
  460. fxp_close_recv(pktin, req);
  461. return toret;
  462. }
  463. bool sftp_put_file(char *fname, char *outfname, bool recurse, bool restart)
  464. {
  465. struct fxp_handle *fh;
  466. struct fxp_xfer *xfer;
  467. struct sftp_packet *pktin;
  468. struct sftp_request *req;
  469. uint64_t offset;
  470. RFile *file;
  471. bool err = false, eof;
  472. struct fxp_attrs attrs;
  473. long permissions;
  474. /*
  475. * In recursive mode, see if we're dealing with a directory.
  476. * (If we're not in recursive mode, we need not even check: the
  477. * subsequent fopen will return an error message.)
  478. */
  479. if (recurse && file_type(fname) == FILE_TYPE_DIRECTORY) {
  480. bool result;
  481. size_t nnames, namesize;
  482. char *name, **ournames;
  483. const char *opendir_err;
  484. DirHandle *dh;
  485. size_t i;
  486. /*
  487. * First, attempt to create the destination directory,
  488. * unless it already exists.
  489. */
  490. req = fxp_stat_send(outfname);
  491. pktin = sftp_wait_for_reply(req);
  492. result = fxp_stat_recv(pktin, req, &attrs);
  493. if (!result ||
  494. !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||
  495. !(attrs.permissions & 0040000)) {
  496. req = fxp_mkdir_send(outfname, NULL);
  497. pktin = sftp_wait_for_reply(req);
  498. result = fxp_mkdir_recv(pktin, req);
  499. if (!result) {
  500. printf("%s: create directory: %s\n",
  501. outfname, fxp_error());
  502. return false;
  503. }
  504. }
  505. /*
  506. * Now get the list of filenames in the local directory.
  507. */
  508. nnames = namesize = 0;
  509. ournames = NULL;
  510. dh = open_directory(fname, &opendir_err);
  511. if (!dh) {
  512. printf("%s: unable to open directory: %s\n", fname, opendir_err);
  513. return false;
  514. }
  515. while ((name = read_filename(dh)) != NULL) {
  516. sgrowarray(ournames, namesize, nnames);
  517. ournames[nnames++] = name;
  518. }
  519. close_directory(dh);
  520. /*
  521. * Sort the names into a clear order. This ought to make
  522. * things more predictable when we're doing a reput of the
  523. * same directory, just in case two readdirs on the same
  524. * local directory return a different order.
  525. */
  526. if (nnames > 0)
  527. qsort(ournames, nnames, sizeof(*ournames), bare_name_compare);
  528. /*
  529. * If we're in restart mode, find the last filename on this
  530. * list that already exists. We may have to do a reput on
  531. * _that_ file, but shouldn't have to do anything on the
  532. * previous files.
  533. *
  534. * If none of them exists, of course, we start at 0.
  535. */
  536. i = 0;
  537. if (restart) {
  538. while (i < nnames) {
  539. char *nextoutfname;
  540. nextoutfname = dupcat(outfname, "/", ournames[i]);
  541. req = fxp_stat_send(nextoutfname);
  542. pktin = sftp_wait_for_reply(req);
  543. result = fxp_stat_recv(pktin, req, &attrs);
  544. sfree(nextoutfname);
  545. if (!result)
  546. break;
  547. i++;
  548. }
  549. if (i > 0)
  550. i--;
  551. }
  552. /*
  553. * Now we're ready to recurse. Starting at ournames[i]
  554. * and continuing on to the end of the list, we
  555. * construct a new source and target file name, and
  556. * call sftp_put_file again.
  557. */
  558. for (; i < nnames; i++) {
  559. char *nextfname, *nextoutfname;
  560. bool retd;
  561. nextfname = dir_file_cat(fname, ournames[i]);
  562. nextoutfname = dupcat(outfname, "/", ournames[i]);
  563. retd = sftp_put_file(nextfname, nextoutfname, recurse, restart);
  564. restart = false; /* after first partial file, do full */
  565. sfree(nextoutfname);
  566. sfree(nextfname);
  567. if (!retd) {
  568. for (size_t i = 0; i < nnames; i++) {
  569. sfree(ournames[i]);
  570. }
  571. sfree(ournames);
  572. return false;
  573. }
  574. }
  575. /*
  576. * Done this recursion level. Free everything.
  577. */
  578. for (size_t i = 0; i < nnames; i++) {
  579. sfree(ournames[i]);
  580. }
  581. sfree(ournames);
  582. return true;
  583. }
  584. file = open_existing_file(fname, NULL, NULL, NULL, &permissions);
  585. if (!file) {
  586. printf("local: unable to open %s\n", fname);
  587. return false;
  588. }
  589. attrs.flags = 0;
  590. PUT_PERMISSIONS(attrs, permissions);
  591. if (restart) {
  592. req = fxp_open_send(outfname, SSH_FXF_WRITE, &attrs);
  593. } else {
  594. req = fxp_open_send(outfname,
  595. SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC,
  596. &attrs);
  597. }
  598. pktin = sftp_wait_for_reply(req);
  599. fh = fxp_open_recv(pktin, req);
  600. if (!fh) {
  601. close_rfile(file);
  602. printf("%s: open for write: %s\n", outfname, fxp_error());
  603. return false;
  604. }
  605. if (restart) {
  606. struct fxp_attrs attrs;
  607. bool retd;
  608. req = fxp_fstat_send(fh);
  609. pktin = sftp_wait_for_reply(req);
  610. retd = fxp_fstat_recv(pktin, req, &attrs);
  611. if (!retd) {
  612. printf("read size of %s: %s\n", outfname, fxp_error());
  613. err = true;
  614. goto cleanup;
  615. }
  616. if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) {
  617. printf("read size of %s: size was not given\n", outfname);
  618. err = true;
  619. goto cleanup;
  620. }
  621. offset = attrs.size;
  622. printf("reput: restarting at file position %"PRIu64"\n", offset);
  623. if (seek_file((WFile *)file, offset, FROM_START) != 0)
  624. seek_file((WFile *)file, 0, FROM_END); /* *shrug* */
  625. } else {
  626. offset = 0;
  627. }
  628. printf("local:%s => remote:%s\n", fname, outfname);
  629. /*
  630. * FIXME: we can use FXP_FSTAT here to get the file size, and
  631. * thus put up a progress bar.
  632. */
  633. xfer = xfer_upload_init(fh, offset);
  634. eof = false;
  635. while ((!err && !eof) || !xfer_done(xfer)) {
  636. char buffer[4096];
  637. int len, ret;
  638. while (xfer_upload_ready(xfer) && !err && !eof) {
  639. len = read_from_file(file, buffer, sizeof(buffer));
  640. if (len == -1) {
  641. printf("error while reading local file\n");
  642. err = true;
  643. } else if (len == 0) {
  644. eof = true;
  645. } else {
  646. xfer_upload_data(xfer, buffer, len);
  647. }
  648. }
  649. if (toplevel_callback_pending() && !err && !eof) {
  650. /* If we have pending callbacks, they might make
  651. * xfer_upload_ready start to return true. So we should
  652. * run them and then re-check xfer_upload_ready, before
  653. * we go as far as waiting for an entire packet to
  654. * arrive. */
  655. run_toplevel_callbacks();
  656. continue;
  657. }
  658. if (!xfer_done(xfer)) {
  659. pktin = sftp_recv();
  660. ret = xfer_upload_gotpkt(xfer, pktin);
  661. if (ret <= 0) {
  662. if (ret == INT_MIN) /* pktin not even freed */
  663. sfree(pktin);
  664. if (!err) {
  665. printf("error while writing: %s\n", fxp_error());
  666. err = true;
  667. }
  668. }
  669. }
  670. }
  671. xfer_cleanup(xfer);
  672. cleanup:
  673. req = fxp_close_send(fh);
  674. pktin = sftp_wait_for_reply(req);
  675. if (!fxp_close_recv(pktin, req)) {
  676. if (!err) {
  677. printf("error while closing: %s", fxp_error());
  678. err = true;
  679. }
  680. }
  681. close_rfile(file);
  682. return !err;
  683. }
  684. /* ----------------------------------------------------------------------
  685. * A remote wildcard matcher, providing a similar interface to the
  686. * local one in psftp.h.
  687. */
  688. typedef struct SftpWildcardMatcher {
  689. struct fxp_handle *dirh;
  690. struct fxp_names *names;
  691. int namepos;
  692. char *wildcard, *prefix;
  693. } SftpWildcardMatcher;
  694. SftpWildcardMatcher *sftp_begin_wildcard_matching(char *name)
  695. {
  696. struct sftp_packet *pktin;
  697. struct sftp_request *req;
  698. char *wildcard;
  699. char *unwcdir, *tmpdir, *cdir;
  700. int len;
  701. bool check;
  702. SftpWildcardMatcher *swcm;
  703. struct fxp_handle *dirh;
  704. /*
  705. * We don't handle multi-level wildcards; so we expect to find
  706. * a fully specified directory part, followed by a wildcard
  707. * after that.
  708. */
  709. wildcard = stripslashes(name, false);
  710. unwcdir = dupstr(name);
  711. len = wildcard - name;
  712. unwcdir[len] = '\0';
  713. if (len > 0 && unwcdir[len-1] == '/')
  714. unwcdir[len-1] = '\0';
  715. tmpdir = snewn(1 + len, char);
  716. check = wc_unescape(tmpdir, unwcdir);
  717. sfree(tmpdir);
  718. if (!check) {
  719. printf("Multiple-level wildcards are not supported\n");
  720. sfree(unwcdir);
  721. return NULL;
  722. }
  723. cdir = canonify(unwcdir);
  724. req = fxp_opendir_send(cdir);
  725. pktin = sftp_wait_for_reply(req);
  726. dirh = fxp_opendir_recv(pktin, req);
  727. if (dirh) {
  728. swcm = snew(SftpWildcardMatcher);
  729. swcm->dirh = dirh;
  730. swcm->names = NULL;
  731. swcm->wildcard = dupstr(wildcard);
  732. swcm->prefix = unwcdir;
  733. } else {
  734. printf("Unable to open %s: %s\n", cdir, fxp_error());
  735. swcm = NULL;
  736. sfree(unwcdir);
  737. }
  738. sfree(cdir);
  739. return swcm;
  740. }
  741. char *sftp_wildcard_get_filename(SftpWildcardMatcher *swcm)
  742. {
  743. struct fxp_name *name;
  744. struct sftp_packet *pktin;
  745. struct sftp_request *req;
  746. while (1) {
  747. if (swcm->names && swcm->namepos >= swcm->names->nnames) {
  748. fxp_free_names(swcm->names);
  749. swcm->names = NULL;
  750. }
  751. if (!swcm->names) {
  752. req = fxp_readdir_send(swcm->dirh);
  753. pktin = sftp_wait_for_reply(req);
  754. swcm->names = fxp_readdir_recv(pktin, req);
  755. if (!swcm->names) {
  756. if (fxp_error_type() != SSH_FX_EOF) {
  757. with_stripctrl(san, swcm->prefix)
  758. printf("%s: reading directory: %s\n",
  759. san, fxp_error());
  760. }
  761. return NULL;
  762. } else if (swcm->names->nnames == 0) {
  763. /*
  764. * Another failure mode which we treat as EOF is if
  765. * the server reports success from FXP_READDIR but
  766. * returns no actual names. This is unusual, since
  767. * from most servers you'd expect at least "." and
  768. * "..", but there's nothing forbidding a server from
  769. * omitting those if it wants to.
  770. */
  771. return NULL;
  772. }
  773. swcm->namepos = 0;
  774. }
  775. assert(swcm->names && swcm->namepos < swcm->names->nnames);
  776. name = &swcm->names->names[swcm->namepos++];
  777. if (!strcmp(name->filename, ".") || !strcmp(name->filename, ".."))
  778. continue; /* expected bad filenames */
  779. if (!vet_filename(name->filename)) {
  780. with_stripctrl(san, name->filename)
  781. printf("ignoring potentially dangerous server-"
  782. "supplied filename '%s'\n", san);
  783. continue; /* unexpected bad filename */
  784. }
  785. if (!wc_match(swcm->wildcard, name->filename))
  786. continue; /* doesn't match the wildcard */
  787. /*
  788. * We have a working filename. Return it.
  789. */
  790. return dupprintf("%s%s%s", swcm->prefix,
  791. (!swcm->prefix[0] ||
  792. swcm->prefix[strlen(swcm->prefix)-1]=='/' ?
  793. "" : "/"),
  794. name->filename);
  795. }
  796. }
  797. void sftp_finish_wildcard_matching(SftpWildcardMatcher *swcm)
  798. {
  799. struct sftp_packet *pktin;
  800. struct sftp_request *req;
  801. req = fxp_close_send(swcm->dirh);
  802. pktin = sftp_wait_for_reply(req);
  803. fxp_close_recv(pktin, req);
  804. if (swcm->names)
  805. fxp_free_names(swcm->names);
  806. sfree(swcm->prefix);
  807. sfree(swcm->wildcard);
  808. sfree(swcm);
  809. }
  810. /*
  811. * General function to match a potential wildcard in a filename
  812. * argument and iterate over every matching file. Used in several
  813. * PSFTP commands (rmdir, rm, chmod, mv).
  814. */
  815. bool wildcard_iterate(char *filename, bool (*func)(void *, char *), void *ctx)
  816. {
  817. char *unwcfname, *newname, *cname;
  818. bool is_wc, toret;
  819. unwcfname = snewn(strlen(filename)+1, char);
  820. is_wc = !wc_unescape(unwcfname, filename);
  821. if (is_wc) {
  822. SftpWildcardMatcher *swcm = sftp_begin_wildcard_matching(filename);
  823. bool matched = false;
  824. sfree(unwcfname);
  825. if (!swcm)
  826. return false;
  827. toret = true;
  828. while ( (newname = sftp_wildcard_get_filename(swcm)) != NULL ) {
  829. cname = canonify(newname);
  830. sfree(newname);
  831. matched = true;
  832. if (!func(ctx, cname))
  833. toret = false;
  834. sfree(cname);
  835. }
  836. if (!matched) {
  837. /* Politely warn the user that nothing matched. */
  838. printf("%s: nothing matched\n", filename);
  839. }
  840. sftp_finish_wildcard_matching(swcm);
  841. } else {
  842. cname = canonify(unwcfname);
  843. toret = func(ctx, cname);
  844. sfree(cname);
  845. sfree(unwcfname);
  846. }
  847. return toret;
  848. }
  849. /*
  850. * Handy helper function.
  851. */
  852. bool is_wildcard(char *name)
  853. {
  854. char *unwcfname = snewn(strlen(name)+1, char);
  855. bool is_wc = !wc_unescape(unwcfname, name);
  856. sfree(unwcfname);
  857. return is_wc;
  858. }
  859. /* ----------------------------------------------------------------------
  860. * Actual sftp commands.
  861. */
  862. struct sftp_command {
  863. char **words;
  864. size_t nwords, wordssize;
  865. int (*obey) (struct sftp_command *); /* returns <0 to quit */
  866. };
  867. int sftp_cmd_null(struct sftp_command *cmd)
  868. {
  869. return 1; /* success */
  870. }
  871. int sftp_cmd_unknown(struct sftp_command *cmd)
  872. {
  873. printf("psftp: unknown command \"%s\"\n", cmd->words[0]);
  874. return 0; /* failure */
  875. }
  876. int sftp_cmd_quit(struct sftp_command *cmd)
  877. {
  878. return -1;
  879. }
  880. int sftp_cmd_close(struct sftp_command *cmd)
  881. {
  882. if (!backend) {
  883. not_connected();
  884. return 0;
  885. }
  886. if (backend_connected(backend)) {
  887. char ch;
  888. backend_special(backend, SS_EOF, 0);
  889. sent_eof = true;
  890. sftp_recvdata(&ch, 1);
  891. }
  892. do_sftp_cleanup();
  893. return 1;
  894. }
  895. void list_directory_from_sftp_warn_unsorted(void)
  896. {
  897. printf("Directory is too large to sort; writing file names unsorted\n");
  898. }
  899. void list_directory_from_sftp_print(struct fxp_name *name)
  900. {
  901. with_stripctrl(san, name->longname)
  902. printf("%s\n", san);
  903. }
  904. /*
  905. * List a directory. If no arguments are given, list pwd; otherwise
  906. * list the directory given in words[1].
  907. */
  908. int sftp_cmd_ls(struct sftp_command *cmd)
  909. {
  910. struct fxp_handle *dirh;
  911. struct fxp_names *names;
  912. const char *dir;
  913. char *cdir, *unwcdir, *wildcard;
  914. struct sftp_packet *pktin;
  915. struct sftp_request *req;
  916. if (!backend) {
  917. not_connected();
  918. return 0;
  919. }
  920. if (cmd->nwords < 2)
  921. dir = ".";
  922. else
  923. dir = cmd->words[1];
  924. unwcdir = snewn(1 + strlen(dir), char);
  925. if (wc_unescape(unwcdir, dir)) {
  926. dir = unwcdir;
  927. wildcard = NULL;
  928. } else {
  929. char *tmpdir;
  930. int len;
  931. bool check;
  932. sfree(unwcdir);
  933. wildcard = stripslashes(dir, false);
  934. unwcdir = dupstr(dir);
  935. len = wildcard - dir;
  936. unwcdir[len] = '\0';
  937. if (len > 0 && unwcdir[len-1] == '/')
  938. unwcdir[len-1] = '\0';
  939. tmpdir = snewn(1 + len, char);
  940. check = wc_unescape(tmpdir, unwcdir);
  941. sfree(tmpdir);
  942. if (!check) {
  943. printf("Multiple-level wildcards are not supported\n");
  944. sfree(unwcdir);
  945. return 0;
  946. }
  947. dir = unwcdir;
  948. }
  949. cdir = canonify(dir);
  950. with_stripctrl(san, cdir)
  951. printf("Listing directory %s\n", san);
  952. req = fxp_opendir_send(cdir);
  953. pktin = sftp_wait_for_reply(req);
  954. dirh = fxp_opendir_recv(pktin, req);
  955. if (dirh == NULL) {
  956. printf("Unable to open %s: %s\n", dir, fxp_error());
  957. sfree(cdir);
  958. sfree(unwcdir);
  959. return 0;
  960. } else {
  961. struct list_directory_from_sftp_ctx *ctx =
  962. list_directory_from_sftp_new();
  963. while (1) {
  964. req = fxp_readdir_send(dirh);
  965. pktin = sftp_wait_for_reply(req);
  966. names = fxp_readdir_recv(pktin, req);
  967. if (names == NULL) {
  968. if (fxp_error_type() == SSH_FX_EOF)
  969. break;
  970. printf("Reading directory %s: %s\n", dir, fxp_error());
  971. break;
  972. }
  973. if (names->nnames == 0) {
  974. fxp_free_names(names);
  975. break;
  976. }
  977. for (size_t i = 0; i < names->nnames; i++)
  978. if (!wildcard || wc_match(wildcard, names->names[i].filename))
  979. list_directory_from_sftp_feed(ctx, &names->names[i]);
  980. fxp_free_names(names);
  981. }
  982. req = fxp_close_send(dirh);
  983. pktin = sftp_wait_for_reply(req);
  984. fxp_close_recv(pktin, req);
  985. list_directory_from_sftp_finish(ctx);
  986. list_directory_from_sftp_free(ctx);
  987. }
  988. sfree(cdir);
  989. sfree(unwcdir);
  990. return 1;
  991. }
  992. /*
  993. * Change directories. We do this by canonifying the new name, then
  994. * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
  995. */
  996. int sftp_cmd_cd(struct sftp_command *cmd)
  997. {
  998. struct fxp_handle *dirh;
  999. struct sftp_packet *pktin;
  1000. struct sftp_request *req;
  1001. char *dir;
  1002. if (!backend) {
  1003. not_connected();
  1004. return 0;
  1005. }
  1006. if (cmd->nwords < 2)
  1007. dir = dupstr(homedir);
  1008. else {
  1009. dir = canonify(cmd->words[1]);
  1010. }
  1011. req = fxp_opendir_send(dir);
  1012. pktin = sftp_wait_for_reply(req);
  1013. dirh = fxp_opendir_recv(pktin, req);
  1014. if (!dirh) {
  1015. with_stripctrl(san, dir)
  1016. printf("Directory %s: %s\n", san, fxp_error());
  1017. sfree(dir);
  1018. return 0;
  1019. }
  1020. req = fxp_close_send(dirh);
  1021. pktin = sftp_wait_for_reply(req);
  1022. fxp_close_recv(pktin, req);
  1023. sfree(pwd);
  1024. pwd = dir;
  1025. with_stripctrl(san, pwd)
  1026. printf("Remote directory is now %s\n", san);
  1027. return 1;
  1028. }
  1029. /*
  1030. * Print current directory. Easy as pie.
  1031. */
  1032. int sftp_cmd_pwd(struct sftp_command *cmd)
  1033. {
  1034. if (!backend) {
  1035. not_connected();
  1036. return 0;
  1037. }
  1038. with_stripctrl(san, pwd)
  1039. printf("Remote directory is %s\n", san);
  1040. return 1;
  1041. }
  1042. /*
  1043. * Get a file and save it at the local end. We have three very
  1044. * similar commands here. The basic one is `get'; `reget' differs
  1045. * in that it checks for the existence of the destination file and
  1046. * starts from where a previous aborted transfer left off; `mget'
  1047. * differs in that it interprets all its arguments as files to
  1048. * transfer (never as a different local name for a remote file) and
  1049. * can handle wildcards.
  1050. */
  1051. int sftp_general_get(struct sftp_command *cmd, bool restart, bool multiple)
  1052. {
  1053. char *fname, *unwcfname, *origfname, *origwfname, *outfname;
  1054. int i, toret;
  1055. bool recurse = false;
  1056. if (!backend) {
  1057. not_connected();
  1058. return 0;
  1059. }
  1060. i = 1;
  1061. while (i < cmd->nwords && cmd->words[i][0] == '-') {
  1062. if (!strcmp(cmd->words[i], "--")) {
  1063. /* finish processing options */
  1064. i++;
  1065. break;
  1066. } else if (!strcmp(cmd->words[i], "-r")) {
  1067. recurse = true;
  1068. } else {
  1069. printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]);
  1070. return 0;
  1071. }
  1072. i++;
  1073. }
  1074. if (i >= cmd->nwords) {
  1075. printf("%s: expects a filename\n", cmd->words[0]);
  1076. return 0;
  1077. }
  1078. toret = 1;
  1079. do {
  1080. SftpWildcardMatcher *swcm;
  1081. origfname = cmd->words[i++];
  1082. unwcfname = snewn(strlen(origfname)+1, char);
  1083. if (multiple && !wc_unescape(unwcfname, origfname)) {
  1084. swcm = sftp_begin_wildcard_matching(origfname);
  1085. if (!swcm) {
  1086. sfree(unwcfname);
  1087. continue;
  1088. }
  1089. origwfname = sftp_wildcard_get_filename(swcm);
  1090. if (!origwfname) {
  1091. /* Politely warn the user that nothing matched. */
  1092. printf("%s: nothing matched\n", origfname);
  1093. sftp_finish_wildcard_matching(swcm);
  1094. sfree(unwcfname);
  1095. continue;
  1096. }
  1097. } else {
  1098. origwfname = origfname;
  1099. swcm = NULL;
  1100. }
  1101. while (origwfname) {
  1102. fname = canonify(origwfname);
  1103. if (!multiple && i < cmd->nwords)
  1104. outfname = cmd->words[i++];
  1105. else
  1106. outfname = stripslashes(origwfname, false);
  1107. toret = sftp_get_file(fname, outfname, recurse, restart);
  1108. sfree(fname);
  1109. if (swcm) {
  1110. sfree(origwfname);
  1111. origwfname = sftp_wildcard_get_filename(swcm);
  1112. } else {
  1113. origwfname = NULL;
  1114. }
  1115. }
  1116. sfree(unwcfname);
  1117. if (swcm)
  1118. sftp_finish_wildcard_matching(swcm);
  1119. if (!toret)
  1120. return toret;
  1121. } while (multiple && i < cmd->nwords);
  1122. return toret;
  1123. }
  1124. int sftp_cmd_get(struct sftp_command *cmd)
  1125. {
  1126. return sftp_general_get(cmd, false, false);
  1127. }
  1128. int sftp_cmd_mget(struct sftp_command *cmd)
  1129. {
  1130. return sftp_general_get(cmd, false, true);
  1131. }
  1132. int sftp_cmd_reget(struct sftp_command *cmd)
  1133. {
  1134. return sftp_general_get(cmd, true, false);
  1135. }
  1136. /*
  1137. * Send a file and store it at the remote end. We have three very
  1138. * similar commands here. The basic one is `put'; `reput' differs
  1139. * in that it checks for the existence of the destination file and
  1140. * starts from where a previous aborted transfer left off; `mput'
  1141. * differs in that it interprets all its arguments as files to
  1142. * transfer (never as a different remote name for a local file) and
  1143. * can handle wildcards.
  1144. */
  1145. int sftp_general_put(struct sftp_command *cmd, bool restart, bool multiple)
  1146. {
  1147. char *fname, *wfname, *origoutfname, *outfname;
  1148. int i;
  1149. int toret;
  1150. bool recurse = false;
  1151. if (!backend) {
  1152. not_connected();
  1153. return 0;
  1154. }
  1155. i = 1;
  1156. while (i < cmd->nwords && cmd->words[i][0] == '-') {
  1157. if (!strcmp(cmd->words[i], "--")) {
  1158. /* finish processing options */
  1159. i++;
  1160. break;
  1161. } else if (!strcmp(cmd->words[i], "-r")) {
  1162. recurse = true;
  1163. } else {
  1164. printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]);
  1165. return 0;
  1166. }
  1167. i++;
  1168. }
  1169. if (i >= cmd->nwords) {
  1170. printf("%s: expects a filename\n", cmd->words[0]);
  1171. return 0;
  1172. }
  1173. toret = 1;
  1174. do {
  1175. WildcardMatcher *wcm;
  1176. fname = cmd->words[i++];
  1177. if (multiple && test_wildcard(fname, false) == WCTYPE_WILDCARD) {
  1178. wcm = begin_wildcard_matching(fname);
  1179. wfname = wildcard_get_filename(wcm);
  1180. if (!wfname) {
  1181. /* Politely warn the user that nothing matched. */
  1182. printf("%s: nothing matched\n", fname);
  1183. finish_wildcard_matching(wcm);
  1184. continue;
  1185. }
  1186. } else {
  1187. wfname = fname;
  1188. wcm = NULL;
  1189. }
  1190. while (wfname) {
  1191. if (!multiple && i < cmd->nwords)
  1192. origoutfname = cmd->words[i++];
  1193. else
  1194. origoutfname = stripslashes(wfname, true);
  1195. outfname = canonify(origoutfname);
  1196. toret = sftp_put_file(wfname, outfname, recurse, restart);
  1197. sfree(outfname);
  1198. if (wcm) {
  1199. sfree(wfname);
  1200. wfname = wildcard_get_filename(wcm);
  1201. } else {
  1202. wfname = NULL;
  1203. }
  1204. }
  1205. if (wcm)
  1206. finish_wildcard_matching(wcm);
  1207. if (!toret)
  1208. return toret;
  1209. } while (multiple && i < cmd->nwords);
  1210. return toret;
  1211. }
  1212. int sftp_cmd_put(struct sftp_command *cmd)
  1213. {
  1214. return sftp_general_put(cmd, false, false);
  1215. }
  1216. int sftp_cmd_mput(struct sftp_command *cmd)
  1217. {
  1218. return sftp_general_put(cmd, false, true);
  1219. }
  1220. int sftp_cmd_reput(struct sftp_command *cmd)
  1221. {
  1222. return sftp_general_put(cmd, true, false);
  1223. }
  1224. int sftp_cmd_mkdir(struct sftp_command *cmd)
  1225. {
  1226. char *dir;
  1227. struct sftp_packet *pktin;
  1228. struct sftp_request *req;
  1229. bool result;
  1230. int i, ret;
  1231. if (!backend) {
  1232. not_connected();
  1233. return 0;
  1234. }
  1235. if (cmd->nwords < 2) {
  1236. printf("mkdir: expects a directory\n");
  1237. return 0;
  1238. }
  1239. ret = 1;
  1240. for (i = 1; i < cmd->nwords; i++) {
  1241. dir = canonify(cmd->words[i]);
  1242. req = fxp_mkdir_send(dir, NULL);
  1243. pktin = sftp_wait_for_reply(req);
  1244. result = fxp_mkdir_recv(pktin, req);
  1245. if (!result) {
  1246. with_stripctrl(san, dir)
  1247. printf("mkdir %s: %s\n", san, fxp_error());
  1248. ret = 0;
  1249. } else
  1250. with_stripctrl(san, dir)
  1251. printf("mkdir %s: OK\n", san);
  1252. sfree(dir);
  1253. }
  1254. return ret;
  1255. }
  1256. static bool sftp_action_rmdir(void *vctx, char *dir)
  1257. {
  1258. struct sftp_packet *pktin;
  1259. struct sftp_request *req;
  1260. bool result;
  1261. req = fxp_rmdir_send(dir);
  1262. pktin = sftp_wait_for_reply(req);
  1263. result = fxp_rmdir_recv(pktin, req);
  1264. if (!result) {
  1265. printf("rmdir %s: %s\n", dir, fxp_error());
  1266. return false;
  1267. }
  1268. printf("rmdir %s: OK\n", dir);
  1269. return true;
  1270. }
  1271. int sftp_cmd_rmdir(struct sftp_command *cmd)
  1272. {
  1273. int i, ret;
  1274. if (!backend) {
  1275. not_connected();
  1276. return 0;
  1277. }
  1278. if (cmd->nwords < 2) {
  1279. printf("rmdir: expects a directory\n");
  1280. return 0;
  1281. }
  1282. ret = 1;
  1283. for (i = 1; i < cmd->nwords; i++)
  1284. ret &= wildcard_iterate(cmd->words[i], sftp_action_rmdir, NULL);
  1285. return ret;
  1286. }
  1287. static bool sftp_action_rm(void *vctx, char *fname)
  1288. {
  1289. struct sftp_packet *pktin;
  1290. struct sftp_request *req;
  1291. bool result;
  1292. req = fxp_remove_send(fname);
  1293. pktin = sftp_wait_for_reply(req);
  1294. result = fxp_remove_recv(pktin, req);
  1295. if (!result) {
  1296. printf("rm %s: %s\n", fname, fxp_error());
  1297. return false;
  1298. }
  1299. printf("rm %s: OK\n", fname);
  1300. return true;
  1301. }
  1302. int sftp_cmd_rm(struct sftp_command *cmd)
  1303. {
  1304. int i, ret;
  1305. if (!backend) {
  1306. not_connected();
  1307. return 0;
  1308. }
  1309. if (cmd->nwords < 2) {
  1310. printf("rm: expects a filename\n");
  1311. return 0;
  1312. }
  1313. ret = 1;
  1314. for (i = 1; i < cmd->nwords; i++)
  1315. ret &= wildcard_iterate(cmd->words[i], sftp_action_rm, NULL);
  1316. return ret;
  1317. }
  1318. static bool check_is_dir(char *dstfname)
  1319. {
  1320. struct sftp_packet *pktin;
  1321. struct sftp_request *req;
  1322. struct fxp_attrs attrs;
  1323. bool result;
  1324. req = fxp_stat_send(dstfname);
  1325. pktin = sftp_wait_for_reply(req);
  1326. result = fxp_stat_recv(pktin, req, &attrs);
  1327. if (result &&
  1328. (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
  1329. (attrs.permissions & 0040000))
  1330. return true;
  1331. else
  1332. return false;
  1333. }
  1334. struct sftp_context_mv {
  1335. char *dstfname;
  1336. bool dest_is_dir;
  1337. };
  1338. static bool sftp_action_mv(void *vctx, char *srcfname)
  1339. {
  1340. struct sftp_context_mv *ctx = (struct sftp_context_mv *)vctx;
  1341. struct sftp_packet *pktin;
  1342. struct sftp_request *req;
  1343. const char *error;
  1344. char *finalfname, *newcanon = NULL;
  1345. bool toret, result;
  1346. if (ctx->dest_is_dir) {
  1347. char *p;
  1348. char *newname;
  1349. p = srcfname + strlen(srcfname);
  1350. while (p > srcfname && p[-1] != '/') p--;
  1351. newname = dupcat(ctx->dstfname, "/", p);
  1352. newcanon = canonify(newname);
  1353. sfree(newname);
  1354. finalfname = newcanon;
  1355. } else {
  1356. finalfname = ctx->dstfname;
  1357. }
  1358. req = fxp_rename_send(srcfname, finalfname);
  1359. pktin = sftp_wait_for_reply(req);
  1360. result = fxp_rename_recv(pktin, req);
  1361. error = result ? NULL : fxp_error();
  1362. if (error) {
  1363. with_stripctrl(san, finalfname)
  1364. printf("mv %s %s: %s\n", srcfname, san, error);
  1365. toret = false;
  1366. } else {
  1367. with_stripctrl(san, finalfname)
  1368. printf("%s -> %s\n", srcfname, san);
  1369. toret = true;
  1370. }
  1371. sfree(newcanon);
  1372. return toret;
  1373. }
  1374. int sftp_cmd_mv(struct sftp_command *cmd)
  1375. {
  1376. struct sftp_context_mv ctx[1];
  1377. int i, ret;
  1378. if (!backend) {
  1379. not_connected();
  1380. return 0;
  1381. }
  1382. if (cmd->nwords < 3) {
  1383. printf("mv: expects two filenames\n");
  1384. return 0;
  1385. }
  1386. ctx->dstfname = canonify(cmd->words[cmd->nwords-1]);
  1387. /*
  1388. * If there's more than one source argument, or one source
  1389. * argument which is a wildcard, we _require_ that the
  1390. * destination is a directory.
  1391. */
  1392. ctx->dest_is_dir = check_is_dir(ctx->dstfname);
  1393. if ((cmd->nwords > 3 || is_wildcard(cmd->words[1])) && !ctx->dest_is_dir) {
  1394. printf("mv: multiple or wildcard arguments require the destination"
  1395. " to be a directory\n");
  1396. sfree(ctx->dstfname);
  1397. return 0;
  1398. }
  1399. /*
  1400. * Now iterate over the source arguments.
  1401. */
  1402. ret = 1;
  1403. for (i = 1; i < cmd->nwords-1; i++)
  1404. ret &= wildcard_iterate(cmd->words[i], sftp_action_mv, ctx);
  1405. sfree(ctx->dstfname);
  1406. return ret;
  1407. }
  1408. struct sftp_context_chmod {
  1409. unsigned attrs_clr, attrs_xor;
  1410. };
  1411. static bool sftp_action_chmod(void *vctx, char *fname)
  1412. {
  1413. struct fxp_attrs attrs;
  1414. struct sftp_packet *pktin;
  1415. struct sftp_request *req;
  1416. bool result;
  1417. unsigned oldperms, newperms;
  1418. struct sftp_context_chmod *ctx = (struct sftp_context_chmod *)vctx;
  1419. req = fxp_stat_send(fname);
  1420. pktin = sftp_wait_for_reply(req);
  1421. result = fxp_stat_recv(pktin, req, &attrs);
  1422. if (!result || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
  1423. printf("get attrs for %s: %s\n", fname,
  1424. result ? "file permissions not provided" : fxp_error());
  1425. return false;
  1426. }
  1427. attrs.flags = SSH_FILEXFER_ATTR_PERMISSIONS; /* perms _only_ */
  1428. oldperms = attrs.permissions & 07777;
  1429. attrs.permissions &= ~ctx->attrs_clr;
  1430. attrs.permissions ^= ctx->attrs_xor;
  1431. newperms = attrs.permissions & 07777;
  1432. if (oldperms == newperms)
  1433. return true; /* no need to do anything! */
  1434. req = fxp_setstat_send(fname, attrs);
  1435. pktin = sftp_wait_for_reply(req);
  1436. result = fxp_setstat_recv(pktin, req);
  1437. if (!result) {
  1438. printf("set attrs for %s: %s\n", fname, fxp_error());
  1439. return false;
  1440. }
  1441. printf("%s: %04o -> %04o\n", fname, oldperms, newperms);
  1442. return true;
  1443. }
  1444. int sftp_cmd_chmod(struct sftp_command *cmd)
  1445. {
  1446. char *mode;
  1447. int i, ret;
  1448. struct sftp_context_chmod ctx[1];
  1449. if (!backend) {
  1450. not_connected();
  1451. return 0;
  1452. }
  1453. if (cmd->nwords < 3) {
  1454. printf("chmod: expects a mode specifier and a filename\n");
  1455. return 0;
  1456. }
  1457. /*
  1458. * Attempt to parse the mode specifier in cmd->words[1]. We
  1459. * don't support the full horror of Unix chmod; instead we
  1460. * support a much simpler syntax in which the user can either
  1461. * specify an octal number, or a comma-separated sequence of
  1462. * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
  1463. * _only_ be omitted if the only attribute mentioned is t,
  1464. * since all others require a user/group/other specification.
  1465. * Additionally, the s attribute may not be specified for any
  1466. * [ugoa] specifications other than exactly u or exactly g.
  1467. */
  1468. ctx->attrs_clr = ctx->attrs_xor = 0;
  1469. mode = cmd->words[1];
  1470. if (mode[0] >= '0' && mode[0] <= '9') {
  1471. if (mode[strspn(mode, "01234567")]) {
  1472. printf("chmod: numeric file modes should"
  1473. " contain digits 0-7 only\n");
  1474. return 0;
  1475. }
  1476. ctx->attrs_clr = 07777;
  1477. sscanf(mode, "%o", &ctx->attrs_xor);
  1478. ctx->attrs_xor &= ctx->attrs_clr;
  1479. } else {
  1480. while (*mode) {
  1481. char *modebegin = mode;
  1482. unsigned subset, perms;
  1483. int action;
  1484. subset = 0;
  1485. while (*mode && *mode != ',' &&
  1486. *mode != '+' && *mode != '-' && *mode != '=') {
  1487. switch (*mode) {
  1488. case 'u': subset |= 04700; break; /* setuid, user perms */
  1489. case 'g': subset |= 02070; break; /* setgid, group perms */
  1490. case 'o': subset |= 00007; break; /* just other perms */
  1491. case 'a': subset |= 06777; break; /* all of the above */
  1492. default:
  1493. printf("chmod: file mode '%.*s' contains unrecognised"
  1494. " user/group/other specifier '%c'\n",
  1495. (int)strcspn(modebegin, ","), modebegin, *mode);
  1496. return 0;
  1497. }
  1498. mode++;
  1499. }
  1500. if (!*mode || *mode == ',') {
  1501. printf("chmod: file mode '%.*s' is incomplete\n",
  1502. (int)strcspn(modebegin, ","), modebegin);
  1503. return 0;
  1504. }
  1505. action = *mode++;
  1506. if (!*mode || *mode == ',') {
  1507. printf("chmod: file mode '%.*s' is incomplete\n",
  1508. (int)strcspn(modebegin, ","), modebegin);
  1509. return 0;
  1510. }
  1511. perms = 0;
  1512. while (*mode && *mode != ',') {
  1513. switch (*mode) {
  1514. case 'r': perms |= 00444; break;
  1515. case 'w': perms |= 00222; break;
  1516. case 'x': perms |= 00111; break;
  1517. case 't': perms |= 01000; subset |= 01000; break;
  1518. case 's':
  1519. if ((subset & 06777) != 04700 &&
  1520. (subset & 06777) != 02070) {
  1521. printf("chmod: file mode '%.*s': set[ug]id bit should"
  1522. " be used with exactly one of u or g only\n",
  1523. (int)strcspn(modebegin, ","), modebegin);
  1524. return 0;
  1525. }
  1526. perms |= 06000;
  1527. break;
  1528. default:
  1529. printf("chmod: file mode '%.*s' contains unrecognised"
  1530. " permission specifier '%c'\n",
  1531. (int)strcspn(modebegin, ","), modebegin, *mode);
  1532. return 0;
  1533. }
  1534. mode++;
  1535. }
  1536. if (!(subset & 06777) && (perms &~ subset)) {
  1537. printf("chmod: file mode '%.*s' contains no user/group/other"
  1538. " specifier and permissions other than 't' \n",
  1539. (int)strcspn(modebegin, ","), modebegin);
  1540. return 0;
  1541. }
  1542. perms &= subset;
  1543. switch (action) {
  1544. case '+':
  1545. ctx->attrs_clr |= perms;
  1546. ctx->attrs_xor |= perms;
  1547. break;
  1548. case '-':
  1549. ctx->attrs_clr |= perms;
  1550. ctx->attrs_xor &= ~perms;
  1551. break;
  1552. case '=':
  1553. ctx->attrs_clr |= subset;
  1554. ctx->attrs_xor |= perms;
  1555. break;
  1556. }
  1557. if (*mode) mode++; /* eat comma */
  1558. }
  1559. }
  1560. ret = 1;
  1561. for (i = 2; i < cmd->nwords; i++)
  1562. ret &= wildcard_iterate(cmd->words[i], sftp_action_chmod, ctx);
  1563. return ret;
  1564. }
  1565. static int sftp_cmd_open(struct sftp_command *cmd)
  1566. {
  1567. int portnumber;
  1568. if (backend) {
  1569. printf("psftp: already connected\n");
  1570. return 0;
  1571. }
  1572. if (cmd->nwords < 2) {
  1573. printf("open: expects a host name\n");
  1574. return 0;
  1575. }
  1576. if (cmd->nwords > 2) {
  1577. portnumber = atoi(cmd->words[2]);
  1578. if (portnumber == 0) {
  1579. printf("open: invalid port number\n");
  1580. return 0;
  1581. }
  1582. } else
  1583. portnumber = 0;
  1584. if (psftp_connect(cmd->words[1], NULL, portnumber)) {
  1585. backend = NULL; /* connection is already closed */
  1586. return -1; /* this is fatal */
  1587. }
  1588. do_sftp_init();
  1589. return 1;
  1590. }
  1591. static int sftp_cmd_lcd(struct sftp_command *cmd)
  1592. {
  1593. char *currdir, *errmsg;
  1594. if (cmd->nwords < 2) {
  1595. printf("lcd: expects a local directory name\n");
  1596. return 0;
  1597. }
  1598. errmsg = psftp_lcd(cmd->words[1]);
  1599. if (errmsg) {
  1600. printf("lcd: unable to change directory: %s\n", errmsg);
  1601. sfree(errmsg);
  1602. return 0;
  1603. }
  1604. currdir = psftp_getcwd();
  1605. printf("New local directory is %s\n", currdir);
  1606. sfree(currdir);
  1607. return 1;
  1608. }
  1609. static int sftp_cmd_lpwd(struct sftp_command *cmd)
  1610. {
  1611. char *currdir;
  1612. currdir = psftp_getcwd();
  1613. printf("Current local directory is %s\n", currdir);
  1614. sfree(currdir);
  1615. return 1;
  1616. }
  1617. static int sftp_cmd_pling(struct sftp_command *cmd)
  1618. {
  1619. int exitcode;
  1620. exitcode = system(cmd->words[1]);
  1621. return (exitcode == 0);
  1622. }
  1623. static int sftp_cmd_help(struct sftp_command *cmd);
  1624. static struct sftp_cmd_lookup {
  1625. const char *name;
  1626. /*
  1627. * For help purposes, there are two kinds of command:
  1628. *
  1629. * - primary commands, in which `longhelp' is non-NULL. In
  1630. * this case `shorthelp' is descriptive text, and `longhelp'
  1631. * is longer descriptive text intended to be printed after
  1632. * the command name.
  1633. *
  1634. * - alias commands, in which `longhelp' is NULL. In this case
  1635. * `shorthelp' is the name of a primary command, which
  1636. * contains the help that should double up for this command.
  1637. */
  1638. bool listed; /* do we list this in primary help? */
  1639. const char *shorthelp;
  1640. const char *longhelp;
  1641. int (*obey) (struct sftp_command *);
  1642. } sftp_lookup[] = {
  1643. /*
  1644. * List of sftp commands. This is binary-searched so it MUST be
  1645. * in ASCII order.
  1646. */
  1647. {
  1648. "!", true, "run a local command",
  1649. "<command>\n"
  1650. /* FIXME: this example is crap for non-Windows. */
  1651. " Runs a local command. For example, \"!del myfile\".\n",
  1652. sftp_cmd_pling
  1653. },
  1654. {
  1655. "bye", true, "finish your SFTP session",
  1656. "\n"
  1657. " Terminates your SFTP session and quits the PSFTP program.\n",
  1658. sftp_cmd_quit
  1659. },
  1660. {
  1661. "cd", true, "change your remote working directory",
  1662. " [ <new working directory> ]\n"
  1663. " Change the remote working directory for your SFTP session.\n"
  1664. " If a new working directory is not supplied, you will be\n"
  1665. " returned to your home directory.\n",
  1666. sftp_cmd_cd
  1667. },
  1668. {
  1669. "chmod", true, "change file permissions and modes",
  1670. " <modes> <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
  1671. " Change the file permissions on one or more remote files or\n"
  1672. " directories.\n"
  1673. " <modes> can be any octal Unix permission specifier.\n"
  1674. " Alternatively, <modes> can include the following modifiers:\n"
  1675. " u+r make file readable by owning user\n"
  1676. " u+w make file writable by owning user\n"
  1677. " u+x make file executable by owning user\n"
  1678. " u-r make file not readable by owning user\n"
  1679. " [also u-w, u-x]\n"
  1680. " g+r make file readable by members of owning group\n"
  1681. " [also g+w, g+x, g-r, g-w, g-x]\n"
  1682. " o+r make file readable by all other users\n"
  1683. " [also o+w, o+x, o-r, o-w, o-x]\n"
  1684. " a+r make file readable by absolutely everybody\n"
  1685. " [also a+w, a+x, a-r, a-w, a-x]\n"
  1686. " u+s enable the Unix set-user-ID bit\n"
  1687. " u-s disable the Unix set-user-ID bit\n"
  1688. " g+s enable the Unix set-group-ID bit\n"
  1689. " g-s disable the Unix set-group-ID bit\n"
  1690. " +t enable the Unix \"sticky bit\"\n"
  1691. " You can give more than one modifier for the same user (\"g-rwx\"), and\n"
  1692. " more than one user for the same modifier (\"ug+w\"). You can\n"
  1693. " use commas to separate different modifiers (\"u+rwx,g+s\").\n",
  1694. sftp_cmd_chmod
  1695. },
  1696. {
  1697. "close", true, "finish your SFTP session but do not quit PSFTP",
  1698. "\n"
  1699. " Terminates your SFTP session, but does not quit the PSFTP\n"
  1700. " program. You can then use \"open\" to start another SFTP\n"
  1701. " session, to the same server or to a different one.\n",
  1702. sftp_cmd_close
  1703. },
  1704. {
  1705. "del", true, "delete files on the remote server",
  1706. " <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
  1707. " Delete a file or files from the server.\n",
  1708. sftp_cmd_rm
  1709. },
  1710. {
  1711. "delete", false, "del", NULL, sftp_cmd_rm
  1712. },
  1713. {
  1714. "dir", true, "list remote files",
  1715. " [ <directory-name> ]/[ <wildcard> ]\n"
  1716. " List the contents of a specified directory on the server.\n"
  1717. " If <directory-name> is not given, the current working directory\n"
  1718. " is assumed.\n"
  1719. " If <wildcard> is given, it is treated as a set of files to\n"
  1720. " list; otherwise, all files are listed.\n",
  1721. sftp_cmd_ls
  1722. },
  1723. {
  1724. "exit", true, "bye", NULL, sftp_cmd_quit
  1725. },
  1726. {
  1727. "get", true, "download a file from the server to your local machine",
  1728. " [ -r ] [ -- ] <filename> [ <local-filename> ]\n"
  1729. " Downloads a file on the server and stores it locally under\n"
  1730. " the same name, or under a different one if you supply the\n"
  1731. " argument <local-filename>.\n"
  1732. " If -r specified, recursively fetch a directory.\n",
  1733. sftp_cmd_get
  1734. },
  1735. {
  1736. "help", true, "give help",
  1737. " [ <command> [ <command> ... ] ]\n"
  1738. " Give general help if no commands are specified.\n"
  1739. " If one or more commands are specified, give specific help on\n"
  1740. " those particular commands.\n",
  1741. sftp_cmd_help
  1742. },
  1743. {
  1744. "lcd", true, "change local working directory",
  1745. " <local-directory-name>\n"
  1746. " Change the local working directory of the PSFTP program (the\n"
  1747. " default location where the \"get\" command will save files).\n",
  1748. sftp_cmd_lcd
  1749. },
  1750. {
  1751. "lpwd", true, "print local working directory",
  1752. "\n"
  1753. " Print the local working directory of the PSFTP program (the\n"
  1754. " default location where the \"get\" command will save files).\n",
  1755. sftp_cmd_lpwd
  1756. },
  1757. {
  1758. "ls", true, "dir", NULL,
  1759. sftp_cmd_ls
  1760. },
  1761. {
  1762. "mget", true, "download multiple files at once",
  1763. " [ -r ] [ -- ] <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
  1764. " Downloads many files from the server, storing each one under\n"
  1765. " the same name it has on the server side. You can use wildcards\n"
  1766. " such as \"*.c\" to specify lots of files at once.\n"
  1767. " If -r specified, recursively fetch files and directories.\n",
  1768. sftp_cmd_mget
  1769. },
  1770. {
  1771. "mkdir", true, "create directories on the remote server",
  1772. " <directory-name> [ <directory-name>... ]\n"
  1773. " Creates directories with the given names on the server.\n",
  1774. sftp_cmd_mkdir
  1775. },
  1776. {
  1777. "mput", true, "upload multiple files at once",
  1778. " [ -r ] [ -- ] <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
  1779. " Uploads many files to the server, storing each one under the\n"
  1780. " same name it has on the client side. You can use wildcards\n"
  1781. " such as \"*.c\" to specify lots of files at once.\n"
  1782. " If -r specified, recursively store files and directories.\n",
  1783. sftp_cmd_mput
  1784. },
  1785. {
  1786. "mv", true, "move or rename file(s) on the remote server",
  1787. " <source> [ <source>... ] <destination>\n"
  1788. " Moves or renames <source>(s) on the server to <destination>,\n"
  1789. " also on the server.\n"
  1790. " If <destination> specifies an existing directory, then <source>\n"
  1791. " may be a wildcard, and multiple <source>s may be given; all\n"
  1792. " source files are moved into <destination>.\n"
  1793. " Otherwise, <source> must specify a single file, which is moved\n"
  1794. " or renamed so that it is accessible under the name <destination>.\n",
  1795. sftp_cmd_mv
  1796. },
  1797. {
  1798. "open", true, "connect to a host",
  1799. " [<user>@]<hostname> [<port>]\n"
  1800. " Establishes an SFTP connection to a given host. Only usable\n"
  1801. " when you are not already connected to a server.\n",
  1802. sftp_cmd_open
  1803. },
  1804. {
  1805. "put", true, "upload a file from your local machine to the server",
  1806. " [ -r ] [ -- ] <filename> [ <remote-filename> ]\n"
  1807. " Uploads a file to the server and stores it there under\n"
  1808. " the same name, or under a different one if you supply the\n"
  1809. " argument <remote-filename>.\n"
  1810. " If -r specified, recursively store a directory.\n",
  1811. sftp_cmd_put
  1812. },
  1813. {
  1814. "pwd", true, "print your remote working directory",
  1815. "\n"
  1816. " Print the current remote working directory for your SFTP session.\n",
  1817. sftp_cmd_pwd
  1818. },
  1819. {
  1820. "quit", true, "bye", NULL,
  1821. sftp_cmd_quit
  1822. },
  1823. {
  1824. "reget", true, "continue downloading files",
  1825. " [ -r ] [ -- ] <filename> [ <local-filename> ]\n"
  1826. " Works exactly like the \"get\" command, but the local file\n"
  1827. " must already exist. The download will begin at the end of the\n"
  1828. " file. This is for resuming a download that was interrupted.\n"
  1829. " If -r specified, resume interrupted \"get -r\".\n",
  1830. sftp_cmd_reget
  1831. },
  1832. {
  1833. "ren", true, "mv", NULL,
  1834. sftp_cmd_mv
  1835. },
  1836. {
  1837. "rename", false, "mv", NULL,
  1838. sftp_cmd_mv
  1839. },
  1840. {
  1841. "reput", true, "continue uploading files",
  1842. " [ -r ] [ -- ] <filename> [ <remote-filename> ]\n"
  1843. " Works exactly like the \"put\" command, but the remote file\n"
  1844. " must already exist. The upload will begin at the end of the\n"
  1845. " file. This is for resuming an upload that was interrupted.\n"
  1846. " If -r specified, resume interrupted \"put -r\".\n",
  1847. sftp_cmd_reput
  1848. },
  1849. {
  1850. "rm", true, "del", NULL,
  1851. sftp_cmd_rm
  1852. },
  1853. {
  1854. "rmdir", true, "remove directories on the remote server",
  1855. " <directory-name> [ <directory-name>... ]\n"
  1856. " Removes the directory with the given name on the server.\n"
  1857. " The directory will not be removed unless it is empty.\n"
  1858. " Wildcards may be used to specify multiple directories.\n",
  1859. sftp_cmd_rmdir
  1860. }
  1861. };
  1862. const struct sftp_cmd_lookup *lookup_command(const char *name)
  1863. {
  1864. int i, j, k, cmp;
  1865. i = -1;
  1866. j = lenof(sftp_lookup);
  1867. while (j - i > 1) {
  1868. k = (j + i) / 2;
  1869. cmp = strcmp(name, sftp_lookup[k].name);
  1870. if (cmp < 0)
  1871. j = k;
  1872. else if (cmp > 0)
  1873. i = k;
  1874. else {
  1875. return &sftp_lookup[k];
  1876. }
  1877. }
  1878. return NULL;
  1879. }
  1880. static int sftp_cmd_help(struct sftp_command *cmd)
  1881. {
  1882. int i;
  1883. if (cmd->nwords == 1) {
  1884. /*
  1885. * Give short help on each command.
  1886. */
  1887. int maxlen;
  1888. maxlen = 0;
  1889. for (i = 0; i < lenof(sftp_lookup); i++) {
  1890. int len;
  1891. if (!sftp_lookup[i].listed)
  1892. continue;
  1893. len = strlen(sftp_lookup[i].name);
  1894. if (maxlen < len)
  1895. maxlen = len;
  1896. }
  1897. for (i = 0; i < lenof(sftp_lookup); i++) {
  1898. const struct sftp_cmd_lookup *lookup;
  1899. if (!sftp_lookup[i].listed)
  1900. continue;
  1901. lookup = &sftp_lookup[i];
  1902. printf("%-*s", maxlen+2, lookup->name);
  1903. if (lookup->longhelp == NULL)
  1904. lookup = lookup_command(lookup->shorthelp);
  1905. printf("%s\n", lookup->shorthelp);
  1906. }
  1907. } else {
  1908. /*
  1909. * Give long help on specific commands.
  1910. */
  1911. for (i = 1; i < cmd->nwords; i++) {
  1912. const struct sftp_cmd_lookup *lookup;
  1913. lookup = lookup_command(cmd->words[i]);
  1914. if (!lookup) {
  1915. printf("help: %s: command not found\n", cmd->words[i]);
  1916. } else {
  1917. printf("%s", lookup->name);
  1918. if (lookup->longhelp == NULL)
  1919. lookup = lookup_command(lookup->shorthelp);
  1920. printf("%s", lookup->longhelp);
  1921. }
  1922. }
  1923. }
  1924. return 1;
  1925. }
  1926. /* ----------------------------------------------------------------------
  1927. * Command line reading and parsing.
  1928. */
  1929. struct sftp_command *sftp_getcmd(FILE *fp, int mode, int modeflags)
  1930. {
  1931. char *line;
  1932. struct sftp_command *cmd;
  1933. char *p, *q, *r;
  1934. bool quoting;
  1935. cmd = snew(struct sftp_command);
  1936. cmd->words = NULL;
  1937. cmd->nwords = 0;
  1938. cmd->wordssize = 0;
  1939. line = NULL;
  1940. if (fp) {
  1941. if (modeflags & 1)
  1942. printf("psftp> ");
  1943. line = fgetline(fp);
  1944. } else {
  1945. line = ssh_sftp_get_cmdline("psftp> ", !backend);
  1946. }
  1947. if (!line || !*line) {
  1948. cmd->obey = sftp_cmd_quit;
  1949. if ((mode == 0) || (modeflags & 1))
  1950. printf("quit\n");
  1951. sfree(line);
  1952. return cmd; /* eof */
  1953. }
  1954. line[strcspn(line, "\r\n")] = '\0';
  1955. if (modeflags & 1) {
  1956. printf("%s\n", line);
  1957. }
  1958. p = line;
  1959. while (*p && (*p == ' ' || *p == '\t'))
  1960. p++;
  1961. if (*p == '!') {
  1962. /*
  1963. * Special case: the ! command. This is always parsed as
  1964. * exactly two words: one containing the !, and the second
  1965. * containing everything else on the line.
  1966. */
  1967. cmd->nwords = 2;
  1968. sgrowarrayn(cmd->words, cmd->wordssize, cmd->nwords, 0);
  1969. cmd->words[0] = dupstr("!");
  1970. cmd->words[1] = dupstr(p+1);
  1971. } else if (*p == '#') {
  1972. /*
  1973. * Special case: comment. Entire line is ignored.
  1974. */
  1975. cmd->nwords = cmd->wordssize = 0;
  1976. } else {
  1977. /*
  1978. * Parse the command line into words. The syntax is:
  1979. * - double quotes are removed, but cause spaces within to be
  1980. * treated as non-separating.
  1981. * - a double-doublequote pair is a literal double quote, inside
  1982. * _or_ outside quotes. Like this:
  1983. *
  1984. * firstword "second word" "this has ""quotes"" in" and""this""
  1985. *
  1986. * becomes
  1987. *
  1988. * >firstword<
  1989. * >second word<
  1990. * >this has "quotes" in<
  1991. * >and"this"<
  1992. */
  1993. while (1) {
  1994. /* skip whitespace */
  1995. while (*p && (*p == ' ' || *p == '\t'))
  1996. p++;
  1997. /* terminate loop */
  1998. if (!*p)
  1999. break;
  2000. /* mark start of word */
  2001. q = r = p; /* q sits at start, r writes word */
  2002. quoting = false;
  2003. while (*p) {
  2004. if (!quoting && (*p == ' ' || *p == '\t'))
  2005. break; /* reached end of word */
  2006. else if (*p == '"' && p[1] == '"')
  2007. p += 2, *r++ = '"'; /* a literal quote */
  2008. else if (*p == '"')
  2009. p++, quoting = !quoting;
  2010. else
  2011. *r++ = *p++;
  2012. }
  2013. if (*p)
  2014. p++; /* skip over the whitespace */
  2015. *r = '\0';
  2016. sgrowarray(cmd->words, cmd->wordssize, cmd->nwords);
  2017. cmd->words[cmd->nwords++] = dupstr(q);
  2018. }
  2019. }
  2020. sfree(line);
  2021. /*
  2022. * Now parse the first word and assign a function.
  2023. */
  2024. if (cmd->nwords == 0)
  2025. cmd->obey = sftp_cmd_null;
  2026. else {
  2027. const struct sftp_cmd_lookup *lookup;
  2028. lookup = lookup_command(cmd->words[0]);
  2029. if (!lookup)
  2030. cmd->obey = sftp_cmd_unknown;
  2031. else
  2032. cmd->obey = lookup->obey;
  2033. }
  2034. return cmd;
  2035. }
  2036. static void sftp_cmd_free(struct sftp_command *cmd)
  2037. {
  2038. if (cmd->words) {
  2039. for (size_t i = 0; i < cmd->nwords; i++)
  2040. sfree(cmd->words[i]);
  2041. sfree(cmd->words);
  2042. }
  2043. sfree(cmd);
  2044. }
  2045. static int do_sftp_init(void)
  2046. {
  2047. struct sftp_packet *pktin;
  2048. struct sftp_request *req;
  2049. /*
  2050. * Do protocol initialisation.
  2051. */
  2052. if (!fxp_init()) {
  2053. fprintf(stderr,
  2054. "Fatal: unable to initialise SFTP: %s\n", fxp_error());
  2055. return 1; /* failure */
  2056. }
  2057. /*
  2058. * Find out where our home directory is.
  2059. */
  2060. req = fxp_realpath_send(".");
  2061. pktin = sftp_wait_for_reply(req);
  2062. homedir = fxp_realpath_recv(pktin, req);
  2063. if (!homedir) {
  2064. fprintf(stderr,
  2065. "Warning: failed to resolve home directory: %s\n",
  2066. fxp_error());
  2067. homedir = dupstr(".");
  2068. } else {
  2069. with_stripctrl(san, homedir)
  2070. printf("Remote working directory is %s\n", san);
  2071. }
  2072. pwd = dupstr(homedir);
  2073. return 0;
  2074. }
  2075. static void do_sftp_cleanup(void)
  2076. {
  2077. char ch;
  2078. if (backend) {
  2079. backend_special(backend, SS_EOF, 0);
  2080. sent_eof = true;
  2081. sftp_recvdata(&ch, 1);
  2082. backend_free(backend);
  2083. sftp_cleanup_request();
  2084. backend = NULL;
  2085. }
  2086. if (pwd) {
  2087. sfree(pwd);
  2088. pwd = NULL;
  2089. }
  2090. if (homedir) {
  2091. sfree(homedir);
  2092. homedir = NULL;
  2093. }
  2094. if (psftp_logctx) {
  2095. log_free(psftp_logctx);
  2096. psftp_logctx = NULL;
  2097. }
  2098. }
  2099. int do_sftp(int mode, int modeflags, char *batchfile)
  2100. {
  2101. FILE *fp;
  2102. int ret;
  2103. /*
  2104. * Batch mode?
  2105. */
  2106. if (mode == 0) {
  2107. /* ------------------------------------------------------------------
  2108. * Now we're ready to do Real Stuff.
  2109. */
  2110. while (1) {
  2111. struct sftp_command *cmd;
  2112. cmd = sftp_getcmd(NULL, 0, 0);
  2113. if (!cmd)
  2114. break;
  2115. ret = cmd->obey(cmd);
  2116. sftp_cmd_free(cmd);
  2117. if (ret < 0)
  2118. break;
  2119. }
  2120. } else {
  2121. fp = fopen(batchfile, "r");
  2122. if (!fp) {
  2123. printf("Fatal: unable to open %s\n", batchfile);
  2124. return 1;
  2125. }
  2126. ret = 0;
  2127. while (1) {
  2128. struct sftp_command *cmd;
  2129. cmd = sftp_getcmd(fp, mode, modeflags);
  2130. if (!cmd)
  2131. break;
  2132. ret = cmd->obey(cmd);
  2133. sftp_cmd_free(cmd);
  2134. if (ret < 0)
  2135. break;
  2136. if (ret == 0) {
  2137. if (!(modeflags & 2))
  2138. break;
  2139. }
  2140. }
  2141. fclose(fp);
  2142. /*
  2143. * In batch mode, and if exit on command failure is enabled,
  2144. * any command failure causes the whole of PSFTP to fail.
  2145. */
  2146. if (ret == 0 && !(modeflags & 2)) return 2;
  2147. }
  2148. return 0;
  2149. }
  2150. /* ----------------------------------------------------------------------
  2151. * Dirty bits: integration with PuTTY.
  2152. */
  2153. static bool verbose = false;
  2154. void ldisc_echoedit_update(Ldisc *ldisc) { }
  2155. void ldisc_check_sendok(Ldisc *ldisc) { }
  2156. /*
  2157. * Receive a block of data from the SSH link. Block until all data
  2158. * is available.
  2159. *
  2160. * To do this, we repeatedly call the SSH protocol module, with our
  2161. * own psftp_output() function to catch the data that comes back. We
  2162. * do this until we have enough data.
  2163. */
  2164. static bufchain received_data;
  2165. static BinarySink *stderr_bs;
  2166. static size_t psftp_output(
  2167. Seat *seat, SeatOutputType type, const void *data, size_t len)
  2168. {
  2169. /*
  2170. * Non-stdout data (both stderr and SSH auth banners) is just
  2171. * spouted to local stderr (optionally via a sanitiser) and
  2172. * otherwise ignored.
  2173. */
  2174. if (type != SEAT_OUTPUT_STDOUT) {
  2175. put_data(stderr_bs, data, len);
  2176. return 0;
  2177. }
  2178. bufchain_add(&received_data, data, len);
  2179. return 0;
  2180. }
  2181. static bool psftp_eof(Seat *seat)
  2182. {
  2183. /*
  2184. * We expect to be the party deciding when to close the
  2185. * connection, so if we see EOF before we sent it ourselves, we
  2186. * should panic.
  2187. */
  2188. if (!sent_eof) {
  2189. seat_connection_fatal(
  2190. psftp_seat, "Received unexpected end-of-file from SFTP server");
  2191. }
  2192. return false;
  2193. }
  2194. bool sftp_recvdata(char *buf, size_t len)
  2195. {
  2196. while (len > 0) {
  2197. while (bufchain_size(&received_data) == 0) {
  2198. if (backend_exitcode(backend) >= 0 ||
  2199. ssh_sftp_loop_iteration() < 0)
  2200. return false; /* doom */
  2201. }
  2202. size_t got = bufchain_fetch_consume_up_to(&received_data, buf, len);
  2203. buf += got;
  2204. len -= got;
  2205. }
  2206. return true;
  2207. }
  2208. bool sftp_senddata(const char *buf, size_t len)
  2209. {
  2210. backend_send(backend, buf, len);
  2211. return true;
  2212. }
  2213. size_t sftp_sendbuffer(void)
  2214. {
  2215. return backend_sendbuffer(backend);
  2216. }
  2217. /*
  2218. * Short description of parameters.
  2219. */
  2220. static void usage(void)
  2221. {
  2222. printf("PuTTY Secure File Transfer (SFTP) client\n");
  2223. printf("%s\n", ver);
  2224. printf("Usage: psftp [options] [user@]host\n");
  2225. printf("Options:\n");
  2226. printf(" -V print version information and exit\n");
  2227. printf(" -pgpfp print PGP key fingerprints and exit\n");
  2228. printf(" -b file use specified batchfile\n");
  2229. printf(" -bc output batchfile commands\n");
  2230. printf(" -be don't stop batchfile processing if errors\n");
  2231. printf(" -v show verbose messages\n");
  2232. printf(" -load sessname Load settings from saved session\n");
  2233. printf(" -l user connect with specified username\n");
  2234. printf(" -P port connect to specified port\n");
  2235. printf(" -pwfile file login with password read from specified file\n");
  2236. printf(" -1 -2 force use of particular SSH protocol version\n");
  2237. printf(" -ssh -ssh-connection\n");
  2238. printf(" force use of particular SSH protocol variant\n");
  2239. printf(" -4 -6 force use of IPv4 or IPv6\n");
  2240. printf(" -C enable compression\n");
  2241. printf(" -i key private key file for user authentication\n");
  2242. printf(" -noagent disable use of Pageant\n");
  2243. printf(" -agent enable use of Pageant\n");
  2244. printf(" -no-trivial-auth\n");
  2245. printf(" disconnect if SSH authentication succeeds trivially\n");
  2246. printf(" -hostkey keyid\n");
  2247. printf(" manually specify a host key (may be repeated)\n");
  2248. printf(" -batch disable all interactive prompts\n");
  2249. printf(" -no-sanitise-stderr don't strip control chars from"
  2250. " standard error\n");
  2251. printf(" -proxycmd command\n");
  2252. printf(" use 'command' as local proxy\n");
  2253. printf(" -sshlog file\n");
  2254. printf(" -sshrawlog file\n");
  2255. printf(" log protocol details to a file\n");
  2256. printf(" -logoverwrite\n");
  2257. printf(" -logappend\n");
  2258. printf(" control what happens when a log file already exists\n");
  2259. cleanup_exit(1);
  2260. }
  2261. static void version(void)
  2262. {
  2263. char *buildinfo_text = buildinfo("\n");
  2264. printf("psftp: %s\n%s\n", ver, buildinfo_text);
  2265. sfree(buildinfo_text);
  2266. exit(0);
  2267. }
  2268. /*
  2269. * Connect to a host.
  2270. */
  2271. static int psftp_connect(char *userhost, char *user, int portnumber)
  2272. {
  2273. char *host, *realhost;
  2274. const char *err;
  2275. /* Separate host and username */
  2276. host = userhost;
  2277. host = strrchr(host, '@');
  2278. if (host == NULL) {
  2279. host = userhost;
  2280. } else {
  2281. *host++ = '\0';
  2282. if (user) {
  2283. printf("psftp: multiple usernames specified; using \"%s\"\n",
  2284. user);
  2285. } else
  2286. user = userhost;
  2287. }
  2288. /*
  2289. * If we haven't loaded session details already (e.g., from -load),
  2290. * try looking for a session called "host".
  2291. */
  2292. if (!cmdline_loaded_session()) {
  2293. /* Try to load settings for `host' into a temporary config */
  2294. Conf *conf2 = conf_new();
  2295. conf_set_str(conf2, CONF_host, "");
  2296. do_defaults(host, conf2);
  2297. if (conf_get_str(conf2, CONF_host)[0] != '\0') {
  2298. /* Settings present and include hostname */
  2299. /* Re-load data into the real config. */
  2300. do_defaults(host, conf);
  2301. } else {
  2302. /* Session doesn't exist or mention a hostname. */
  2303. /* Use `host' as a bare hostname. */
  2304. conf_set_str(conf, CONF_host, host);
  2305. }
  2306. conf_free(conf2);
  2307. } else {
  2308. /* Patch in hostname `host' to session details. */
  2309. conf_set_str(conf, CONF_host, host);
  2310. }
  2311. /*
  2312. * Force protocol to SSH if the user has somehow contrived to
  2313. * select one we don't support (e.g. by loading an inappropriate
  2314. * saved session). In that situation we assume the port number is
  2315. * useless too.)
  2316. */
  2317. if (!backend_vt_from_proto(conf_get_int(conf, CONF_protocol))) {
  2318. conf_set_int(conf, CONF_protocol, PROT_SSH);
  2319. conf_set_int(conf, CONF_port, 22);
  2320. }
  2321. /*
  2322. * If saved session / Default Settings says SSH-1 (`1 only' or `1'),
  2323. * then change it to SSH-2, on the grounds that that's more likely to
  2324. * work for SFTP. (Can be overridden with `-1' option.)
  2325. * But if it says `2 only' or `2', respect which.
  2326. */
  2327. if ((conf_get_int(conf, CONF_sshprot) & ~1) != 2) /* is it 2 or 3? */
  2328. conf_set_int(conf, CONF_sshprot, 2);
  2329. /*
  2330. * Enact command-line overrides.
  2331. */
  2332. cmdline_run_saved(conf);
  2333. /*
  2334. * Muck about with the hostname in various ways.
  2335. */
  2336. {
  2337. char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
  2338. char *host = hostbuf;
  2339. char *p, *q;
  2340. /*
  2341. * Trim leading whitespace.
  2342. */
  2343. host += strspn(host, " \t");
  2344. /*
  2345. * See if host is of the form user@host, and separate out
  2346. * the username if so.
  2347. */
  2348. if (host[0] != '\0') {
  2349. char *atsign = strrchr(host, '@');
  2350. if (atsign) {
  2351. *atsign = '\0';
  2352. conf_set_str(conf, CONF_username, host);
  2353. host = atsign + 1;
  2354. }
  2355. }
  2356. /*
  2357. * Remove any remaining whitespace.
  2358. */
  2359. p = hostbuf;
  2360. q = host;
  2361. while (*q) {
  2362. if (*q != ' ' && *q != '\t')
  2363. *p++ = *q;
  2364. q++;
  2365. }
  2366. *p = '\0';
  2367. conf_set_str(conf, CONF_host, hostbuf);
  2368. sfree(hostbuf);
  2369. }
  2370. /* Set username */
  2371. if (user != NULL && user[0] != '\0') {
  2372. conf_set_str(conf, CONF_username, user);
  2373. }
  2374. if (portnumber)
  2375. conf_set_int(conf, CONF_port, portnumber);
  2376. /*
  2377. * Disable scary things which shouldn't be enabled for simple
  2378. * things like SCP and SFTP: agent forwarding, port forwarding,
  2379. * X forwarding.
  2380. */
  2381. conf_set_bool(conf, CONF_x11_forward, false);
  2382. conf_set_bool(conf, CONF_agentfwd, false);
  2383. conf_set_bool(conf, CONF_ssh_simple, true);
  2384. {
  2385. char *key;
  2386. while ((key = conf_get_str_nthstrkey(conf, CONF_portfwd, 0)) != NULL)
  2387. conf_del_str_str(conf, CONF_portfwd, key);
  2388. }
  2389. /* Set up subsystem name. */
  2390. conf_set_str(conf, CONF_remote_cmd, "sftp");
  2391. conf_set_bool(conf, CONF_ssh_subsys, true);
  2392. conf_set_bool(conf, CONF_nopty, true);
  2393. /*
  2394. * Set up fallback option, for SSH-1 servers or servers with the
  2395. * sftp subsystem not enabled but the server binary installed
  2396. * in the usual place. We only support fallback on Unix
  2397. * systems, and we use a kludgy piece of shellery which should
  2398. * try to find sftp-server in various places (the obvious
  2399. * systemwide spots /usr/lib and /usr/local/lib, and then the
  2400. * user's PATH) and finally give up.
  2401. *
  2402. * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
  2403. * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
  2404. * exec sftp-server
  2405. *
  2406. * the idea being that this will attempt to use either of the
  2407. * obvious pathnames and then give up, and when it does give up
  2408. * it will print the preferred pathname in the error messages.
  2409. */
  2410. conf_set_str(conf, CONF_remote_cmd2,
  2411. "test -x /usr/lib/sftp-server &&"
  2412. " exec /usr/lib/sftp-server\n"
  2413. "test -x /usr/local/lib/sftp-server &&"
  2414. " exec /usr/local/lib/sftp-server\n"
  2415. "exec sftp-server");
  2416. conf_set_bool(conf, CONF_ssh_subsys2, false);
  2417. psftp_logctx = log_init(console_cli_logpolicy, conf);
  2418. platform_psftp_pre_conn_setup(console_cli_logpolicy);
  2419. err = backend_init(backend_vt_from_proto(
  2420. conf_get_int(conf, CONF_protocol)),
  2421. psftp_seat, &backend, psftp_logctx, conf,
  2422. conf_get_str(conf, CONF_host),
  2423. conf_get_int(conf, CONF_port),
  2424. &realhost, 0,
  2425. conf_get_bool(conf, CONF_tcp_keepalives));
  2426. if (err != NULL) {
  2427. fprintf(stderr, "ssh_init: %s\n", err);
  2428. return 1;
  2429. }
  2430. while (!backend_sendok(backend)) {
  2431. if (backend_exitcode(backend) >= 0)
  2432. return 1;
  2433. if (ssh_sftp_loop_iteration() < 0) {
  2434. fprintf(stderr, "ssh_init: error during SSH connection setup\n");
  2435. return 1;
  2436. }
  2437. }
  2438. if (verbose && realhost != NULL)
  2439. printf("Connected to %s\n", realhost);
  2440. if (realhost != NULL)
  2441. sfree(realhost);
  2442. return 0;
  2443. }
  2444. void cmdline_error(const char *p, ...)
  2445. {
  2446. va_list ap;
  2447. fprintf(stderr, "psftp: ");
  2448. va_start(ap, p);
  2449. vfprintf(stderr, p, ap);
  2450. va_end(ap);
  2451. fprintf(stderr, "\n try typing \"psftp -h\" for help\n");
  2452. exit(1);
  2453. }
  2454. const bool share_can_be_downstream = true;
  2455. const bool share_can_be_upstream = false;
  2456. static stdio_sink stderr_ss;
  2457. static StripCtrlChars *stderr_scc;
  2458. const unsigned cmdline_tooltype = TOOLTYPE_FILETRANSFER;
  2459. /*
  2460. * Main program. Parse arguments etc.
  2461. */
  2462. int psftp_main(int argc, char *argv[])
  2463. {
  2464. int i, toret;
  2465. int portnumber = 0;
  2466. char *userhost, *user;
  2467. int mode = 0;
  2468. int modeflags = 0;
  2469. bool sanitise_stderr = true;
  2470. char *batchfile = NULL;
  2471. sk_init();
  2472. userhost = user = NULL;
  2473. /* Load Default Settings before doing anything else. */
  2474. conf = conf_new();
  2475. do_defaults(NULL, conf);
  2476. for (i = 1; i < argc; i++) {
  2477. int retd;
  2478. if (argv[i][0] != '-') {
  2479. if (userhost)
  2480. usage();
  2481. else
  2482. userhost = dupstr(argv[i]);
  2483. continue;
  2484. }
  2485. retd = cmdline_process_param(
  2486. argv[i], i+1 < argc ? argv[i+1] : NULL, 1, conf);
  2487. if (retd == -2) {
  2488. cmdline_error("option \"%s\" requires an argument", argv[i]);
  2489. } else if (retd == 2) {
  2490. i++; /* skip next argument */
  2491. } else if (retd == 1) {
  2492. /* We have our own verbosity in addition to `flags'. */
  2493. if (cmdline_verbose())
  2494. verbose = true;
  2495. } else if (strcmp(argv[i], "-h") == 0 ||
  2496. strcmp(argv[i], "-?") == 0 ||
  2497. strcmp(argv[i], "--help") == 0) {
  2498. usage();
  2499. } else if (strcmp(argv[i], "-pgpfp") == 0) {
  2500. pgp_fingerprints();
  2501. return 1;
  2502. } else if (strcmp(argv[i], "-V") == 0 ||
  2503. strcmp(argv[i], "--version") == 0) {
  2504. version();
  2505. } else if (strcmp(argv[i], "-batch") == 0) {
  2506. console_batch_mode = true;
  2507. } else if (strcmp(argv[i], "-b") == 0 && i + 1 < argc) {
  2508. mode = 1;
  2509. batchfile = argv[++i];
  2510. } else if (strcmp(argv[i], "-bc") == 0) {
  2511. modeflags = modeflags | 1;
  2512. } else if (strcmp(argv[i], "-be") == 0) {
  2513. modeflags = modeflags | 2;
  2514. } else if (strcmp(argv[i], "-sanitise-stderr") == 0) {
  2515. sanitise_stderr = true;
  2516. } else if (strcmp(argv[i], "-no-sanitise-stderr") == 0) {
  2517. sanitise_stderr = false;
  2518. } else if (strcmp(argv[i], "--") == 0) {
  2519. i++;
  2520. break;
  2521. } else {
  2522. cmdline_error("unknown option \"%s\"", argv[i]);
  2523. }
  2524. }
  2525. argc -= i;
  2526. argv += i;
  2527. backend = NULL;
  2528. stdio_sink_init(&stderr_ss, stderr);
  2529. stderr_bs = BinarySink_UPCAST(&stderr_ss);
  2530. if (sanitise_stderr) {
  2531. stderr_scc = stripctrl_new(stderr_bs, false, L'\0');
  2532. stderr_bs = BinarySink_UPCAST(stderr_scc);
  2533. }
  2534. string_scc = stripctrl_new(NULL, false, L'\0');
  2535. /*
  2536. * If the loaded session provides a hostname, and a hostname has not
  2537. * otherwise been specified, pop it in `userhost' so that
  2538. * `psftp -load sessname' is sufficient to start a session.
  2539. */
  2540. if (!userhost && conf_get_str(conf, CONF_host)[0] != '\0') {
  2541. userhost = dupstr(conf_get_str(conf, CONF_host));
  2542. }
  2543. /*
  2544. * If a user@host string has already been provided, connect to
  2545. * it now.
  2546. */
  2547. if (userhost) {
  2548. int retd;
  2549. retd = psftp_connect(userhost, user, portnumber);
  2550. sfree(userhost);
  2551. if (retd)
  2552. return 1;
  2553. if (do_sftp_init())
  2554. return 1;
  2555. } else {
  2556. printf("psftp: no hostname specified; use \"open host.name\""
  2557. " to connect\n");
  2558. }
  2559. toret = do_sftp(mode, modeflags, batchfile);
  2560. if (backend && backend_connected(backend)) {
  2561. char ch;
  2562. backend_special(backend, SS_EOF, 0);
  2563. sent_eof = true;
  2564. sftp_recvdata(&ch, 1);
  2565. }
  2566. do_sftp_cleanup();
  2567. random_save_seed();
  2568. cmdline_cleanup();
  2569. sk_cleanup();
  2570. stripctrl_free(string_scc);
  2571. stripctrl_free(stderr_scc);
  2572. if (psftp_logctx)
  2573. log_free(psftp_logctx);
  2574. return toret;
  2575. }