3
0

ftpd.c 34 KB

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