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