psftp.c 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921
  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, char *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 = fopen(batchfile, "r");
  2123. if (!fp) {
  2124. printf("Fatal: unable to open %s\n", 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. cleanup_exit(1);
  2261. }
  2262. static void version(void)
  2263. {
  2264. char *buildinfo_text = buildinfo("\n");
  2265. printf("psftp: %s\n%s\n", ver, buildinfo_text);
  2266. sfree(buildinfo_text);
  2267. exit(0);
  2268. }
  2269. /*
  2270. * Connect to a host.
  2271. */
  2272. static int psftp_connect(char *userhost, char *user, int portnumber)
  2273. {
  2274. char *host, *realhost;
  2275. const char *err;
  2276. /* Separate host and username */
  2277. host = userhost;
  2278. host = strrchr(host, '@');
  2279. if (host == NULL) {
  2280. host = userhost;
  2281. } else {
  2282. *host++ = '\0';
  2283. if (user) {
  2284. printf("psftp: multiple usernames specified; using \"%s\"\n",
  2285. user);
  2286. } else
  2287. user = userhost;
  2288. }
  2289. /*
  2290. * If we haven't loaded session details already (e.g., from -load),
  2291. * try looking for a session called "host".
  2292. */
  2293. if (!cmdline_loaded_session()) {
  2294. /* Try to load settings for `host' into a temporary config */
  2295. Conf *conf2 = conf_new();
  2296. conf_set_str(conf2, CONF_host, "");
  2297. do_defaults(host, conf2);
  2298. if (conf_get_str(conf2, CONF_host)[0] != '\0') {
  2299. /* Settings present and include hostname */
  2300. /* Re-load data into the real config. */
  2301. do_defaults(host, conf);
  2302. } else {
  2303. /* Session doesn't exist or mention a hostname. */
  2304. /* Use `host' as a bare hostname. */
  2305. conf_set_str(conf, CONF_host, host);
  2306. }
  2307. conf_free(conf2);
  2308. } else {
  2309. /* Patch in hostname `host' to session details. */
  2310. conf_set_str(conf, CONF_host, host);
  2311. }
  2312. /*
  2313. * Force protocol to SSH if the user has somehow contrived to
  2314. * select one we don't support (e.g. by loading an inappropriate
  2315. * saved session). In that situation we assume the port number is
  2316. * useless too.)
  2317. */
  2318. if (!backend_vt_from_proto(conf_get_int(conf, CONF_protocol))) {
  2319. conf_set_int(conf, CONF_protocol, PROT_SSH);
  2320. conf_set_int(conf, CONF_port, 22);
  2321. }
  2322. /*
  2323. * If saved session / Default Settings says SSH-1 (`1 only' or `1'),
  2324. * then change it to SSH-2, on the grounds that that's more likely to
  2325. * work for SFTP. (Can be overridden with `-1' option.)
  2326. * But if it says `2 only' or `2', respect which.
  2327. */
  2328. if ((conf_get_int(conf, CONF_sshprot) & ~1) != 2) /* is it 2 or 3? */
  2329. conf_set_int(conf, CONF_sshprot, 2);
  2330. /*
  2331. * Enact command-line overrides.
  2332. */
  2333. cmdline_run_saved(conf);
  2334. /*
  2335. * Muck about with the hostname in various ways.
  2336. */
  2337. {
  2338. char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
  2339. char *host = hostbuf;
  2340. char *p, *q;
  2341. /*
  2342. * Trim leading whitespace.
  2343. */
  2344. host += strspn(host, " \t");
  2345. /*
  2346. * See if host is of the form user@host, and separate out
  2347. * the username if so.
  2348. */
  2349. if (host[0] != '\0') {
  2350. char *atsign = strrchr(host, '@');
  2351. if (atsign) {
  2352. *atsign = '\0';
  2353. conf_set_str(conf, CONF_username, host);
  2354. host = atsign + 1;
  2355. }
  2356. }
  2357. /*
  2358. * Remove any remaining whitespace.
  2359. */
  2360. p = hostbuf;
  2361. q = host;
  2362. while (*q) {
  2363. if (*q != ' ' && *q != '\t')
  2364. *p++ = *q;
  2365. q++;
  2366. }
  2367. *p = '\0';
  2368. conf_set_str(conf, CONF_host, hostbuf);
  2369. sfree(hostbuf);
  2370. }
  2371. /* Set username */
  2372. if (user != NULL && user[0] != '\0') {
  2373. conf_set_str(conf, CONF_username, user);
  2374. }
  2375. if (portnumber)
  2376. conf_set_int(conf, CONF_port, portnumber);
  2377. /*
  2378. * Disable scary things which shouldn't be enabled for simple
  2379. * things like SCP and SFTP: agent forwarding, port forwarding,
  2380. * X forwarding.
  2381. */
  2382. conf_set_bool(conf, CONF_x11_forward, false);
  2383. conf_set_bool(conf, CONF_agentfwd, false);
  2384. conf_set_bool(conf, CONF_ssh_simple, true);
  2385. {
  2386. char *key;
  2387. while ((key = conf_get_str_nthstrkey(conf, CONF_portfwd, 0)) != NULL)
  2388. conf_del_str_str(conf, CONF_portfwd, key);
  2389. }
  2390. /* Set up subsystem name. */
  2391. conf_set_str(conf, CONF_remote_cmd, "sftp");
  2392. conf_set_bool(conf, CONF_ssh_subsys, true);
  2393. conf_set_bool(conf, CONF_nopty, true);
  2394. /*
  2395. * Set up fallback option, for SSH-1 servers or servers with the
  2396. * sftp subsystem not enabled but the server binary installed
  2397. * in the usual place. We only support fallback on Unix
  2398. * systems, and we use a kludgy piece of shellery which should
  2399. * try to find sftp-server in various places (the obvious
  2400. * systemwide spots /usr/lib and /usr/local/lib, and then the
  2401. * user's PATH) and finally give up.
  2402. *
  2403. * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
  2404. * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
  2405. * exec sftp-server
  2406. *
  2407. * the idea being that this will attempt to use either of the
  2408. * obvious pathnames and then give up, and when it does give up
  2409. * it will print the preferred pathname in the error messages.
  2410. */
  2411. conf_set_str(conf, CONF_remote_cmd2,
  2412. "test -x /usr/lib/sftp-server &&"
  2413. " exec /usr/lib/sftp-server\n"
  2414. "test -x /usr/local/lib/sftp-server &&"
  2415. " exec /usr/local/lib/sftp-server\n"
  2416. "exec sftp-server");
  2417. conf_set_bool(conf, CONF_ssh_subsys2, false);
  2418. psftp_logctx = log_init(console_cli_logpolicy, conf);
  2419. platform_psftp_pre_conn_setup(console_cli_logpolicy);
  2420. err = backend_init(backend_vt_from_proto(
  2421. conf_get_int(conf, CONF_protocol)),
  2422. psftp_seat, &backend, psftp_logctx, conf,
  2423. conf_get_str(conf, CONF_host),
  2424. conf_get_int(conf, CONF_port),
  2425. &realhost, 0,
  2426. conf_get_bool(conf, CONF_tcp_keepalives));
  2427. if (err != NULL) {
  2428. fprintf(stderr, "ssh_init: %s\n", err);
  2429. return 1;
  2430. }
  2431. while (!backend_sendok(backend)) {
  2432. if (backend_exitcode(backend) >= 0)
  2433. return 1;
  2434. if (ssh_sftp_loop_iteration() < 0) {
  2435. fprintf(stderr, "ssh_init: error during SSH connection setup\n");
  2436. return 1;
  2437. }
  2438. }
  2439. if (verbose && realhost != NULL)
  2440. printf("Connected to %s\n", realhost);
  2441. if (realhost != NULL)
  2442. sfree(realhost);
  2443. return 0;
  2444. }
  2445. void cmdline_error(const char *p, ...)
  2446. {
  2447. va_list ap;
  2448. fprintf(stderr, "psftp: ");
  2449. va_start(ap, p);
  2450. vfprintf(stderr, p, ap);
  2451. va_end(ap);
  2452. fprintf(stderr, "\n try typing \"psftp -h\" for help\n");
  2453. exit(1);
  2454. }
  2455. const bool share_can_be_downstream = true;
  2456. const bool share_can_be_upstream = false;
  2457. static stdio_sink stderr_ss;
  2458. static StripCtrlChars *stderr_scc;
  2459. const unsigned cmdline_tooltype = TOOLTYPE_FILETRANSFER;
  2460. /*
  2461. * Main program. Parse arguments etc.
  2462. */
  2463. int psftp_main(int argc, char *argv[])
  2464. {
  2465. int i, toret;
  2466. int portnumber = 0;
  2467. char *userhost, *user;
  2468. int mode = 0;
  2469. int modeflags = 0;
  2470. bool sanitise_stderr = true;
  2471. char *batchfile = NULL;
  2472. sk_init();
  2473. userhost = user = NULL;
  2474. /* Load Default Settings before doing anything else. */
  2475. conf = conf_new();
  2476. do_defaults(NULL, conf);
  2477. for (i = 1; i < argc; i++) {
  2478. int retd;
  2479. if (argv[i][0] != '-') {
  2480. if (userhost)
  2481. usage();
  2482. else
  2483. userhost = dupstr(argv[i]);
  2484. continue;
  2485. }
  2486. retd = cmdline_process_param(
  2487. argv[i], i+1 < argc ? argv[i+1] : NULL, 1, conf);
  2488. if (retd == -2) {
  2489. cmdline_error("option \"%s\" requires an argument", argv[i]);
  2490. } else if (retd == 2) {
  2491. i++; /* skip next argument */
  2492. } else if (retd == 1) {
  2493. /* We have our own verbosity in addition to `flags'. */
  2494. if (cmdline_verbose())
  2495. verbose = true;
  2496. } else if (strcmp(argv[i], "-h") == 0 ||
  2497. strcmp(argv[i], "-?") == 0 ||
  2498. strcmp(argv[i], "--help") == 0) {
  2499. usage();
  2500. } else if (strcmp(argv[i], "-pgpfp") == 0) {
  2501. pgp_fingerprints();
  2502. return 1;
  2503. } else if (strcmp(argv[i], "-V") == 0 ||
  2504. strcmp(argv[i], "--version") == 0) {
  2505. version();
  2506. } else if (strcmp(argv[i], "-b") == 0 && i + 1 < argc) {
  2507. mode = 1;
  2508. batchfile = argv[++i];
  2509. } else if (strcmp(argv[i], "-bc") == 0) {
  2510. modeflags = modeflags | 1;
  2511. } else if (strcmp(argv[i], "-be") == 0) {
  2512. modeflags = modeflags | 2;
  2513. } else if (strcmp(argv[i], "-sanitise-stderr") == 0) {
  2514. sanitise_stderr = true;
  2515. } else if (strcmp(argv[i], "-no-sanitise-stderr") == 0) {
  2516. sanitise_stderr = false;
  2517. } else if (strcmp(argv[i], "--") == 0) {
  2518. i++;
  2519. break;
  2520. } else {
  2521. cmdline_error("unknown option \"%s\"", argv[i]);
  2522. }
  2523. }
  2524. argc -= i;
  2525. argv += i;
  2526. backend = NULL;
  2527. stdio_sink_init(&stderr_ss, stderr);
  2528. stderr_bs = BinarySink_UPCAST(&stderr_ss);
  2529. if (sanitise_stderr) {
  2530. stderr_scc = stripctrl_new(stderr_bs, false, L'\0');
  2531. stderr_bs = BinarySink_UPCAST(stderr_scc);
  2532. }
  2533. string_scc = stripctrl_new(NULL, false, L'\0');
  2534. /*
  2535. * If the loaded session provides a hostname, and a hostname has not
  2536. * otherwise been specified, pop it in `userhost' so that
  2537. * `psftp -load sessname' is sufficient to start a session.
  2538. */
  2539. if (!userhost && conf_get_str(conf, CONF_host)[0] != '\0') {
  2540. userhost = dupstr(conf_get_str(conf, CONF_host));
  2541. }
  2542. /*
  2543. * If a user@host string has already been provided, connect to
  2544. * it now.
  2545. */
  2546. if (userhost) {
  2547. int retd;
  2548. retd = psftp_connect(userhost, user, portnumber);
  2549. sfree(userhost);
  2550. if (retd)
  2551. return 1;
  2552. if (do_sftp_init())
  2553. return 1;
  2554. } else {
  2555. printf("psftp: no hostname specified; use \"open host.name\""
  2556. " to connect\n");
  2557. }
  2558. toret = do_sftp(mode, modeflags, batchfile);
  2559. if (backend && backend_connected(backend)) {
  2560. char ch;
  2561. backend_special(backend, SS_EOF, 0);
  2562. sent_eof = true;
  2563. sftp_recvdata(&ch, 1);
  2564. }
  2565. do_sftp_cleanup();
  2566. random_save_seed();
  2567. cmdline_cleanup();
  2568. sk_cleanup();
  2569. stripctrl_free(string_scc);
  2570. stripctrl_free(stderr_scc);
  2571. if (psftp_logctx)
  2572. log_free(psftp_logctx);
  2573. return toret;
  2574. }