ftpd.c 36 KB

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