ftpd.c 37 KB

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