3
0

ftpd.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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_keepalive(remote_fd);
  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; /* "-lA" or "-1A" */
  540. argv[2] = "--";
  541. argv[3] = G.ftp_arg;
  542. argv[4] = NULL;
  543. /* Improve compatibility with non-RFC conforming FTP clients
  544. * which send e.g. "LIST -l", "LIST -la", "LIST -aL".
  545. * See https://bugs.kde.org/show_bug.cgi?id=195578 */
  546. if (ENABLE_FEATURE_FTPD_ACCEPT_BROKEN_LIST
  547. && G.ftp_arg && G.ftp_arg[0] == '-'
  548. ) {
  549. const char *tmp = strchr(G.ftp_arg, ' ');
  550. if (tmp) /* skip the space */
  551. tmp++;
  552. argv[3] = tmp;
  553. }
  554. xpiped_pair(outfd);
  555. /*fflush_all(); - so far we dont use stdio on output */
  556. pid = BB_MMU ? xfork() : xvfork();
  557. if (pid == 0) {
  558. #if !BB_MMU
  559. int cur_fd;
  560. #endif
  561. /* child */
  562. /* NB: close _first_, then move fd! */
  563. close(outfd.rd);
  564. xmove_fd(outfd.wr, STDOUT_FILENO);
  565. /* Opening /dev/null in chroot is hard.
  566. * Just making sure STDIN_FILENO is opened
  567. * to something harmless. Paranoia,
  568. * ls won't read it anyway */
  569. close(STDIN_FILENO);
  570. dup(STDOUT_FILENO); /* copy will become STDIN_FILENO */
  571. #if BB_MMU
  572. /* memset(&G, 0, sizeof(G)); - ls_main does it */
  573. exit(ls_main(ARRAY_SIZE(argv) - 1, (char**) argv));
  574. #else
  575. cur_fd = xopen(".", O_RDONLY | O_DIRECTORY);
  576. /* On NOMMU, we want to execute a child - copy of ourself
  577. * in order to unblock parent after vfork.
  578. * In chroot we usually can't re-exec. Thus we escape
  579. * out of the chroot back to original root.
  580. */
  581. if (G.root_fd >= 0) {
  582. if (fchdir(G.root_fd) != 0 || chroot(".") != 0)
  583. _exit(127);
  584. /*close(G.root_fd); - close_on_exec_on() took care of this */
  585. }
  586. /* Child expects directory to list on fd #3 */
  587. xmove_fd(cur_fd, 3);
  588. execv(bb_busybox_exec_path, (char**) argv);
  589. _exit(127);
  590. #endif
  591. }
  592. /* parent */
  593. close(outfd.wr);
  594. return outfd.rd;
  595. }
  596. enum {
  597. USE_CTRL_CONN = 1,
  598. LONG_LISTING = 2,
  599. };
  600. static void
  601. handle_dir_common(int opts)
  602. {
  603. FILE *ls_fp;
  604. char *line;
  605. int ls_fd;
  606. if (!(opts & USE_CTRL_CONN) && !port_or_pasv_was_seen())
  607. return; /* port_or_pasv_was_seen emitted error response */
  608. ls_fd = popen_ls((opts & LONG_LISTING) ? "-lA" : "-1A");
  609. ls_fp = xfdopen_for_read(ls_fd);
  610. /* FIXME: filenames with embedded newlines are mishandled */
  611. if (opts & USE_CTRL_CONN) {
  612. /* STAT <filename> */
  613. cmdio_write_raw(STR(FTP_STATFILE_OK)"-File status:\r\n");
  614. while (1) {
  615. line = xmalloc_fgetline(ls_fp);
  616. if (!line)
  617. break;
  618. /* Hack: 0 results in no status at all */
  619. /* Note: it's ok that we don't prepend space,
  620. * ftp.kernel.org doesn't do that too */
  621. cmdio_write(0, line);
  622. free(line);
  623. }
  624. WRITE_OK(FTP_STATFILE_OK);
  625. } else {
  626. /* LIST/NLST [<filename>] */
  627. int remote_fd = get_remote_transfer_fd(" Directory listing");
  628. if (remote_fd >= 0) {
  629. while (1) {
  630. unsigned len;
  631. line = xmalloc_fgets(ls_fp);
  632. if (!line)
  633. break;
  634. /* I've seen clients complaining when they
  635. * are fed with ls output with bare '\n'.
  636. * Replace trailing "\n\0" with "\r\n".
  637. */
  638. len = strlen(line);
  639. if (len != 0) /* paranoia check */
  640. line[len - 1] = '\r';
  641. line[len] = '\n';
  642. xwrite(remote_fd, line, len + 1);
  643. free(line);
  644. }
  645. }
  646. close(remote_fd);
  647. WRITE_OK(FTP_TRANSFEROK);
  648. }
  649. fclose(ls_fp); /* closes ls_fd too */
  650. }
  651. static void
  652. handle_list(void)
  653. {
  654. handle_dir_common(LONG_LISTING);
  655. }
  656. static void
  657. handle_nlst(void)
  658. {
  659. /* NLST returns list of names, "\r\n" terminated without regard
  660. * to the current binary flag. Names may start with "/",
  661. * then they represent full names (we don't produce such names),
  662. * otherwise names are relative to current directory.
  663. * Embedded "\n" are replaced by NULs. This is safe since names
  664. * can never contain NUL.
  665. */
  666. handle_dir_common(0);
  667. }
  668. static void
  669. handle_stat_file(void)
  670. {
  671. handle_dir_common(LONG_LISTING + USE_CTRL_CONN);
  672. }
  673. /* This can be extended to handle MLST, as all info is available
  674. * in struct stat for that:
  675. * MLST file_name
  676. * 250-Listing file_name
  677. * type=file;size=4161;modify=19970214165800; /dir/dir/file_name
  678. * 250 End
  679. * Nano-doc:
  680. * MLST [<file or dir name, "." assumed if not given>]
  681. * Returned name should be either the same as requested, or fully qualified.
  682. * If there was no parameter, return "" or (preferred) fully-qualified name.
  683. * Returned "facts" (case is not important):
  684. * size - size in octets
  685. * modify - last modification time
  686. * type - entry type (file,dir,OS.unix=block)
  687. * (+ cdir and pdir types for MLSD)
  688. * unique - unique id of file/directory (inode#)
  689. * perm -
  690. * a: can be appended to (APPE)
  691. * d: can be deleted (RMD/DELE)
  692. * f: can be renamed (RNFR)
  693. * r: can be read (RETR)
  694. * w: can be written (STOR)
  695. * e: can CWD into this dir
  696. * l: this dir can be listed (dir only!)
  697. * c: can create files in this dir
  698. * m: can create dirs in this dir (MKD)
  699. * p: can delete files in this dir
  700. * UNIX.mode - unix file mode
  701. */
  702. static void
  703. handle_size_or_mdtm(int need_size)
  704. {
  705. struct stat statbuf;
  706. struct tm broken_out;
  707. char buf[(sizeof("NNN %"OFF_FMT"u\r\n") + sizeof(off_t) * 3)
  708. | sizeof("NNN YYYYMMDDhhmmss\r\n")
  709. ];
  710. if (!G.ftp_arg
  711. || stat(G.ftp_arg, &statbuf) != 0
  712. || !S_ISREG(statbuf.st_mode)
  713. ) {
  714. WRITE_ERR(FTP_FILEFAIL);
  715. return;
  716. }
  717. if (need_size) {
  718. sprintf(buf, STR(FTP_STATFILE_OK)" %"OFF_FMT"u\r\n", statbuf.st_size);
  719. } else {
  720. gmtime_r(&statbuf.st_mtime, &broken_out);
  721. sprintf(buf, STR(FTP_STATFILE_OK)" %04u%02u%02u%02u%02u%02u\r\n",
  722. broken_out.tm_year + 1900,
  723. broken_out.tm_mon + 1,
  724. broken_out.tm_mday,
  725. broken_out.tm_hour,
  726. broken_out.tm_min,
  727. broken_out.tm_sec);
  728. }
  729. cmdio_write_raw(buf);
  730. }
  731. /* Upload commands */
  732. #if ENABLE_FEATURE_FTP_WRITE
  733. static void
  734. handle_mkd(void)
  735. {
  736. if (!G.ftp_arg || mkdir(G.ftp_arg, 0777) != 0) {
  737. WRITE_ERR(FTP_FILEFAIL);
  738. return;
  739. }
  740. WRITE_OK(FTP_MKDIROK);
  741. }
  742. static void
  743. handle_rmd(void)
  744. {
  745. if (!G.ftp_arg || rmdir(G.ftp_arg) != 0) {
  746. WRITE_ERR(FTP_FILEFAIL);
  747. return;
  748. }
  749. WRITE_OK(FTP_RMDIROK);
  750. }
  751. static void
  752. handle_dele(void)
  753. {
  754. if (!G.ftp_arg || unlink(G.ftp_arg) != 0) {
  755. WRITE_ERR(FTP_FILEFAIL);
  756. return;
  757. }
  758. WRITE_OK(FTP_DELEOK);
  759. }
  760. static void
  761. handle_rnfr(void)
  762. {
  763. free(G.rnfr_filename);
  764. G.rnfr_filename = xstrdup(G.ftp_arg);
  765. WRITE_OK(FTP_RNFROK);
  766. }
  767. static void
  768. handle_rnto(void)
  769. {
  770. int retval;
  771. /* If we didn't get a RNFR, throw a wobbly */
  772. if (G.rnfr_filename == NULL || G.ftp_arg == NULL) {
  773. cmdio_write_raw(STR(FTP_NEEDRNFR)" Use RNFR first\r\n");
  774. return;
  775. }
  776. retval = rename(G.rnfr_filename, G.ftp_arg);
  777. free(G.rnfr_filename);
  778. G.rnfr_filename = NULL;
  779. if (retval) {
  780. WRITE_ERR(FTP_FILEFAIL);
  781. return;
  782. }
  783. WRITE_OK(FTP_RENAMEOK);
  784. }
  785. static void
  786. handle_upload_common(int is_append, int is_unique)
  787. {
  788. struct stat statbuf;
  789. char *tempname;
  790. off_t bytes_transferred;
  791. off_t offset;
  792. int local_file_fd;
  793. int remote_fd;
  794. offset = G.restart_pos;
  795. G.restart_pos = 0;
  796. if (!port_or_pasv_was_seen())
  797. return; /* port_or_pasv_was_seen emitted error response */
  798. tempname = NULL;
  799. local_file_fd = -1;
  800. if (is_unique) {
  801. tempname = xstrdup(" FILE: uniq.XXXXXX");
  802. local_file_fd = mkstemp(tempname + 7);
  803. } else if (G.ftp_arg) {
  804. int flags = O_WRONLY | O_CREAT | O_TRUNC;
  805. if (is_append)
  806. flags = O_WRONLY | O_CREAT | O_APPEND;
  807. if (offset)
  808. flags = O_WRONLY | O_CREAT;
  809. local_file_fd = open(G.ftp_arg, flags, 0666);
  810. }
  811. if (local_file_fd < 0
  812. || fstat(local_file_fd, &statbuf) != 0
  813. || !S_ISREG(statbuf.st_mode)
  814. ) {
  815. free(tempname);
  816. WRITE_ERR(FTP_UPLOADFAIL);
  817. if (local_file_fd >= 0)
  818. goto close_local_and_bail;
  819. return;
  820. }
  821. G.local_file_fd = local_file_fd;
  822. if (offset)
  823. xlseek(local_file_fd, offset, SEEK_SET);
  824. remote_fd = get_remote_transfer_fd(tempname ? tempname : " Ok to send data");
  825. free(tempname);
  826. if (remote_fd < 0)
  827. goto close_local_and_bail;
  828. bytes_transferred = bb_copyfd_eof(remote_fd, local_file_fd);
  829. close(remote_fd);
  830. if (bytes_transferred < 0)
  831. WRITE_ERR(FTP_BADSENDFILE);
  832. else
  833. WRITE_OK(FTP_TRANSFEROK);
  834. close_local_and_bail:
  835. close(local_file_fd);
  836. G.local_file_fd = 0;
  837. }
  838. static void
  839. handle_stor(void)
  840. {
  841. handle_upload_common(0, 0);
  842. }
  843. static void
  844. handle_appe(void)
  845. {
  846. G.restart_pos = 0;
  847. handle_upload_common(1, 0);
  848. }
  849. static void
  850. handle_stou(void)
  851. {
  852. G.restart_pos = 0;
  853. handle_upload_common(0, 1);
  854. }
  855. #endif /* ENABLE_FEATURE_FTP_WRITE */
  856. static uint32_t
  857. cmdio_get_cmd_and_arg(void)
  858. {
  859. int len;
  860. uint32_t cmdval;
  861. char *cmd;
  862. alarm(G.timeout);
  863. free(G.ftp_cmd);
  864. {
  865. /* Paranoia. Peer may send 1 gigabyte long cmd... */
  866. /* Using separate len_on_stk instead of len optimizes
  867. * code size (allows len to be in CPU register) */
  868. size_t len_on_stk = 8 * 1024;
  869. G.ftp_cmd = cmd = xmalloc_fgets_str_len(stdin, "\r\n", &len_on_stk);
  870. if (!cmd)
  871. exit(0);
  872. len = len_on_stk;
  873. }
  874. /* De-escape telnet: 0xff,0xff => 0xff */
  875. /* RFC959 says that ABOR, STAT, QUIT may be sent even during
  876. * data transfer, and may be preceded by telnet's "Interrupt Process"
  877. * code (two-byte sequence 255,244) and then by telnet "Synch" code
  878. * 255,242 (byte 242 is sent with TCP URG bit using send(MSG_OOB)
  879. * and may generate SIGURG on our side. See RFC854).
  880. * So far we don't support that (may install SIGURG handler if we'd want to),
  881. * but we need to at least remove 255,xxx pairs. lftp sends those. */
  882. /* Then de-escape FTP: NUL => '\n' */
  883. /* Testing for \xff:
  884. * Create file named '\xff': echo Hello >`echo -ne "\xff"`
  885. * Try to get it: ftpget -v 127.0.0.1 Eff `echo -ne "\xff\xff"`
  886. * (need "\xff\xff" until ftpget applet is fixed to do escaping :)
  887. * Testing for embedded LF:
  888. * LF_HERE=`echo -ne "LF\nHERE"`
  889. * echo Hello >"$LF_HERE"
  890. * ftpget -v 127.0.0.1 LF_HERE "$LF_HERE"
  891. */
  892. {
  893. int dst, src;
  894. /* Strip "\r\n" if it is there */
  895. if (len != 0 && cmd[len - 1] == '\n') {
  896. len--;
  897. if (len != 0 && cmd[len - 1] == '\r')
  898. len--;
  899. cmd[len] = '\0';
  900. }
  901. src = strchrnul(cmd, 0xff) - cmd;
  902. /* 99,99% there are neither NULs nor 255s and src == len */
  903. if (src < len) {
  904. dst = src;
  905. do {
  906. if ((unsigned char)(cmd[src]) == 255) {
  907. src++;
  908. /* 255,xxx - skip 255 */
  909. if ((unsigned char)(cmd[src]) != 255) {
  910. /* 255,!255 - skip both */
  911. src++;
  912. continue;
  913. }
  914. /* 255,255 - retain one 255 */
  915. }
  916. /* NUL => '\n' */
  917. cmd[dst++] = cmd[src] ? cmd[src] : '\n';
  918. src++;
  919. } while (src < len);
  920. cmd[dst] = '\0';
  921. }
  922. }
  923. if (G.verbose > 1)
  924. verbose_log(cmd);
  925. G.ftp_arg = strchr(cmd, ' ');
  926. if (G.ftp_arg != NULL)
  927. *G.ftp_arg++ = '\0';
  928. /* Uppercase and pack into uint32_t first word of the command */
  929. cmdval = 0;
  930. while (*cmd)
  931. cmdval = (cmdval << 8) + ((unsigned char)*cmd++ & (unsigned char)~0x20);
  932. return cmdval;
  933. }
  934. #define mk_const4(a,b,c,d) (((a * 0x100 + b) * 0x100 + c) * 0x100 + d)
  935. #define mk_const3(a,b,c) ((a * 0x100 + b) * 0x100 + c)
  936. enum {
  937. const_ALLO = mk_const4('A', 'L', 'L', 'O'),
  938. const_APPE = mk_const4('A', 'P', 'P', 'E'),
  939. const_CDUP = mk_const4('C', 'D', 'U', 'P'),
  940. const_CWD = mk_const3('C', 'W', 'D'),
  941. const_DELE = mk_const4('D', 'E', 'L', 'E'),
  942. const_EPSV = mk_const4('E', 'P', 'S', 'V'),
  943. const_FEAT = mk_const4('F', 'E', 'A', 'T'),
  944. const_HELP = mk_const4('H', 'E', 'L', 'P'),
  945. const_LIST = mk_const4('L', 'I', 'S', 'T'),
  946. const_MDTM = mk_const4('M', 'D', 'T', 'M'),
  947. const_MKD = mk_const3('M', 'K', 'D'),
  948. const_MODE = mk_const4('M', 'O', 'D', 'E'),
  949. const_NLST = mk_const4('N', 'L', 'S', 'T'),
  950. const_NOOP = mk_const4('N', 'O', 'O', 'P'),
  951. const_PASS = mk_const4('P', 'A', 'S', 'S'),
  952. const_PASV = mk_const4('P', 'A', 'S', 'V'),
  953. const_PORT = mk_const4('P', 'O', 'R', 'T'),
  954. const_PWD = mk_const3('P', 'W', 'D'),
  955. /* Same as PWD. Reportedly used by windows ftp client */
  956. const_XPWD = mk_const4('X', 'P', 'W', 'D'),
  957. const_QUIT = mk_const4('Q', 'U', 'I', 'T'),
  958. const_REST = mk_const4('R', 'E', 'S', 'T'),
  959. const_RETR = mk_const4('R', 'E', 'T', 'R'),
  960. const_RMD = mk_const3('R', 'M', 'D'),
  961. const_RNFR = mk_const4('R', 'N', 'F', 'R'),
  962. const_RNTO = mk_const4('R', 'N', 'T', 'O'),
  963. const_SIZE = mk_const4('S', 'I', 'Z', 'E'),
  964. const_STAT = mk_const4('S', 'T', 'A', 'T'),
  965. const_STOR = mk_const4('S', 'T', 'O', 'R'),
  966. const_STOU = mk_const4('S', 'T', 'O', 'U'),
  967. const_STRU = mk_const4('S', 'T', 'R', 'U'),
  968. const_SYST = mk_const4('S', 'Y', 'S', 'T'),
  969. const_TYPE = mk_const4('T', 'Y', 'P', 'E'),
  970. const_USER = mk_const4('U', 'S', 'E', 'R'),
  971. #if !BB_MMU
  972. OPT_l = (1 << 0),
  973. OPT_1 = (1 << 1),
  974. OPT_A = (1 << 2),
  975. #endif
  976. OPT_v = (1 << ((!BB_MMU) * 3 + 0)),
  977. OPT_S = (1 << ((!BB_MMU) * 3 + 1)),
  978. OPT_w = (1 << ((!BB_MMU) * 3 + 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. #if ENABLE_FEATURE_FTP_AUTHENTICATION
  988. struct passwd *pw = NULL;
  989. #endif
  990. unsigned abs_timeout;
  991. unsigned verbose_S;
  992. smallint opts;
  993. INIT_G();
  994. abs_timeout = 1 * 60 * 60;
  995. verbose_S = 0;
  996. G.timeout = 2 * 60;
  997. opt_complementary = "t+:T+:vv:SS";
  998. #if BB_MMU
  999. opts = getopt32(argv, "vS" IF_FEATURE_FTP_WRITE("w") "t:T:", &G.timeout, &abs_timeout, &G.verbose, &verbose_S);
  1000. #else
  1001. opts = getopt32(argv, "l1AvS" IF_FEATURE_FTP_WRITE("w") "t:T:", &G.timeout, &abs_timeout, &G.verbose, &verbose_S);
  1002. if (opts & (OPT_l|OPT_1)) {
  1003. /* Our secret backdoor to ls */
  1004. /* TODO: pass --group-directories-first? would be nice, but ls doesn't do that yet */
  1005. if (fchdir(3) != 0)
  1006. _exit(127);
  1007. /* memset(&G, 0, sizeof(G)); - ls_main does it */
  1008. return ls_main(argc, argv);
  1009. }
  1010. #endif
  1011. if (G.verbose < verbose_S)
  1012. G.verbose = verbose_S;
  1013. if (abs_timeout | G.timeout) {
  1014. if (abs_timeout == 0)
  1015. abs_timeout = INT_MAX;
  1016. G.end_time = monotonic_sec() + abs_timeout;
  1017. if (G.timeout > abs_timeout)
  1018. G.timeout = abs_timeout;
  1019. }
  1020. strcpy(G.msg_ok + 4, MSG_OK );
  1021. strcpy(G.msg_err + 4, MSG_ERR);
  1022. G.local_addr = get_sock_lsa(STDIN_FILENO);
  1023. if (!G.local_addr) {
  1024. /* This is confusing:
  1025. * bb_error_msg_and_die("stdin is not a socket");
  1026. * Better: */
  1027. bb_show_usage();
  1028. /* Help text says that ftpd must be used as inetd service,
  1029. * which is by far the most usual cause of get_sock_lsa
  1030. * failure */
  1031. }
  1032. if (!(opts & OPT_v))
  1033. logmode = LOGMODE_NONE;
  1034. if (opts & OPT_S) {
  1035. /* LOG_NDELAY is needed since we may chroot later */
  1036. openlog(applet_name, LOG_PID | LOG_NDELAY, LOG_DAEMON);
  1037. logmode |= LOGMODE_SYSLOG;
  1038. }
  1039. if (logmode)
  1040. applet_name = xasprintf("%s[%u]", applet_name, (int)getpid());
  1041. //umask(077); - admin can set umask before starting us
  1042. /* Signals */
  1043. bb_signals(0
  1044. /* We'll always take EPIPE rather than a rude signal, thanks */
  1045. + (1 << SIGPIPE)
  1046. /* LIST command spawns chilren. Prevent zombies */
  1047. + (1 << SIGCHLD)
  1048. , SIG_IGN);
  1049. /* Set up options on the command socket (do we need these all? why?) */
  1050. setsockopt_1(STDIN_FILENO, IPPROTO_TCP, TCP_NODELAY);
  1051. setsockopt_keepalive(STDIN_FILENO);
  1052. /* Telnet protocol over command link may send "urgent" data,
  1053. * we prefer it to be received in the "normal" data stream: */
  1054. setsockopt_1(STDIN_FILENO, SOL_SOCKET, SO_OOBINLINE);
  1055. WRITE_OK(FTP_GREET);
  1056. signal(SIGALRM, timeout_handler);
  1057. #if ENABLE_FEATURE_FTP_AUTHENTICATION
  1058. while (1) {
  1059. uint32_t cmdval = cmdio_get_cmd_and_arg();
  1060. if (cmdval == const_USER) {
  1061. pw = getpwnam(G.ftp_arg);
  1062. cmdio_write_raw(STR(FTP_GIVEPWORD)" Please specify password\r\n");
  1063. } else if (cmdval == const_PASS) {
  1064. if (check_password(pw, G.ftp_arg) > 0) {
  1065. break; /* login success */
  1066. }
  1067. cmdio_write_raw(STR(FTP_LOGINERR)" Login failed\r\n");
  1068. pw = NULL;
  1069. } else if (cmdval == const_QUIT) {
  1070. WRITE_OK(FTP_GOODBYE);
  1071. return 0;
  1072. } else {
  1073. cmdio_write_raw(STR(FTP_LOGINERR)" Login with USER and PASS\r\n");
  1074. }
  1075. }
  1076. WRITE_OK(FTP_LOGINOK);
  1077. #endif
  1078. /* Do this after auth, else /etc/passwd is not accessible */
  1079. #if !BB_MMU
  1080. G.root_fd = -1;
  1081. #endif
  1082. argv += optind;
  1083. if (argv[0]) {
  1084. const char *basedir = argv[0];
  1085. #if !BB_MMU
  1086. G.root_fd = xopen("/", O_RDONLY | O_DIRECTORY);
  1087. close_on_exec_on(G.root_fd);
  1088. #endif
  1089. if (chroot(basedir) == 0)
  1090. basedir = "/";
  1091. #if !BB_MMU
  1092. else {
  1093. close(G.root_fd);
  1094. G.root_fd = -1;
  1095. }
  1096. #endif
  1097. /*
  1098. * If chroot failed, assume that we aren't root,
  1099. * and at least chdir to the specified DIR
  1100. * (older versions were dying with error message).
  1101. * If chroot worked, move current dir to new "/":
  1102. */
  1103. xchdir(basedir);
  1104. }
  1105. #if ENABLE_FEATURE_FTP_AUTHENTICATION
  1106. change_identity(pw);
  1107. #endif
  1108. /* RFC-959 Section 5.1
  1109. * The following commands and options MUST be supported by every
  1110. * server-FTP and user-FTP, except in cases where the underlying
  1111. * file system or operating system does not allow or support
  1112. * a particular command.
  1113. * Type: ASCII Non-print, IMAGE, LOCAL 8
  1114. * Mode: Stream
  1115. * Structure: File, Record*
  1116. * (Record structure is REQUIRED only for hosts whose file
  1117. * systems support record structure).
  1118. * Commands:
  1119. * USER, PASS, ACCT, [bbox: ACCT not supported]
  1120. * PORT, PASV,
  1121. * TYPE, MODE, STRU,
  1122. * RETR, STOR, APPE,
  1123. * RNFR, RNTO, DELE,
  1124. * CWD, CDUP, RMD, MKD, PWD,
  1125. * LIST, NLST,
  1126. * SYST, STAT,
  1127. * HELP, NOOP, QUIT.
  1128. */
  1129. /* ACCOUNT (ACCT)
  1130. * "The argument field is a Telnet string identifying the user's account.
  1131. * The command is not necessarily related to the USER command, as some
  1132. * sites may require an account for login and others only for specific
  1133. * access, such as storing files. In the latter case the command may
  1134. * arrive at any time.
  1135. * There are reply codes to differentiate these cases for the automation:
  1136. * when account information is required for login, the response to
  1137. * a successful PASSword command is reply code 332. On the other hand,
  1138. * if account information is NOT required for login, the reply to
  1139. * a successful PASSword command is 230; and if the account information
  1140. * is needed for a command issued later in the dialogue, the server
  1141. * should return a 332 or 532 reply depending on whether it stores
  1142. * (pending receipt of the ACCounT command) or discards the command,
  1143. * respectively."
  1144. */
  1145. while (1) {
  1146. uint32_t cmdval = cmdio_get_cmd_and_arg();
  1147. if (cmdval == const_QUIT) {
  1148. WRITE_OK(FTP_GOODBYE);
  1149. return 0;
  1150. }
  1151. else if (cmdval == const_USER)
  1152. /* This would mean "ok, now give me PASS". */
  1153. /*WRITE_OK(FTP_GIVEPWORD);*/
  1154. /* vsftpd can be configured to not require that,
  1155. * and this also saves one roundtrip:
  1156. */
  1157. WRITE_OK(FTP_LOGINOK);
  1158. else if (cmdval == const_PASS)
  1159. WRITE_OK(FTP_LOGINOK);
  1160. else if (cmdval == const_NOOP)
  1161. WRITE_OK(FTP_NOOPOK);
  1162. else if (cmdval == const_TYPE)
  1163. WRITE_OK(FTP_TYPEOK);
  1164. else if (cmdval == const_STRU)
  1165. WRITE_OK(FTP_STRUOK);
  1166. else if (cmdval == const_MODE)
  1167. WRITE_OK(FTP_MODEOK);
  1168. else if (cmdval == const_ALLO)
  1169. WRITE_OK(FTP_ALLOOK);
  1170. else if (cmdval == const_SYST)
  1171. cmdio_write_raw(STR(FTP_SYSTOK)" UNIX Type: L8\r\n");
  1172. else if (cmdval == const_PWD || cmdval == const_XPWD)
  1173. handle_pwd();
  1174. else if (cmdval == const_CWD)
  1175. handle_cwd();
  1176. else if (cmdval == const_CDUP) /* cd .. */
  1177. handle_cdup();
  1178. /* HELP is nearly useless, but we can reuse FEAT for it */
  1179. /* lftp uses FEAT */
  1180. else if (cmdval == const_HELP || cmdval == const_FEAT)
  1181. handle_feat(cmdval == const_HELP
  1182. ? STRNUM32(FTP_HELP)
  1183. : STRNUM32(FTP_STATOK)
  1184. );
  1185. else if (cmdval == const_LIST) /* ls -l */
  1186. handle_list();
  1187. else if (cmdval == const_NLST) /* "name list", bare ls */
  1188. handle_nlst();
  1189. /* SIZE is crucial for wget's download indicator etc */
  1190. /* Mozilla, lftp use MDTM (presumably for caching) */
  1191. else if (cmdval == const_SIZE || cmdval == const_MDTM)
  1192. handle_size_or_mdtm(cmdval == const_SIZE);
  1193. else if (cmdval == const_STAT) {
  1194. if (G.ftp_arg == NULL)
  1195. handle_stat();
  1196. else
  1197. handle_stat_file();
  1198. }
  1199. else if (cmdval == const_PASV)
  1200. handle_pasv();
  1201. else if (cmdval == const_EPSV)
  1202. handle_epsv();
  1203. else if (cmdval == const_RETR)
  1204. handle_retr();
  1205. else if (cmdval == const_PORT)
  1206. handle_port();
  1207. else if (cmdval == const_REST)
  1208. handle_rest();
  1209. #if ENABLE_FEATURE_FTP_WRITE
  1210. else if (opts & OPT_w) {
  1211. if (cmdval == const_STOR)
  1212. handle_stor();
  1213. else if (cmdval == const_MKD)
  1214. handle_mkd();
  1215. else if (cmdval == const_RMD)
  1216. handle_rmd();
  1217. else if (cmdval == const_DELE)
  1218. handle_dele();
  1219. else if (cmdval == const_RNFR) /* "rename from" */
  1220. handle_rnfr();
  1221. else if (cmdval == const_RNTO) /* "rename to" */
  1222. handle_rnto();
  1223. else if (cmdval == const_APPE)
  1224. handle_appe();
  1225. else if (cmdval == const_STOU) /* "store unique" */
  1226. handle_stou();
  1227. else
  1228. goto bad_cmd;
  1229. }
  1230. #endif
  1231. #if 0
  1232. else if (cmdval == const_STOR
  1233. || cmdval == const_MKD
  1234. || cmdval == const_RMD
  1235. || cmdval == const_DELE
  1236. || cmdval == const_RNFR
  1237. || cmdval == const_RNTO
  1238. || cmdval == const_APPE
  1239. || cmdval == const_STOU
  1240. ) {
  1241. cmdio_write_raw(STR(FTP_NOPERM)" Permission denied\r\n");
  1242. }
  1243. #endif
  1244. else {
  1245. /* Which unsupported commands were seen in the wild?
  1246. * (doesn't necessarily mean "we must support them")
  1247. * foo 1.2.3: XXXX - comment
  1248. */
  1249. #if ENABLE_FEATURE_FTP_WRITE
  1250. bad_cmd:
  1251. #endif
  1252. cmdio_write_raw(STR(FTP_BADCMD)" Unknown command\r\n");
  1253. }
  1254. }
  1255. }