ftpd.c 33 KB

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