ftpd.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Simple FTP daemon, based on vsftpd 2.0.7 (written by Chris Evans)
  4. *
  5. * Author: Adam Tkac <vonsch@gmail.com>
  6. *
  7. * Licensed under GPLv2, see file LICENSE in this source tree.
  8. *
  9. * Only subset of FTP protocol is implemented but vast majority of clients
  10. * should not have any problem.
  11. *
  12. * You have to run this daemon via inetd.
  13. */
  14. //usage:#define ftpd_trivial_usage
  15. //usage: "[-wvS] [-t N] [-T N] [DIR]"
  16. //usage:#define ftpd_full_usage "\n\n"
  17. //usage: "Anonymous FTP server\n"
  18. //usage: "\n"
  19. //usage: "ftpd should be used as an inetd service.\n"
  20. //usage: "ftpd's line for inetd.conf:\n"
  21. //usage: " 21 stream tcp nowait root ftpd ftpd /files/to/serve\n"
  22. //usage: "It also can be ran from tcpsvd:\n"
  23. //usage: " tcpsvd -vE 0.0.0.0 21 ftpd /files/to/serve\n"
  24. //usage: "\n -w Allow upload"
  25. //usage: "\n -v Log errors to stderr. -vv: verbose log"
  26. //usage: "\n -S Log errors to syslog. -SS: verbose log"
  27. //usage: "\n -t,-T Idle and absolute timeouts"
  28. //usage: "\n DIR Change root to this directory"
  29. #include "libbb.h"
  30. #include <syslog.h>
  31. #include <netinet/tcp.h>
  32. #define FTP_DATACONN 150
  33. #define FTP_NOOPOK 200
  34. #define FTP_TYPEOK 200
  35. #define FTP_PORTOK 200
  36. #define FTP_STRUOK 200
  37. #define FTP_MODEOK 200
  38. #define FTP_ALLOOK 202
  39. #define FTP_STATOK 211
  40. #define FTP_STATFILE_OK 213
  41. #define FTP_HELP 214
  42. #define FTP_SYSTOK 215
  43. #define FTP_GREET 220
  44. #define FTP_GOODBYE 221
  45. #define FTP_TRANSFEROK 226
  46. #define FTP_PASVOK 227
  47. /*#define FTP_EPRTOK 228*/
  48. #define FTP_EPSVOK 229
  49. #define FTP_LOGINOK 230
  50. #define FTP_CWDOK 250
  51. #define FTP_RMDIROK 250
  52. #define FTP_DELEOK 250
  53. #define FTP_RENAMEOK 250
  54. #define FTP_PWDOK 257
  55. #define FTP_MKDIROK 257
  56. #define FTP_GIVEPWORD 331
  57. #define FTP_RESTOK 350
  58. #define FTP_RNFROK 350
  59. #define FTP_TIMEOUT 421
  60. #define FTP_BADSENDCONN 425
  61. #define FTP_BADSENDNET 426
  62. #define FTP_BADSENDFILE 451
  63. #define FTP_BADCMD 500
  64. #define FTP_COMMANDNOTIMPL 502
  65. #define FTP_NEEDUSER 503
  66. #define FTP_NEEDRNFR 503
  67. #define FTP_BADSTRU 504
  68. #define FTP_BADMODE 504
  69. #define FTP_LOGINERR 530
  70. #define FTP_FILEFAIL 550
  71. #define FTP_NOPERM 550
  72. #define FTP_UPLOADFAIL 553
  73. #define STR1(s) #s
  74. #define STR(s) STR1(s)
  75. /* Convert a constant to 3-digit string, packed into uint32_t */
  76. enum {
  77. /* Shift for Nth decimal digit */
  78. SHIFT2 = 0 * BB_LITTLE_ENDIAN + 24 * BB_BIG_ENDIAN,
  79. SHIFT1 = 8 * BB_LITTLE_ENDIAN + 16 * BB_BIG_ENDIAN,
  80. SHIFT0 = 16 * BB_LITTLE_ENDIAN + 8 * BB_BIG_ENDIAN,
  81. /* And for 4th position (space) */
  82. SHIFTsp = 24 * BB_LITTLE_ENDIAN + 0 * BB_BIG_ENDIAN,
  83. };
  84. #define STRNUM32(s) (uint32_t)(0 \
  85. | (('0' + ((s) / 1 % 10)) << SHIFT0) \
  86. | (('0' + ((s) / 10 % 10)) << SHIFT1) \
  87. | (('0' + ((s) / 100 % 10)) << SHIFT2) \
  88. )
  89. #define STRNUM32sp(s) (uint32_t)(0 \
  90. | (' ' << SHIFTsp) \
  91. | (('0' + ((s) / 1 % 10)) << SHIFT0) \
  92. | (('0' + ((s) / 10 % 10)) << SHIFT1) \
  93. | (('0' + ((s) / 100 % 10)) << SHIFT2) \
  94. )
  95. #define MSG_OK "Operation successful\r\n"
  96. #define MSG_ERR "Error\r\n"
  97. struct globals {
  98. int pasv_listen_fd;
  99. #if !BB_MMU
  100. int root_fd;
  101. #endif
  102. int local_file_fd;
  103. unsigned end_time;
  104. unsigned timeout;
  105. unsigned verbose;
  106. off_t local_file_pos;
  107. off_t restart_pos;
  108. len_and_sockaddr *local_addr;
  109. len_and_sockaddr *port_addr;
  110. char *ftp_cmd;
  111. char *ftp_arg;
  112. #if ENABLE_FEATURE_FTP_WRITE
  113. char *rnfr_filename;
  114. #endif
  115. /* We need these aligned to uint32_t */
  116. char msg_ok [(sizeof("NNN " MSG_OK ) + 3) & 0xfffc];
  117. char msg_err[(sizeof("NNN " MSG_ERR) + 3) & 0xfffc];
  118. } FIX_ALIASING;
  119. #define G (*(struct globals*)&bb_common_bufsiz1)
  120. #define INIT_G() do { \
  121. /* Moved to main */ \
  122. /*strcpy(G.msg_ok + 4, MSG_OK );*/ \
  123. /*strcpy(G.msg_err + 4, MSG_ERR);*/ \
  124. } while (0)
  125. static char *
  126. escape_text(const char *prepend, const char *str, unsigned escapee)
  127. {
  128. unsigned retlen, remainlen, chunklen;
  129. char *ret, *found;
  130. char append;
  131. append = (char)escapee;
  132. escapee >>= 8;
  133. remainlen = strlen(str);
  134. retlen = strlen(prepend);
  135. ret = xmalloc(retlen + remainlen * 2 + 1 + 1);
  136. strcpy(ret, prepend);
  137. for (;;) {
  138. found = strchrnul(str, escapee);
  139. chunklen = found - str + 1;
  140. /* Copy chunk up to and including escapee (or NUL) to ret */
  141. memcpy(ret + retlen, str, chunklen);
  142. retlen += chunklen;
  143. if (*found == '\0') {
  144. /* It wasn't escapee, it was NUL! */
  145. ret[retlen - 1] = append; /* replace NUL */
  146. ret[retlen] = '\0'; /* add NUL */
  147. break;
  148. }
  149. ret[retlen++] = escapee; /* duplicate escapee */
  150. str = found + 1;
  151. }
  152. return ret;
  153. }
  154. /* Returns strlen as a bonus */
  155. static unsigned
  156. replace_char(char *str, char from, char to)
  157. {
  158. char *p = str;
  159. while (*p) {
  160. if (*p == from)
  161. *p = to;
  162. p++;
  163. }
  164. return p - str;
  165. }
  166. static void
  167. verbose_log(const char *str)
  168. {
  169. bb_error_msg("%.*s", (int)strcspn(str, "\r\n"), str);
  170. }
  171. /* NB: status_str is char[4] packed into uint32_t */
  172. static void
  173. cmdio_write(uint32_t status_str, const char *str)
  174. {
  175. char *response;
  176. int len;
  177. /* FTP uses telnet protocol for command link.
  178. * In telnet, 0xff is an escape char, and needs to be escaped: */
  179. response = escape_text((char *) &status_str, str, (0xff << 8) + '\r');
  180. /* FTP sends embedded LFs as NULs */
  181. len = replace_char(response, '\n', '\0');
  182. response[len++] = '\n'; /* tack on trailing '\n' */
  183. xwrite(STDOUT_FILENO, response, len);
  184. if (G.verbose > 1)
  185. verbose_log(response);
  186. free(response);
  187. }
  188. static void
  189. cmdio_write_ok(unsigned status)
  190. {
  191. *(uint32_t *) G.msg_ok = status;
  192. xwrite(STDOUT_FILENO, G.msg_ok, sizeof("NNN " MSG_OK) - 1);
  193. if (G.verbose > 1)
  194. verbose_log(G.msg_ok);
  195. }
  196. #define WRITE_OK(a) cmdio_write_ok(STRNUM32sp(a))
  197. /* TODO: output strerr(errno) if errno != 0? */
  198. static void
  199. cmdio_write_error(unsigned status)
  200. {
  201. *(uint32_t *) G.msg_err = status;
  202. xwrite(STDOUT_FILENO, G.msg_err, sizeof("NNN " MSG_ERR) - 1);
  203. if (G.verbose > 0)
  204. verbose_log(G.msg_err);
  205. }
  206. #define WRITE_ERR(a) cmdio_write_error(STRNUM32sp(a))
  207. static void
  208. cmdio_write_raw(const char *p_text)
  209. {
  210. xwrite_str(STDOUT_FILENO, p_text);
  211. if (G.verbose > 1)
  212. verbose_log(p_text);
  213. }
  214. static void
  215. timeout_handler(int sig UNUSED_PARAM)
  216. {
  217. off_t pos;
  218. int sv_errno = errno;
  219. if ((int)(monotonic_sec() - G.end_time) >= 0)
  220. goto timed_out;
  221. if (!G.local_file_fd)
  222. goto timed_out;
  223. pos = xlseek(G.local_file_fd, 0, SEEK_CUR);
  224. if (pos == G.local_file_pos)
  225. goto timed_out;
  226. G.local_file_pos = pos;
  227. alarm(G.timeout);
  228. errno = sv_errno;
  229. return;
  230. timed_out:
  231. cmdio_write_raw(STR(FTP_TIMEOUT)" Timeout\r\n");
  232. /* TODO: do we need to abort (as opposed to usual shutdown) data transfer? */
  233. exit(1);
  234. }
  235. /* Simple commands */
  236. static void
  237. handle_pwd(void)
  238. {
  239. char *cwd, *response;
  240. cwd = xrealloc_getcwd_or_warn(NULL);
  241. if (cwd == NULL)
  242. cwd = xstrdup("");
  243. /* We have to promote each " to "" */
  244. response = escape_text(" \"", cwd, ('"' << 8) + '"');
  245. free(cwd);
  246. cmdio_write(STRNUM32(FTP_PWDOK), response);
  247. free(response);
  248. }
  249. static void
  250. handle_cwd(void)
  251. {
  252. if (!G.ftp_arg || chdir(G.ftp_arg) != 0) {
  253. WRITE_ERR(FTP_FILEFAIL);
  254. return;
  255. }
  256. WRITE_OK(FTP_CWDOK);
  257. }
  258. static void
  259. handle_cdup(void)
  260. {
  261. G.ftp_arg = (char*)"..";
  262. handle_cwd();
  263. }
  264. static void
  265. handle_stat(void)
  266. {
  267. cmdio_write_raw(STR(FTP_STATOK)"-Server status:\r\n"
  268. " TYPE: BINARY\r\n"
  269. STR(FTP_STATOK)" Ok\r\n");
  270. }
  271. /* Examples of HELP and FEAT:
  272. # nc -vvv ftp.kernel.org 21
  273. ftp.kernel.org (130.239.17.4:21) open
  274. 220 Welcome to ftp.kernel.org.
  275. FEAT
  276. 211-Features:
  277. EPRT
  278. EPSV
  279. MDTM
  280. PASV
  281. REST STREAM
  282. SIZE
  283. TVFS
  284. UTF8
  285. 211 End
  286. HELP
  287. 214-The following commands are recognized.
  288. ABOR ACCT ALLO APPE CDUP CWD DELE EPRT EPSV FEAT HELP LIST MDTM MKD
  289. MODE NLST NOOP OPTS PASS PASV PORT PWD QUIT REIN REST RETR RMD RNFR
  290. RNTO SITE SIZE SMNT STAT STOR STOU STRU SYST TYPE USER XCUP XCWD XMKD
  291. XPWD XRMD
  292. 214 Help OK.
  293. */
  294. static void
  295. handle_feat(unsigned status)
  296. {
  297. cmdio_write(status, "-Features:");
  298. cmdio_write_raw(" EPSV\r\n"
  299. " PASV\r\n"
  300. " REST STREAM\r\n"
  301. " MDTM\r\n"
  302. " SIZE\r\n");
  303. cmdio_write(status, " Ok");
  304. }
  305. /* Download commands */
  306. static inline int
  307. port_active(void)
  308. {
  309. return (G.port_addr != NULL);
  310. }
  311. static inline int
  312. pasv_active(void)
  313. {
  314. return (G.pasv_listen_fd > STDOUT_FILENO);
  315. }
  316. static void
  317. port_pasv_cleanup(void)
  318. {
  319. free(G.port_addr);
  320. G.port_addr = NULL;
  321. if (G.pasv_listen_fd > STDOUT_FILENO)
  322. close(G.pasv_listen_fd);
  323. G.pasv_listen_fd = -1;
  324. }
  325. /* On error, emits error code to the peer */
  326. static int
  327. ftpdataio_get_pasv_fd(void)
  328. {
  329. int remote_fd;
  330. remote_fd = accept(G.pasv_listen_fd, NULL, 0);
  331. if (remote_fd < 0) {
  332. WRITE_ERR(FTP_BADSENDCONN);
  333. return remote_fd;
  334. }
  335. setsockopt(remote_fd, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
  336. return remote_fd;
  337. }
  338. /* Clears port/pasv data.
  339. * This means we dont waste resources, for example, keeping
  340. * PASV listening socket open when it is no longer needed.
  341. * On error, emits error code to the peer (or exits).
  342. * On success, emits p_status_msg to the peer.
  343. */
  344. static int
  345. get_remote_transfer_fd(const char *p_status_msg)
  346. {
  347. int remote_fd;
  348. if (pasv_active())
  349. /* On error, emits error code to the peer */
  350. remote_fd = ftpdataio_get_pasv_fd();
  351. else
  352. /* Exits on error */
  353. remote_fd = xconnect_stream(G.port_addr);
  354. port_pasv_cleanup();
  355. if (remote_fd < 0)
  356. return remote_fd;
  357. cmdio_write(STRNUM32(FTP_DATACONN), p_status_msg);
  358. return remote_fd;
  359. }
  360. /* If there were neither PASV nor PORT, emits error code to the peer */
  361. static int
  362. port_or_pasv_was_seen(void)
  363. {
  364. if (!pasv_active() && !port_active()) {
  365. cmdio_write_raw(STR(FTP_BADSENDCONN)" Use PORT/PASV first\r\n");
  366. return 0;
  367. }
  368. return 1;
  369. }
  370. /* Exits on error */
  371. static unsigned
  372. bind_for_passive_mode(void)
  373. {
  374. int fd;
  375. unsigned port;
  376. port_pasv_cleanup();
  377. G.pasv_listen_fd = fd = xsocket(G.local_addr->u.sa.sa_family, SOCK_STREAM, 0);
  378. setsockopt_reuseaddr(fd);
  379. set_nport(&G.local_addr->u.sa, 0);
  380. xbind(fd, &G.local_addr->u.sa, G.local_addr->len);
  381. xlisten(fd, 1);
  382. getsockname(fd, &G.local_addr->u.sa, &G.local_addr->len);
  383. port = get_nport(&G.local_addr->u.sa);
  384. port = ntohs(port);
  385. return port;
  386. }
  387. /* Exits on error */
  388. static void
  389. handle_pasv(void)
  390. {
  391. unsigned port;
  392. char *addr, *response;
  393. port = bind_for_passive_mode();
  394. if (G.local_addr->u.sa.sa_family == AF_INET)
  395. addr = xmalloc_sockaddr2dotted_noport(&G.local_addr->u.sa);
  396. else /* seen this in the wild done by other ftp servers: */
  397. addr = xstrdup("0.0.0.0");
  398. replace_char(addr, '.', ',');
  399. response = xasprintf(STR(FTP_PASVOK)" PASV ok (%s,%u,%u)\r\n",
  400. addr, (int)(port >> 8), (int)(port & 255));
  401. free(addr);
  402. cmdio_write_raw(response);
  403. free(response);
  404. }
  405. /* Exits on error */
  406. static void
  407. handle_epsv(void)
  408. {
  409. unsigned port;
  410. char *response;
  411. port = bind_for_passive_mode();
  412. response = xasprintf(STR(FTP_EPSVOK)" EPSV ok (|||%u|)\r\n", port);
  413. cmdio_write_raw(response);
  414. free(response);
  415. }
  416. static void
  417. handle_port(void)
  418. {
  419. unsigned port, port_hi;
  420. char *raw, *comma;
  421. #ifdef WHY_BOTHER_WE_CAN_ASSUME_IP_MATCHES
  422. socklen_t peer_ipv4_len;
  423. struct sockaddr_in peer_ipv4;
  424. struct in_addr port_ipv4_sin_addr;
  425. #endif
  426. port_pasv_cleanup();
  427. raw = G.ftp_arg;
  428. /* PORT command format makes sense only over IPv4 */
  429. if (!raw
  430. #ifdef WHY_BOTHER_WE_CAN_ASSUME_IP_MATCHES
  431. || G.local_addr->u.sa.sa_family != AF_INET
  432. #endif
  433. ) {
  434. bail:
  435. WRITE_ERR(FTP_BADCMD);
  436. return;
  437. }
  438. comma = strrchr(raw, ',');
  439. if (comma == NULL)
  440. goto bail;
  441. *comma = '\0';
  442. port = bb_strtou(&comma[1], NULL, 10);
  443. if (errno || port > 0xff)
  444. goto bail;
  445. comma = strrchr(raw, ',');
  446. if (comma == NULL)
  447. goto bail;
  448. *comma = '\0';
  449. port_hi = bb_strtou(&comma[1], NULL, 10);
  450. if (errno || port_hi > 0xff)
  451. goto bail;
  452. port |= port_hi << 8;
  453. #ifdef WHY_BOTHER_WE_CAN_ASSUME_IP_MATCHES
  454. replace_char(raw, ',', '.');
  455. /* We are verifying that PORT's IP matches getpeername().
  456. * Otherwise peer can make us open data connections
  457. * to other hosts (security problem!)
  458. * This code would be too simplistic:
  459. * lsa = xdotted2sockaddr(raw, port);
  460. * if (lsa == NULL) goto bail;
  461. */
  462. if (!inet_aton(raw, &port_ipv4_sin_addr))
  463. goto bail;
  464. peer_ipv4_len = sizeof(peer_ipv4);
  465. if (getpeername(STDIN_FILENO, &peer_ipv4, &peer_ipv4_len) != 0)
  466. goto bail;
  467. if (memcmp(&port_ipv4_sin_addr, &peer_ipv4.sin_addr, sizeof(struct in_addr)) != 0)
  468. goto bail;
  469. G.port_addr = xdotted2sockaddr(raw, port);
  470. #else
  471. G.port_addr = get_peer_lsa(STDIN_FILENO);
  472. set_nport(&G.port_addr->u.sa, htons(port));
  473. #endif
  474. WRITE_OK(FTP_PORTOK);
  475. }
  476. static void
  477. handle_rest(void)
  478. {
  479. /* When ftp_arg == NULL simply restart from beginning */
  480. G.restart_pos = G.ftp_arg ? xatoi_positive(G.ftp_arg) : 0;
  481. WRITE_OK(FTP_RESTOK);
  482. }
  483. static void
  484. handle_retr(void)
  485. {
  486. struct stat statbuf;
  487. off_t bytes_transferred;
  488. int remote_fd;
  489. int local_file_fd;
  490. off_t offset = G.restart_pos;
  491. char *response;
  492. G.restart_pos = 0;
  493. if (!port_or_pasv_was_seen())
  494. return; /* port_or_pasv_was_seen emitted error response */
  495. /* O_NONBLOCK is useful if file happens to be a device node */
  496. local_file_fd = G.ftp_arg ? open(G.ftp_arg, O_RDONLY | O_NONBLOCK) : -1;
  497. if (local_file_fd < 0) {
  498. WRITE_ERR(FTP_FILEFAIL);
  499. return;
  500. }
  501. if (fstat(local_file_fd, &statbuf) != 0 || !S_ISREG(statbuf.st_mode)) {
  502. /* Note - pretend open failed */
  503. WRITE_ERR(FTP_FILEFAIL);
  504. goto file_close_out;
  505. }
  506. G.local_file_fd = local_file_fd;
  507. /* Now deactive O_NONBLOCK, otherwise we have a problem
  508. * on DMAPI filesystems such as XFS DMAPI.
  509. */
  510. ndelay_off(local_file_fd);
  511. /* Set the download offset (from REST) if any */
  512. if (offset != 0)
  513. xlseek(local_file_fd, offset, SEEK_SET);
  514. response = xasprintf(
  515. " Opening BINARY connection for %s (%"OFF_FMT"u bytes)",
  516. G.ftp_arg, statbuf.st_size);
  517. remote_fd = get_remote_transfer_fd(response);
  518. free(response);
  519. if (remote_fd < 0)
  520. goto file_close_out;
  521. bytes_transferred = bb_copyfd_eof(local_file_fd, remote_fd);
  522. close(remote_fd);
  523. if (bytes_transferred < 0)
  524. WRITE_ERR(FTP_BADSENDFILE);
  525. else
  526. WRITE_OK(FTP_TRANSFEROK);
  527. file_close_out:
  528. close(local_file_fd);
  529. G.local_file_fd = 0;
  530. }
  531. /* List commands */
  532. static int
  533. popen_ls(const char *opt)
  534. {
  535. const char *argv[5];
  536. struct fd_pair outfd;
  537. pid_t pid;
  538. argv[0] = "ftpd";
  539. argv[1] = opt; /* "-l" or "-1" */
  540. #if BB_MMU
  541. argv[2] = "--";
  542. #else
  543. /* NOMMU ftpd ls helper chdirs to argv[2],
  544. * preventing peer from seeing real root. */
  545. argv[2] = xrealloc_getcwd_or_warn(NULL);
  546. #endif
  547. argv[3] = G.ftp_arg;
  548. argv[4] = NULL;
  549. /* Improve compatibility with non-RFC conforming FTP clients
  550. * which send e.g. "LIST -l", "LIST -la", "LIST -aL".
  551. * See https://bugs.kde.org/show_bug.cgi?id=195578 */
  552. if (ENABLE_FEATURE_FTPD_ACCEPT_BROKEN_LIST
  553. && G.ftp_arg && G.ftp_arg[0] == '-'
  554. ) {
  555. const char *tmp = strchr(G.ftp_arg, ' ');
  556. if (tmp) /* skip the space */
  557. tmp++;
  558. argv[3] = tmp;
  559. }
  560. xpiped_pair(outfd);
  561. /*fflush_all(); - so far we dont use stdio on output */
  562. pid = BB_MMU ? xfork() : xvfork();
  563. if (pid == 0) {
  564. /* child */
  565. #if !BB_MMU
  566. /* On NOMMU, we want to execute a child - copy of ourself.
  567. * In chroot we usually can't do it. Thus we chdir
  568. * out of the chroot back to original root,
  569. * and (see later below) execute bb_busybox_exec_path
  570. * relative to current directory */
  571. if (fchdir(G.root_fd) != 0)
  572. _exit(127);
  573. /*close(G.root_fd); - close_on_exec_on() took care of this */
  574. #endif
  575. /* NB: close _first_, then move fd! */
  576. close(outfd.rd);
  577. xmove_fd(outfd.wr, STDOUT_FILENO);
  578. /* Opening /dev/null in chroot is hard.
  579. * Just making sure STDIN_FILENO is opened
  580. * to something harmless. Paranoia,
  581. * ls won't read it anyway */
  582. close(STDIN_FILENO);
  583. dup(STDOUT_FILENO); /* copy will become STDIN_FILENO */
  584. #if BB_MMU
  585. /* memset(&G, 0, sizeof(G)); - ls_main does it */
  586. exit(ls_main(ARRAY_SIZE(argv) - 1, (char**) argv));
  587. #else
  588. /* + 1: we must use relative path here if in chroot.
  589. * For example, execv("/proc/self/exe") will fail, since
  590. * it looks for "/proc/self/exe" _relative to chroot!_ */
  591. execv(bb_busybox_exec_path + 1, (char**) argv);
  592. _exit(127);
  593. #endif
  594. }
  595. /* parent */
  596. close(outfd.wr);
  597. #if !BB_MMU
  598. free((char*)argv[2]);
  599. #endif
  600. return outfd.rd;
  601. }
  602. enum {
  603. USE_CTRL_CONN = 1,
  604. LONG_LISTING = 2,
  605. };
  606. static void
  607. handle_dir_common(int opts)
  608. {
  609. FILE *ls_fp;
  610. char *line;
  611. int ls_fd;
  612. if (!(opts & USE_CTRL_CONN) && !port_or_pasv_was_seen())
  613. return; /* port_or_pasv_was_seen emitted error response */
  614. /* -n prevents user/groupname display,
  615. * which can be problematic in chroot */
  616. ls_fd = popen_ls((opts & LONG_LISTING) ? "-l" : "-1");
  617. ls_fp = xfdopen_for_read(ls_fd);
  618. if (opts & USE_CTRL_CONN) {
  619. /* STAT <filename> */
  620. cmdio_write_raw(STR(FTP_STATFILE_OK)"-File status:\r\n");
  621. while (1) {
  622. line = xmalloc_fgetline(ls_fp);
  623. if (!line)
  624. break;
  625. /* Hack: 0 results in no status at all */
  626. /* Note: it's ok that we don't prepend space,
  627. * ftp.kernel.org doesn't do that too */
  628. cmdio_write(0, line);
  629. free(line);
  630. }
  631. WRITE_OK(FTP_STATFILE_OK);
  632. } else {
  633. /* LIST/NLST [<filename>] */
  634. int remote_fd = get_remote_transfer_fd(" Directory listing");
  635. if (remote_fd >= 0) {
  636. while (1) {
  637. line = xmalloc_fgetline(ls_fp);
  638. if (!line)
  639. break;
  640. /* I've seen clients complaining when they
  641. * are fed with ls output with bare '\n'.
  642. * Pity... that would be much simpler.
  643. */
  644. /* TODO: need to s/LF/NUL/g here */
  645. xwrite_str(remote_fd, line);
  646. xwrite(remote_fd, "\r\n", 2);
  647. free(line);
  648. }
  649. }
  650. close(remote_fd);
  651. WRITE_OK(FTP_TRANSFEROK);
  652. }
  653. fclose(ls_fp); /* closes ls_fd too */
  654. }
  655. static void
  656. handle_list(void)
  657. {
  658. handle_dir_common(LONG_LISTING);
  659. }
  660. static void
  661. handle_nlst(void)
  662. {
  663. /* NLST returns list of names, "\r\n" terminated without regard
  664. * to the current binary flag. Names may start with "/",
  665. * then they represent full names (we don't produce such names),
  666. * otherwise names are relative to current directory.
  667. * Embedded "\n" are replaced by NULs. This is safe since names
  668. * can never contain NUL.
  669. */
  670. handle_dir_common(0);
  671. }
  672. static void
  673. handle_stat_file(void)
  674. {
  675. handle_dir_common(LONG_LISTING + USE_CTRL_CONN);
  676. }
  677. /* This can be extended to handle MLST, as all info is available
  678. * in struct stat for that:
  679. * MLST file_name
  680. * 250-Listing file_name
  681. * type=file;size=4161;modify=19970214165800; /dir/dir/file_name
  682. * 250 End
  683. * Nano-doc:
  684. * MLST [<file or dir name, "." assumed if not given>]
  685. * Returned name should be either the same as requested, or fully qualified.
  686. * If there was no parameter, return "" or (preferred) fully-qualified name.
  687. * Returned "facts" (case is not important):
  688. * size - size in octets
  689. * modify - last modification time
  690. * type - entry type (file,dir,OS.unix=block)
  691. * (+ cdir and pdir types for MLSD)
  692. * unique - unique id of file/directory (inode#)
  693. * perm -
  694. * a: can be appended to (APPE)
  695. * d: can be deleted (RMD/DELE)
  696. * f: can be renamed (RNFR)
  697. * r: can be read (RETR)
  698. * w: can be written (STOR)
  699. * e: can CWD into this dir
  700. * l: this dir can be listed (dir only!)
  701. * c: can create files in this dir
  702. * m: can create dirs in this dir (MKD)
  703. * p: can delete files in this dir
  704. * UNIX.mode - unix file mode
  705. */
  706. static void
  707. handle_size_or_mdtm(int need_size)
  708. {
  709. struct stat statbuf;
  710. struct tm broken_out;
  711. char buf[(sizeof("NNN %"OFF_FMT"u\r\n") + sizeof(off_t) * 3)
  712. | sizeof("NNN YYYYMMDDhhmmss\r\n")
  713. ];
  714. if (!G.ftp_arg
  715. || stat(G.ftp_arg, &statbuf) != 0
  716. || !S_ISREG(statbuf.st_mode)
  717. ) {
  718. WRITE_ERR(FTP_FILEFAIL);
  719. return;
  720. }
  721. if (need_size) {
  722. sprintf(buf, STR(FTP_STATFILE_OK)" %"OFF_FMT"u\r\n", statbuf.st_size);
  723. } else {
  724. gmtime_r(&statbuf.st_mtime, &broken_out);
  725. sprintf(buf, STR(FTP_STATFILE_OK)" %04u%02u%02u%02u%02u%02u\r\n",
  726. broken_out.tm_year + 1900,
  727. broken_out.tm_mon,
  728. broken_out.tm_mday,
  729. broken_out.tm_hour,
  730. broken_out.tm_min,
  731. broken_out.tm_sec);
  732. }
  733. cmdio_write_raw(buf);
  734. }
  735. /* Upload commands */
  736. #if ENABLE_FEATURE_FTP_WRITE
  737. static void
  738. handle_mkd(void)
  739. {
  740. if (!G.ftp_arg || mkdir(G.ftp_arg, 0777) != 0) {
  741. WRITE_ERR(FTP_FILEFAIL);
  742. return;
  743. }
  744. WRITE_OK(FTP_MKDIROK);
  745. }
  746. static void
  747. handle_rmd(void)
  748. {
  749. if (!G.ftp_arg || rmdir(G.ftp_arg) != 0) {
  750. WRITE_ERR(FTP_FILEFAIL);
  751. return;
  752. }
  753. WRITE_OK(FTP_RMDIROK);
  754. }
  755. static void
  756. handle_dele(void)
  757. {
  758. if (!G.ftp_arg || unlink(G.ftp_arg) != 0) {
  759. WRITE_ERR(FTP_FILEFAIL);
  760. return;
  761. }
  762. WRITE_OK(FTP_DELEOK);
  763. }
  764. static void
  765. handle_rnfr(void)
  766. {
  767. free(G.rnfr_filename);
  768. G.rnfr_filename = xstrdup(G.ftp_arg);
  769. WRITE_OK(FTP_RNFROK);
  770. }
  771. static void
  772. handle_rnto(void)
  773. {
  774. int retval;
  775. /* If we didn't get a RNFR, throw a wobbly */
  776. if (G.rnfr_filename == NULL || G.ftp_arg == NULL) {
  777. cmdio_write_raw(STR(FTP_NEEDRNFR)" Use RNFR first\r\n");
  778. return;
  779. }
  780. retval = rename(G.rnfr_filename, G.ftp_arg);
  781. free(G.rnfr_filename);
  782. G.rnfr_filename = NULL;
  783. if (retval) {
  784. WRITE_ERR(FTP_FILEFAIL);
  785. return;
  786. }
  787. WRITE_OK(FTP_RENAMEOK);
  788. }
  789. static void
  790. handle_upload_common(int is_append, int is_unique)
  791. {
  792. struct stat statbuf;
  793. char *tempname;
  794. off_t bytes_transferred;
  795. off_t offset;
  796. int local_file_fd;
  797. int remote_fd;
  798. offset = G.restart_pos;
  799. G.restart_pos = 0;
  800. if (!port_or_pasv_was_seen())
  801. return; /* port_or_pasv_was_seen emitted error response */
  802. tempname = NULL;
  803. local_file_fd = -1;
  804. if (is_unique) {
  805. tempname = xstrdup(" FILE: uniq.XXXXXX");
  806. local_file_fd = mkstemp(tempname + 7);
  807. } else if (G.ftp_arg) {
  808. int flags = O_WRONLY | O_CREAT | O_TRUNC;
  809. if (is_append)
  810. flags = O_WRONLY | O_CREAT | O_APPEND;
  811. if (offset)
  812. flags = O_WRONLY | O_CREAT;
  813. local_file_fd = open(G.ftp_arg, flags, 0666);
  814. }
  815. if (local_file_fd < 0
  816. || fstat(local_file_fd, &statbuf) != 0
  817. || !S_ISREG(statbuf.st_mode)
  818. ) {
  819. WRITE_ERR(FTP_UPLOADFAIL);
  820. if (local_file_fd >= 0)
  821. goto close_local_and_bail;
  822. return;
  823. }
  824. G.local_file_fd = local_file_fd;
  825. if (offset)
  826. xlseek(local_file_fd, offset, SEEK_SET);
  827. remote_fd = get_remote_transfer_fd(tempname ? tempname : " Ok to send data");
  828. free(tempname);
  829. if (remote_fd < 0)
  830. goto close_local_and_bail;
  831. bytes_transferred = bb_copyfd_eof(remote_fd, local_file_fd);
  832. close(remote_fd);
  833. if (bytes_transferred < 0)
  834. WRITE_ERR(FTP_BADSENDFILE);
  835. else
  836. WRITE_OK(FTP_TRANSFEROK);
  837. close_local_and_bail:
  838. close(local_file_fd);
  839. G.local_file_fd = 0;
  840. }
  841. static void
  842. handle_stor(void)
  843. {
  844. handle_upload_common(0, 0);
  845. }
  846. static void
  847. handle_appe(void)
  848. {
  849. G.restart_pos = 0;
  850. handle_upload_common(1, 0);
  851. }
  852. static void
  853. handle_stou(void)
  854. {
  855. G.restart_pos = 0;
  856. handle_upload_common(0, 1);
  857. }
  858. #endif /* ENABLE_FEATURE_FTP_WRITE */
  859. static uint32_t
  860. cmdio_get_cmd_and_arg(void)
  861. {
  862. int len;
  863. uint32_t cmdval;
  864. char *cmd;
  865. alarm(G.timeout);
  866. free(G.ftp_cmd);
  867. {
  868. /* Paranoia. Peer may send 1 gigabyte long cmd... */
  869. /* Using separate len_on_stk instead of len optimizes
  870. * code size (allows len to be in CPU register) */
  871. size_t len_on_stk = 8 * 1024;
  872. G.ftp_cmd = cmd = xmalloc_fgets_str_len(stdin, "\r\n", &len_on_stk);
  873. if (!cmd)
  874. exit(0);
  875. len = len_on_stk;
  876. }
  877. /* De-escape telnet: 0xff,0xff => 0xff */
  878. /* RFC959 says that ABOR, STAT, QUIT may be sent even during
  879. * data transfer, and may be preceded by telnet's "Interrupt Process"
  880. * code (two-byte sequence 255,244) and then by telnet "Synch" code
  881. * 255,242 (byte 242 is sent with TCP URG bit using send(MSG_OOB)
  882. * and may generate SIGURG on our side. See RFC854).
  883. * So far we don't support that (may install SIGURG handler if we'd want to),
  884. * but we need to at least remove 255,xxx pairs. lftp sends those. */
  885. /* Then de-escape FTP: NUL => '\n' */
  886. /* Testing for \xff:
  887. * Create file named '\xff': echo Hello >`echo -ne "\xff"`
  888. * Try to get it: ftpget -v 127.0.0.1 Eff `echo -ne "\xff\xff"`
  889. * (need "\xff\xff" until ftpget applet is fixed to do escaping :)
  890. * Testing for embedded LF:
  891. * LF_HERE=`echo -ne "LF\nHERE"`
  892. * echo Hello >"$LF_HERE"
  893. * ftpget -v 127.0.0.1 LF_HERE "$LF_HERE"
  894. */
  895. {
  896. int dst, src;
  897. /* Strip "\r\n" if it is there */
  898. if (len != 0 && cmd[len - 1] == '\n') {
  899. len--;
  900. if (len != 0 && cmd[len - 1] == '\r')
  901. len--;
  902. cmd[len] = '\0';
  903. }
  904. src = strchrnul(cmd, 0xff) - cmd;
  905. /* 99,99% there are neither NULs nor 255s and src == len */
  906. if (src < len) {
  907. dst = src;
  908. do {
  909. if ((unsigned char)(cmd[src]) == 255) {
  910. src++;
  911. /* 255,xxx - skip 255 */
  912. if ((unsigned char)(cmd[src]) != 255) {
  913. /* 255,!255 - skip both */
  914. src++;
  915. continue;
  916. }
  917. /* 255,255 - retain one 255 */
  918. }
  919. /* NUL => '\n' */
  920. cmd[dst++] = cmd[src] ? cmd[src] : '\n';
  921. src++;
  922. } while (src < len);
  923. cmd[dst] = '\0';
  924. }
  925. }
  926. if (G.verbose > 1)
  927. verbose_log(cmd);
  928. G.ftp_arg = strchr(cmd, ' ');
  929. if (G.ftp_arg != NULL)
  930. *G.ftp_arg++ = '\0';
  931. /* Uppercase and pack into uint32_t first word of the command */
  932. cmdval = 0;
  933. while (*cmd)
  934. cmdval = (cmdval << 8) + ((unsigned char)*cmd++ & (unsigned char)~0x20);
  935. return cmdval;
  936. }
  937. #define mk_const4(a,b,c,d) (((a * 0x100 + b) * 0x100 + c) * 0x100 + d)
  938. #define mk_const3(a,b,c) ((a * 0x100 + b) * 0x100 + c)
  939. enum {
  940. const_ALLO = mk_const4('A', 'L', 'L', 'O'),
  941. const_APPE = mk_const4('A', 'P', 'P', 'E'),
  942. const_CDUP = mk_const4('C', 'D', 'U', 'P'),
  943. const_CWD = mk_const3('C', 'W', 'D'),
  944. const_DELE = mk_const4('D', 'E', 'L', 'E'),
  945. const_EPSV = mk_const4('E', 'P', 'S', 'V'),
  946. const_FEAT = mk_const4('F', 'E', 'A', 'T'),
  947. const_HELP = mk_const4('H', 'E', 'L', 'P'),
  948. const_LIST = mk_const4('L', 'I', 'S', 'T'),
  949. const_MDTM = mk_const4('M', 'D', 'T', 'M'),
  950. const_MKD = mk_const3('M', 'K', 'D'),
  951. const_MODE = mk_const4('M', 'O', 'D', 'E'),
  952. const_NLST = mk_const4('N', 'L', 'S', 'T'),
  953. const_NOOP = mk_const4('N', 'O', 'O', 'P'),
  954. const_PASS = mk_const4('P', 'A', 'S', 'S'),
  955. const_PASV = mk_const4('P', 'A', 'S', 'V'),
  956. const_PORT = mk_const4('P', 'O', 'R', 'T'),
  957. const_PWD = mk_const3('P', 'W', 'D'),
  958. const_QUIT = mk_const4('Q', 'U', 'I', 'T'),
  959. const_REST = mk_const4('R', 'E', 'S', 'T'),
  960. const_RETR = mk_const4('R', 'E', 'T', 'R'),
  961. const_RMD = mk_const3('R', 'M', 'D'),
  962. const_RNFR = mk_const4('R', 'N', 'F', 'R'),
  963. const_RNTO = mk_const4('R', 'N', 'T', 'O'),
  964. const_SIZE = mk_const4('S', 'I', 'Z', 'E'),
  965. const_STAT = mk_const4('S', 'T', 'A', 'T'),
  966. const_STOR = mk_const4('S', 'T', 'O', 'R'),
  967. const_STOU = mk_const4('S', 'T', 'O', 'U'),
  968. const_STRU = mk_const4('S', 'T', 'R', 'U'),
  969. const_SYST = mk_const4('S', 'Y', 'S', 'T'),
  970. const_TYPE = mk_const4('T', 'Y', 'P', 'E'),
  971. const_USER = mk_const4('U', 'S', 'E', 'R'),
  972. #if !BB_MMU
  973. OPT_l = (1 << 0),
  974. OPT_1 = (1 << 1),
  975. #endif
  976. OPT_v = (1 << ((!BB_MMU) * 2 + 0)),
  977. OPT_S = (1 << ((!BB_MMU) * 2 + 1)),
  978. OPT_w = (1 << ((!BB_MMU) * 2 + 2)) * ENABLE_FEATURE_FTP_WRITE,
  979. };
  980. int ftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  981. #if !BB_MMU
  982. int ftpd_main(int argc, char **argv)
  983. #else
  984. int ftpd_main(int argc UNUSED_PARAM, char **argv)
  985. #endif
  986. {
  987. unsigned abs_timeout;
  988. unsigned verbose_S;
  989. smallint opts;
  990. INIT_G();
  991. abs_timeout = 1 * 60 * 60;
  992. verbose_S = 0;
  993. G.timeout = 2 * 60;
  994. opt_complementary = "t+:T+:vv:SS";
  995. #if BB_MMU
  996. opts = getopt32(argv, "vS" IF_FEATURE_FTP_WRITE("w") "t:T:", &G.timeout, &abs_timeout, &G.verbose, &verbose_S);
  997. #else
  998. opts = getopt32(argv, "l1vS" IF_FEATURE_FTP_WRITE("w") "t:T:", &G.timeout, &abs_timeout, &G.verbose, &verbose_S);
  999. if (opts & (OPT_l|OPT_1)) {
  1000. /* Our secret backdoor to ls */
  1001. /* TODO: pass -n? It prevents user/group resolution, which may not work in chroot anyway */
  1002. /* TODO: pass -A? It shows dot files */
  1003. /* TODO: pass --group-directories-first? would be nice, but ls doesn't do that yet */
  1004. xchdir(argv[2]);
  1005. argv[2] = (char*)"--";
  1006. /* memset(&G, 0, sizeof(G)); - ls_main does it */
  1007. return ls_main(argc, argv);
  1008. }
  1009. #endif
  1010. if (G.verbose < verbose_S)
  1011. G.verbose = verbose_S;
  1012. if (abs_timeout | G.timeout) {
  1013. if (abs_timeout == 0)
  1014. abs_timeout = INT_MAX;
  1015. G.end_time = monotonic_sec() + abs_timeout;
  1016. if (G.timeout > abs_timeout)
  1017. G.timeout = abs_timeout;
  1018. }
  1019. strcpy(G.msg_ok + 4, MSG_OK );
  1020. strcpy(G.msg_err + 4, MSG_ERR);
  1021. G.local_addr = get_sock_lsa(STDIN_FILENO);
  1022. if (!G.local_addr) {
  1023. /* This is confusing:
  1024. * bb_error_msg_and_die("stdin is not a socket");
  1025. * Better: */
  1026. bb_show_usage();
  1027. /* Help text says that ftpd must be used as inetd service,
  1028. * which is by far the most usual cause of get_sock_lsa
  1029. * failure */
  1030. }
  1031. if (!(opts & OPT_v))
  1032. logmode = LOGMODE_NONE;
  1033. if (opts & OPT_S) {
  1034. /* LOG_NDELAY is needed since we may chroot later */
  1035. openlog(applet_name, LOG_PID | LOG_NDELAY, LOG_DAEMON);
  1036. logmode |= LOGMODE_SYSLOG;
  1037. }
  1038. if (logmode)
  1039. applet_name = xasprintf("%s[%u]", applet_name, (int)getpid());
  1040. #if !BB_MMU
  1041. G.root_fd = xopen("/", O_RDONLY | O_DIRECTORY);
  1042. close_on_exec_on(G.root_fd);
  1043. #endif
  1044. if (argv[optind]) {
  1045. xchroot(argv[optind]);
  1046. }
  1047. //umask(077); - admin can set umask before starting us
  1048. /* Signals. We'll always take -EPIPE rather than a rude signal, thanks */
  1049. signal(SIGPIPE, SIG_IGN);
  1050. /* Set up options on the command socket (do we need these all? why?) */
  1051. setsockopt(STDIN_FILENO, IPPROTO_TCP, TCP_NODELAY, &const_int_1, sizeof(const_int_1));
  1052. setsockopt(STDIN_FILENO, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
  1053. /* Telnet protocol over command link may send "urgent" data,
  1054. * we prefer it to be received in the "normal" data stream: */
  1055. setsockopt(STDIN_FILENO, SOL_SOCKET, SO_OOBINLINE, &const_int_1, sizeof(const_int_1));
  1056. WRITE_OK(FTP_GREET);
  1057. signal(SIGALRM, timeout_handler);
  1058. #ifdef IF_WE_WANT_TO_REQUIRE_LOGIN
  1059. {
  1060. smallint user_was_specified = 0;
  1061. while (1) {
  1062. uint32_t cmdval = cmdio_get_cmd_and_arg();
  1063. if (cmdval == const_USER) {
  1064. if (G.ftp_arg == NULL || strcasecmp(G.ftp_arg, "anonymous") != 0)
  1065. cmdio_write_raw(STR(FTP_LOGINERR)" Server is anonymous only\r\n");
  1066. else {
  1067. user_was_specified = 1;
  1068. cmdio_write_raw(STR(FTP_GIVEPWORD)" Please specify the password\r\n");
  1069. }
  1070. } else if (cmdval == const_PASS) {
  1071. if (user_was_specified)
  1072. break;
  1073. cmdio_write_raw(STR(FTP_NEEDUSER)" Login with USER\r\n");
  1074. } else if (cmdval == const_QUIT) {
  1075. WRITE_OK(FTP_GOODBYE);
  1076. return 0;
  1077. } else {
  1078. cmdio_write_raw(STR(FTP_LOGINERR)" Login with USER and PASS\r\n");
  1079. }
  1080. }
  1081. }
  1082. WRITE_OK(FTP_LOGINOK);
  1083. #endif
  1084. /* RFC-959 Section 5.1
  1085. * The following commands and options MUST be supported by every
  1086. * server-FTP and user-FTP, except in cases where the underlying
  1087. * file system or operating system does not allow or support
  1088. * a particular command.
  1089. * Type: ASCII Non-print, IMAGE, LOCAL 8
  1090. * Mode: Stream
  1091. * Structure: File, Record*
  1092. * (Record structure is REQUIRED only for hosts whose file
  1093. * systems support record structure).
  1094. * Commands:
  1095. * USER, PASS, ACCT, [bbox: ACCT not supported]
  1096. * PORT, PASV,
  1097. * TYPE, MODE, STRU,
  1098. * RETR, STOR, APPE,
  1099. * RNFR, RNTO, DELE,
  1100. * CWD, CDUP, RMD, MKD, PWD,
  1101. * LIST, NLST,
  1102. * SYST, STAT,
  1103. * HELP, NOOP, QUIT.
  1104. */
  1105. /* ACCOUNT (ACCT)
  1106. * "The argument field is a Telnet string identifying the user's account.
  1107. * The command is not necessarily related to the USER command, as some
  1108. * sites may require an account for login and others only for specific
  1109. * access, such as storing files. In the latter case the command may
  1110. * arrive at any time.
  1111. * There are reply codes to differentiate these cases for the automation:
  1112. * when account information is required for login, the response to
  1113. * a successful PASSword command is reply code 332. On the other hand,
  1114. * if account information is NOT required for login, the reply to
  1115. * a successful PASSword command is 230; and if the account information
  1116. * is needed for a command issued later in the dialogue, the server
  1117. * should return a 332 or 532 reply depending on whether it stores
  1118. * (pending receipt of the ACCounT command) or discards the command,
  1119. * respectively."
  1120. */
  1121. while (1) {
  1122. uint32_t cmdval = cmdio_get_cmd_and_arg();
  1123. if (cmdval == const_QUIT) {
  1124. WRITE_OK(FTP_GOODBYE);
  1125. return 0;
  1126. }
  1127. else if (cmdval == const_USER)
  1128. /* This would mean "ok, now give me PASS". */
  1129. /*WRITE_OK(FTP_GIVEPWORD);*/
  1130. /* vsftpd can be configured to not require that,
  1131. * and this also saves one roundtrip:
  1132. */
  1133. WRITE_OK(FTP_LOGINOK);
  1134. else if (cmdval == const_PASS)
  1135. WRITE_OK(FTP_LOGINOK);
  1136. else if (cmdval == const_NOOP)
  1137. WRITE_OK(FTP_NOOPOK);
  1138. else if (cmdval == const_TYPE)
  1139. WRITE_OK(FTP_TYPEOK);
  1140. else if (cmdval == const_STRU)
  1141. WRITE_OK(FTP_STRUOK);
  1142. else if (cmdval == const_MODE)
  1143. WRITE_OK(FTP_MODEOK);
  1144. else if (cmdval == const_ALLO)
  1145. WRITE_OK(FTP_ALLOOK);
  1146. else if (cmdval == const_SYST)
  1147. cmdio_write_raw(STR(FTP_SYSTOK)" UNIX Type: L8\r\n");
  1148. else if (cmdval == const_PWD)
  1149. handle_pwd();
  1150. else if (cmdval == const_CWD)
  1151. handle_cwd();
  1152. else if (cmdval == const_CDUP) /* cd .. */
  1153. handle_cdup();
  1154. /* HELP is nearly useless, but we can reuse FEAT for it */
  1155. /* lftp uses FEAT */
  1156. else if (cmdval == const_HELP || cmdval == const_FEAT)
  1157. handle_feat(cmdval == const_HELP
  1158. ? STRNUM32(FTP_HELP)
  1159. : STRNUM32(FTP_STATOK)
  1160. );
  1161. else if (cmdval == const_LIST) /* ls -l */
  1162. handle_list();
  1163. else if (cmdval == const_NLST) /* "name list", bare ls */
  1164. handle_nlst();
  1165. /* SIZE is crucial for wget's download indicator etc */
  1166. /* Mozilla, lftp use MDTM (presumably for caching) */
  1167. else if (cmdval == const_SIZE || cmdval == const_MDTM)
  1168. handle_size_or_mdtm(cmdval == const_SIZE);
  1169. else if (cmdval == const_STAT) {
  1170. if (G.ftp_arg == NULL)
  1171. handle_stat();
  1172. else
  1173. handle_stat_file();
  1174. }
  1175. else if (cmdval == const_PASV)
  1176. handle_pasv();
  1177. else if (cmdval == const_EPSV)
  1178. handle_epsv();
  1179. else if (cmdval == const_RETR)
  1180. handle_retr();
  1181. else if (cmdval == const_PORT)
  1182. handle_port();
  1183. else if (cmdval == const_REST)
  1184. handle_rest();
  1185. #if ENABLE_FEATURE_FTP_WRITE
  1186. else if (opts & OPT_w) {
  1187. if (cmdval == const_STOR)
  1188. handle_stor();
  1189. else if (cmdval == const_MKD)
  1190. handle_mkd();
  1191. else if (cmdval == const_RMD)
  1192. handle_rmd();
  1193. else if (cmdval == const_DELE)
  1194. handle_dele();
  1195. else if (cmdval == const_RNFR) /* "rename from" */
  1196. handle_rnfr();
  1197. else if (cmdval == const_RNTO) /* "rename to" */
  1198. handle_rnto();
  1199. else if (cmdval == const_APPE)
  1200. handle_appe();
  1201. else if (cmdval == const_STOU) /* "store unique" */
  1202. handle_stou();
  1203. else
  1204. goto bad_cmd;
  1205. }
  1206. #endif
  1207. #if 0
  1208. else if (cmdval == const_STOR
  1209. || cmdval == const_MKD
  1210. || cmdval == const_RMD
  1211. || cmdval == const_DELE
  1212. || cmdval == const_RNFR
  1213. || cmdval == const_RNTO
  1214. || cmdval == const_APPE
  1215. || cmdval == const_STOU
  1216. ) {
  1217. cmdio_write_raw(STR(FTP_NOPERM)" Permission denied\r\n");
  1218. }
  1219. #endif
  1220. else {
  1221. /* Which unsupported commands were seen in the wild?
  1222. * (doesn't necessarily mean "we must support them")
  1223. * foo 1.2.3: XXXX - comment
  1224. */
  1225. #if ENABLE_FEATURE_FTP_WRITE
  1226. bad_cmd:
  1227. #endif
  1228. cmdio_write_raw(STR(FTP_BADCMD)" Unknown command\r\n");
  1229. }
  1230. }
  1231. }