ftpd.c 37 KB

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