ftpd.c 34 KB

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