psftp.c 86 KB

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