ftpd.c 35 KB

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