2 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)ftpd.c 8.4 (Berkeley) 4/16/94
30 * $FreeBSD: src/libexec/ftpd/ftpd.c,v 1.213 2008/12/23 01:23:09 cperciva Exp $
36 #include <sys/param.h>
37 #include <sys/ioctl.h>
39 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <netinet/in_systm.h>
46 #include <netinet/ip.h>
47 #include <netinet/tcp.h>
51 #include <arpa/inet.h>
52 #include <arpa/telnet.h>
75 #include <login_cap.h>
79 #include <security/pam_appl.h>
82 #include "pathnames.h"
88 static char version
[] = "Version 6.00LS";
91 extern off_t restart_point
;
94 union sockunion ctrl_addr
;
95 union sockunion data_source
;
96 union sockunion data_dest
;
97 union sockunion his_addr
;
98 union sockunion pasv_addr
;
103 int hostinfo
= 1; /* print host-specific info in messages */
108 int timeout
= 900; /* timeout after 15 minutes of inactivity */
109 int maxtimeout
= 7200;/* don't allow idle time to be set beyond 2 hours */
111 int restricted_data_ports
= 1;
112 int paranoid
= 1; /* be extra careful about security */
113 int anon_only
= 0; /* Only anonymous ftp allowed */
114 int assumeutf8
= 0; /* Assume that server file names are in UTF-8 */
123 int stru
; /* avoid C keyword */
125 int usedefault
= 1; /* for data transfers */
126 int pdata
= -1; /* for passive mode */
127 int readonly
= 0; /* Server is in readonly mode. */
128 int noepsv
= 0; /* EPSV command is disabled. */
129 int noretr
= 0; /* RETR command is disabled. */
130 int noguestretr
= 0; /* RETR command is disabled for anon users. */
131 int noguestmkd
= 0; /* MKD command is disabled for anon users. */
132 int noguestmod
= 1; /* anon users may not modify existing files. */
136 #if !defined(CMASK) || CMASK == 0
140 int defumask
= CMASK
; /* default umask value */
145 #ifdef VIRTUAL_HOSTING
148 static struct ftphost
{
149 struct ftphost
*next
;
150 struct addrinfo
*hostinfo
;
156 } *thishost
, *firsthost
;
159 char remotehost
[NI_MAXHOST
];
162 static char ttyline
[20];
163 char *tty
= ttyline
; /* for klogin */
166 static int auth_pam(struct passwd
**, const char*);
167 pam_handle_t
*pamh
= NULL
;
170 static struct opie opiedata
;
171 static char opieprompt
[OPIE_CHALLENGE_MAX
+1];
174 char *pid_file
= NULL
; /* means default location to pidfile(3) */
177 * Limit number of pathnames that glob can return.
178 * A limit of 0 indicates the number of pathnames is unlimited.
180 #define MAXGLOBARGS 16384
183 * Timeout intervals for retrying connections
184 * to hosts that don't accept PORT cmds. This
185 * is a kludge, but given the problems with TCP...
187 #define SWAITMAX 90 /* wait at most 90 seconds */
188 #define SWAITINT 5 /* interval between retries */
190 int swaitmax
= SWAITMAX
;
191 int swaitint
= SWAITINT
;
194 char proctitle
[LINE_MAX
]; /* initial part of title */
195 #endif /* SETPROCTITLE */
197 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1)
198 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1)
199 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt))
201 static volatile sig_atomic_t recvurg
;
202 static int transflag
; /* NB: for debugging only */
204 #define STARTXFER flagxfer(1)
205 #define ENDXFER flagxfer(0)
207 #define START_UNSAFE maskurg(1)
208 #define END_UNSAFE maskurg(0)
210 /* It's OK to put an `else' clause after this macro. */
211 #define CHECKOOB(action) \
220 #ifdef VIRTUAL_HOSTING
221 static void inithosts(int);
222 static void selecthost(union sockunion
*);
224 static void ack(char *);
225 static void sigurg(int);
226 static void maskurg(int);
227 static void flagxfer(int);
228 static int myoob(void);
229 static int checkuser(char *, char *, int, char **);
230 static FILE *dataconn(char *, off_t
, char *);
231 static void dolog(struct sockaddr
*);
232 static void end_login(void);
233 static FILE *getdatasock(char *);
234 static int guniquefd(char *, char **);
235 static void lostconn(int);
236 static void sigquit(int);
237 static int receive_data(FILE *, FILE *);
238 static int send_data(FILE *, FILE *, size_t, off_t
, int);
239 static struct passwd
*
241 static char *sgetsave(char *);
242 static void reapchild(int);
243 static void appendf(char **, char *, ...) __printflike(2, 3);
244 static void logcmd(char *, char *, char *, off_t
);
245 static void logxfer(char *, off_t
, time_t);
246 static char *doublequote(char *);
247 static int *socksetup(int, char *, const char *);
250 main(int argc
, char *argv
[])
254 char *cp
, line
[LINE_MAX
];
256 char *bindname
= NULL
;
257 const char *bindport
= "ftp";
258 int family
= AF_UNSPEC
;
261 tzset(); /* in case no timezone database in ~ftp */
262 sigemptyset(&sa
.sa_mask
);
263 sa
.sa_flags
= SA_RESTART
;
266 * Prevent diagnostic messages from appearing on stderr.
267 * We run as a daemon or from inetd; in both cases, there's
268 * more reason in logging to syslog.
270 freopen(_PATH_DEVNULL
, "w", stderr
);
274 * LOG_NDELAY sets up the logging connection immediately,
275 * necessary for anonymous ftp's that chroot and can't do it later.
277 openlog("ftpd", LOG_PID
| LOG_NDELAY
, LOG_FTP
);
279 while ((ch
= getopt(argc
, argv
,
280 "468a:AdDEH:hlmMoOp:P:rRSt:T:u:UvW")) != -1) {
283 family
= (family
== AF_INET6
) ? AF_UNSPEC
: AF_INET
;
287 family
= (family
== AF_INET
) ? AF_UNSPEC
: AF_INET6
;
323 logging
++; /* > 1 == extra logging */
363 timeout
= atoi(optarg
);
364 if (maxtimeout
< timeout
)
365 maxtimeout
= timeout
;
369 maxtimeout
= atoi(optarg
);
370 if (timeout
> maxtimeout
)
371 timeout
= maxtimeout
;
378 val
= strtol(optarg
, &optarg
, 8);
379 if (*optarg
!= '\0' || val
< 0)
380 syslog(LOG_WARNING
, "bad value for -u");
386 restricted_data_ports
= 0;
398 syslog(LOG_WARNING
, "unknown flag -%c ignored", optopt
);
404 int *ctl_sock
, fd
, maxfd
= -1, nfds
, i
;
405 fd_set defreadfds
, readfds
;
409 if ((pfh
= pidfile_open(pid_file
, 0600, &pid
)) == NULL
) {
410 if (errno
== EEXIST
) {
411 syslog(LOG_ERR
, "%s already running, pid %d",
412 getprogname(), (int)pid
);
415 syslog(LOG_WARNING
, "pidfile_open: %m");
419 * Detach from parent.
421 if (daemon(1, 1) < 0) {
422 syslog(LOG_ERR
, "failed to become a daemon");
426 if (pfh
!= NULL
&& pidfile_write(pfh
) == -1)
427 syslog(LOG_WARNING
, "pidfile_write: %m");
429 sa
.sa_handler
= reapchild
;
430 sigaction(SIGCHLD
, &sa
, NULL
);
432 #ifdef VIRTUAL_HOSTING
437 * Open a socket, bind it to the FTP port, and start
440 ctl_sock
= socksetup(family
, bindname
, bindport
);
441 if (ctl_sock
== NULL
)
444 FD_ZERO(&defreadfds
);
445 for (i
= 1; i
<= *ctl_sock
; i
++) {
446 FD_SET(ctl_sock
[i
], &defreadfds
);
447 if (listen(ctl_sock
[i
], 32) < 0) {
448 syslog(LOG_ERR
, "control listen: %m");
451 if (maxfd
< ctl_sock
[i
])
456 * Loop forever accepting connection requests and forking off
457 * children to handle them.
460 FD_COPY(&defreadfds
, &readfds
);
461 nfds
= select(maxfd
+ 1, &readfds
, NULL
, NULL
, 0);
463 if (nfds
< 0 && errno
!= EINTR
)
464 syslog(LOG_WARNING
, "select: %m");
469 for (i
= 1; i
<= *ctl_sock
; i
++)
470 if (FD_ISSET(ctl_sock
[i
], &readfds
)) {
471 addrlen
= sizeof(his_addr
);
472 fd
= accept(ctl_sock
[i
],
473 (struct sockaddr
*)&his_addr
,
480 switch (pid
= fork()) {
486 for (i
= 1; i
<= *ctl_sock
; i
++)
492 syslog(LOG_WARNING
, "fork: %m");
500 addrlen
= sizeof(his_addr
);
501 if (getpeername(0, (struct sockaddr
*)&his_addr
, &addrlen
) < 0) {
502 syslog(LOG_ERR
, "getpeername (%s): %m",argv
[0]);
506 #ifdef VIRTUAL_HOSTING
507 if (his_addr
.su_family
== AF_INET6
&&
508 IN6_IS_ADDR_V4MAPPED(&his_addr
.su_sin6
.sin6_addr
))
511 family
= his_addr
.su_family
;
517 sa
.sa_handler
= SIG_DFL
;
518 sigaction(SIGCHLD
, &sa
, NULL
);
520 sa
.sa_handler
= sigurg
;
521 sa
.sa_flags
= 0; /* don't restart syscalls for SIGURG */
522 sigaction(SIGURG
, &sa
, NULL
);
524 sigfillset(&sa
.sa_mask
); /* block all signals in handler */
525 sa
.sa_flags
= SA_RESTART
;
526 sa
.sa_handler
= sigquit
;
527 sigaction(SIGHUP
, &sa
, NULL
);
528 sigaction(SIGINT
, &sa
, NULL
);
529 sigaction(SIGQUIT
, &sa
, NULL
);
530 sigaction(SIGTERM
, &sa
, NULL
);
532 sa
.sa_handler
= lostconn
;
533 sigaction(SIGPIPE
, &sa
, NULL
);
535 addrlen
= sizeof(ctrl_addr
);
536 if (getsockname(0, (struct sockaddr
*)&ctrl_addr
, &addrlen
) < 0) {
537 syslog(LOG_ERR
, "getsockname (%s): %m",argv
[0]);
540 dataport
= ntohs(ctrl_addr
.su_port
) - 1; /* as per RFC 959 */
541 #ifdef VIRTUAL_HOSTING
542 /* select our identity from virtual host table */
543 selecthost(&ctrl_addr
);
546 if (ctrl_addr
.su_family
== AF_INET
)
548 tos
= IPTOS_LOWDELAY
;
549 if (setsockopt(0, IPPROTO_IP
, IP_TOS
, &tos
, sizeof(int)) < 0)
550 syslog(LOG_WARNING
, "control setsockopt (IP_TOS): %m");
554 * Disable Nagle on the control channel so that we don't have to wait
555 * for peer's ACK before issuing our next reply.
557 if (setsockopt(0, IPPROTO_TCP
, TCP_NODELAY
, &on
, sizeof(on
)) < 0)
558 syslog(LOG_WARNING
, "control setsockopt (TCP_NODELAY): %m");
560 data_source
.su_port
= htons(ntohs(ctrl_addr
.su_port
) - 1);
562 /* set this here so klogin can use it... */
563 snprintf(ttyline
, sizeof(ttyline
), "ftp%d", getpid());
565 /* Try to handle urgent data inline */
567 if (setsockopt(0, SOL_SOCKET
, SO_OOBINLINE
, &on
, sizeof(on
)) < 0)
568 syslog(LOG_WARNING
, "control setsockopt (SO_OOBINLINE): %m");
572 if (fcntl(fileno(stdin
), F_SETOWN
, getpid()) == -1)
573 syslog(LOG_ERR
, "fcntl F_SETOWN: %m");
575 dolog((struct sockaddr
*)&his_addr
);
577 * Set up default state
586 /* If logins are disabled, print out the message. */
587 if ((fd
= fopen(_PATH_NOLOGIN
,"r")) != NULL
) {
588 while (fgets(line
, sizeof(line
), fd
) != NULL
) {
589 if ((cp
= strchr(line
, '\n')) != NULL
)
591 lreply(530, "%s", line
);
595 reply(530, "System not available.");
598 #ifdef VIRTUAL_HOSTING
599 fd
= fopen(thishost
->welcome
, "r");
601 fd
= fopen(_PATH_FTPWELCOME
, "r");
604 while (fgets(line
, sizeof(line
), fd
) != NULL
) {
605 if ((cp
= strchr(line
, '\n')) != NULL
)
607 lreply(220, "%s", line
);
611 /* reply(220,) must follow */
613 #ifndef VIRTUAL_HOSTING
614 if (hostname
== NULL
) {
615 if ((hostname
= malloc(MAXHOSTNAMELEN
)) == NULL
)
616 fatalerror("Ran out of memory.");
617 if (gethostname(hostname
, MAXHOSTNAMELEN
- 1) < 0)
619 hostname
[MAXHOSTNAMELEN
- 1] = '\0';
623 reply(220, "%s FTP server (%s) ready.", hostname
, version
);
625 reply(220, "FTP server ready.");
636 syslog(LOG_DEBUG
, "lost connection");
644 syslog(LOG_ERR
, "got signal %d", signo
);
648 #ifdef VIRTUAL_HOSTING
650 * read in virtual host tables (if they exist)
654 inithosts(int family
)
659 char *cp
, *mp
, *line
;
660 char *vhost
, *anonuser
, *statfile
, *welcome
, *loginmsg
;
661 struct ftphost
*hrp
, *lhrp
;
662 struct addrinfo hints
, *res
, *ai
;
665 * Fill in the default host information
667 if (hostname
== NULL
) {
668 if ((hostname
= malloc(MAXHOSTNAMELEN
)) == NULL
)
669 fatalerror("Ran out of memory.");
670 if (gethostname(hostname
, MAXHOSTNAMELEN
- 1) < 0)
672 hostname
[MAXHOSTNAMELEN
- 1] = '\0';
674 if ((hrp
= malloc(sizeof(struct ftphost
))) == NULL
)
675 fatalerror("Ran out of memory.");
676 hrp
->hostname
= hostname
;
677 hrp
->hostinfo
= NULL
;
679 memset(&hints
, 0, sizeof(hints
));
680 hints
.ai_flags
= AI_PASSIVE
;
681 hints
.ai_family
= family
;
682 hints
.ai_socktype
= SOCK_STREAM
;
683 if (getaddrinfo(hrp
->hostname
, NULL
, &hints
, &res
) == 0)
685 hrp
->statfile
= _PATH_FTPDSTATFILE
;
686 hrp
->welcome
= _PATH_FTPWELCOME
;
687 hrp
->loginmsg
= _PATH_FTPLOGINMESG
;
688 hrp
->anonuser
= "ftp";
690 thishost
= firsthost
= lhrp
= hrp
;
691 if ((fp
= fopen(_PATH_FTPHOSTS
, "r")) != NULL
) {
692 int addrsize
, gothost
;
696 while ((line
= fgetln(fp
, &len
)) != NULL
) {
702 if (line
[len
- 1] == '\n') {
703 line
[len
- 1] = '\0';
706 if ((mp
= malloc(len
+ 1)) == NULL
)
707 fatalerror("Ran out of memory.");
708 memcpy(mp
, line
, len
);
712 cp
= strtok(line
, " \t");
713 /* skip empty lines */
720 statfile
= _PATH_FTPDSTATFILE
;
721 welcome
= _PATH_FTPWELCOME
;
722 loginmsg
= _PATH_FTPLOGINMESG
;
725 * Preparse the line so we can use its info
726 * for all the addresses associated with
727 * the virtual host name.
728 * Field 0, the virtual host name, is special:
729 * it's already parsed off and will be strdup'ed
730 * later, after we know its canonical form.
732 for (i
= 1; i
< 5 && (cp
= strtok(NULL
, " \t")); i
++)
733 if (*cp
!= '-' && (cp
= strdup(cp
)))
735 case 1: /* anon user permissions */
738 case 2: /* statistics file */
741 case 3: /* welcome message */
744 case 4: /* login message */
747 default: /* programming error */
752 hints
.ai_flags
= AI_PASSIVE
;
753 hints
.ai_family
= family
;
754 hints
.ai_socktype
= SOCK_STREAM
;
755 if (getaddrinfo(vhost
, NULL
, &hints
, &res
) != 0)
757 for (ai
= res
; ai
!= NULL
&& ai
->ai_addr
!= NULL
;
761 for (hrp
= firsthost
; hrp
!= NULL
; hrp
= hrp
->next
) {
764 for (hi
= hrp
->hostinfo
; hi
!= NULL
;
766 if (hi
->ai_addrlen
== ai
->ai_addrlen
&&
769 ai
->ai_addr
->sa_len
) == 0) {
777 if ((hrp
= malloc(sizeof(struct ftphost
))) == NULL
)
779 hrp
->hostname
= NULL
;
782 if (hrp
->hostinfo
&& hrp
->hostinfo
!= res
)
783 freeaddrinfo(hrp
->hostinfo
);
784 insert
= 0; /* host already in the chain */
789 * determine hostname to use.
790 * force defined name if there is a valid alias
791 * otherwise fallback to primary hostname
793 /* XXX: getaddrinfo() can't do alias check */
794 switch(hrp
->hostinfo
->ai_family
) {
796 addr
= &((struct sockaddr_in
*)hrp
->hostinfo
->ai_addr
)->sin_addr
;
797 addrsize
= sizeof(struct in_addr
);
800 addr
= &((struct sockaddr_in6
*)hrp
->hostinfo
->ai_addr
)->sin6_addr
;
801 addrsize
= sizeof(struct in6_addr
);
804 /* should not reach here */
805 freeaddrinfo(hrp
->hostinfo
);
807 free(hrp
); /*not in chain, can free*/
809 hrp
->hostinfo
= NULL
; /*mark as blank*/
813 if ((hp
= getipnodebyaddr(addr
, addrsize
,
814 hrp
->hostinfo
->ai_family
,
815 &hp_error
)) != NULL
) {
816 if (strcmp(vhost
, hp
->h_name
) != 0) {
817 if (hp
->h_aliases
== NULL
)
821 while (hp
->h_aliases
[i
] &&
822 strcmp(vhost
, hp
->h_aliases
[i
]) != 0)
824 if (hp
->h_aliases
[i
] == NULL
)
830 strcmp(hrp
->hostname
, vhost
) != 0) {
832 hrp
->hostname
= NULL
;
834 if (hrp
->hostname
== NULL
&&
835 (hrp
->hostname
= strdup(vhost
)) == NULL
) {
836 freeaddrinfo(hrp
->hostinfo
);
837 hrp
->hostinfo
= NULL
; /* mark as blank */
842 hrp
->anonuser
= anonuser
;
843 hrp
->statfile
= statfile
;
844 hrp
->welcome
= welcome
;
845 hrp
->loginmsg
= loginmsg
;
863 selecthost(union sockunion
*su
)
868 struct in6_addr
*mapped_in6
= NULL
;
874 * XXX IPv4 mapped IPv6 addr consideraton,
875 * specified in rfc2373.
877 if (su
->su_family
== AF_INET6
&&
878 IN6_IS_ADDR_V4MAPPED(&su
->su_sin6
.sin6_addr
))
879 mapped_in6
= &su
->su_sin6
.sin6_addr
;
882 hrp
= thishost
= firsthost
; /* default */
885 while (hrp
!= NULL
) {
886 for (hi
= hrp
->hostinfo
; hi
!= NULL
; hi
= hi
->ai_next
) {
887 if (memcmp(su
, hi
->ai_addr
, hi
->ai_addrlen
) == 0) {
892 /* XXX IPv4 mapped IPv6 addr consideraton */
893 if (hi
->ai_addr
->sa_family
== AF_INET
&& mapped_in6
!= NULL
&&
894 (memcmp(&mapped_in6
->s6_addr
[12],
895 &((struct sockaddr_in
*)hi
->ai_addr
)->sin_addr
,
896 sizeof(struct in_addr
)) == 0)) {
906 /* setup static variables as appropriate */
907 hostname
= thishost
->hostname
;
908 ftpuser
= thishost
->anonuser
;
913 * Helper function for sgetpwnam().
918 char *new = malloc(strlen(s
) + 1);
921 reply(421, "Ran out of memory.");
930 * Save the result of a getpwnam. Used for USER command, since
931 * the data returned must not be clobbered by any other command
933 * NB: The data returned by sgetpwnam() will remain valid until
934 * the next call to this function. Its difference from getpwnam()
935 * is that sgetpwnam() is known to be called from ftpd code only.
937 static struct passwd
*
938 sgetpwnam(char *name
)
940 static struct passwd save
;
943 if ((p
= getpwnam(name
)) == NULL
)
947 free(save
.pw_passwd
);
953 save
.pw_name
= sgetsave(p
->pw_name
);
954 save
.pw_passwd
= sgetsave(p
->pw_passwd
);
955 save
.pw_gecos
= sgetsave(p
->pw_gecos
);
956 save
.pw_dir
= sgetsave(p
->pw_dir
);
957 save
.pw_shell
= sgetsave(p
->pw_shell
);
961 static int login_attempts
; /* number of failed login attempts */
962 static int askpasswd
; /* had user command, ask for passwd */
963 static char curname
[MAXLOGNAME
]; /* current USER name */
967 * Sets global passwd pointer pw if named account exists and is acceptable;
968 * sets askpasswd if a PASS command is expected. If logged in previously,
969 * need to reset state. If name is "ftp" or "anonymous", the name is not in
970 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
971 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
972 * requesting login privileges. Disallow anyone who does not have a standard
973 * shell as returned by getusershell(). Disallow anyone mentioned in the file
974 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
983 reply(530, "Can't change user from guest login.");
985 } else if (dochroot
) {
986 reply(530, "Can't change user from chroot user.");
993 #ifdef VIRTUAL_HOSTING
994 pw
= sgetpwnam(thishost
->anonuser
);
996 pw
= sgetpwnam("ftp");
998 if (strcmp(name
, "ftp") == 0 || strcmp(name
, "anonymous") == 0) {
999 if (checkuser(_PATH_FTPUSERS
, "ftp", 0, NULL
) ||
1000 checkuser(_PATH_FTPUSERS
, "anonymous", 0, NULL
))
1001 reply(530, "User %s access denied.", name
);
1002 else if (pw
!= NULL
) {
1006 "Guest login ok, send your email address as password.");
1008 reply(530, "User %s unknown.", name
);
1009 if (!askpasswd
&& logging
)
1011 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost
);
1014 if (anon_only
!= 0) {
1015 reply(530, "Sorry, only anonymous ftp allowed.");
1019 if ((pw
= sgetpwnam(name
))) {
1020 if ((shell
= pw
->pw_shell
) == NULL
|| *shell
== 0)
1021 shell
= _PATH_BSHELL
;
1023 while ((cp
= getusershell()) != NULL
)
1024 if (strcmp(cp
, shell
) == 0)
1028 if (cp
== NULL
|| checkuser(_PATH_FTPUSERS
, name
, 1, NULL
)) {
1029 reply(530, "User %s access denied.", name
);
1032 "FTP LOGIN REFUSED FROM %s, %s",
1039 strncpy(curname
, name
, sizeof(curname
)-1);
1043 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1045 if (opiechallenge(&opiedata
, name
, opieprompt
) == 0) {
1046 pwok
= (pw
!= NULL
) &&
1047 opieaccessfile(remotehost
) &&
1048 opiealways(pw
->pw_dir
);
1049 reply(331, "Response to %s %s for %s.",
1050 opieprompt
, pwok
? "requested" : "required", name
);
1053 reply(331, "Password required for %s.", name
);
1057 * Delay before reading passwd after first failed
1058 * attempt to slow down passwd-guessing programs.
1061 sleep(login_attempts
);
1065 * Check if a user is in the file "fname",
1066 * return a pointer to a malloc'd string with the rest
1067 * of the matching line in "residue" if not NULL.
1070 checkuser(char *fname
, char *name
, int pwset
, char **residue
)
1075 char *line
, *mp
, *p
;
1077 if ((fd
= fopen(fname
, "r")) != NULL
) {
1078 while (!found
&& (line
= fgetln(fd
, &len
)) != NULL
) {
1082 if (line
[len
- 1] == '\n') {
1083 line
[len
- 1] = '\0';
1086 if ((mp
= malloc(len
+ 1)) == NULL
)
1087 fatalerror("Ran out of memory.");
1088 memcpy(mp
, line
, len
);
1092 /* avoid possible leading and trailing whitespace */
1093 p
= strtok(line
, " \t");
1094 /* skip empty lines */
1098 * if first chr is '@', check group membership
1104 if (p
[1] == '\0') /* single @ matches anyone */
1107 if ((grp
= getgrnam(p
+1)) == NULL
)
1110 * Check user's default group
1112 if (pwset
&& grp
->gr_gid
== pw
->pw_gid
)
1115 * Check supplementary groups
1117 while (!found
&& grp
->gr_mem
[i
])
1118 found
= strcmp(name
,
1124 * Otherwise, just check for username match
1127 found
= strcmp(p
, name
) == 0;
1129 * Save the rest of line to "residue" if matched
1131 if (found
&& residue
) {
1132 if ((p
= strtok(NULL
, "")) != NULL
)
1133 p
+= strspn(p
, " \t");
1135 if ((*residue
= strdup(p
)) == NULL
)
1136 fatalerror("Ran out of memory.");
1150 * Terminate login as previous user, if any, resetting state;
1151 * used when USER command is given or login fails.
1161 if (logged_in
&& dowtmp
)
1162 ftpd_logwtmp(ttyline
, "", NULL
);
1165 /* XXX Missing LOGIN_SETMAC */
1166 setusercontext(NULL
, getpwuid(0), 0,
1167 LOGIN_SETPRIORITY
|LOGIN_SETRESOURCES
|LOGIN_SETUMASK
);
1171 if ((e
= pam_setcred(pamh
, PAM_DELETE_CRED
)) != PAM_SUCCESS
)
1172 syslog(LOG_ERR
, "pam_setcred: %s", pam_strerror(pamh
, e
));
1173 if ((e
= pam_close_session(pamh
,0)) != PAM_SUCCESS
)
1174 syslog(LOG_ERR
, "pam_close_session: %s", pam_strerror(pamh
, e
));
1175 if ((e
= pam_end(pamh
, e
)) != PAM_SUCCESS
)
1176 syslog(LOG_ERR
, "pam_end: %s", pam_strerror(pamh
, e
));
1188 * the following code is stolen from imap-uw PAM authentication module and
1191 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1194 const char *uname
; /* user name */
1195 const char *pass
; /* password */
1197 typedef struct cred_t cred_t
;
1200 auth_conv(int num_msg
, const struct pam_message
**msg
,
1201 struct pam_response
**resp
, void *appdata
)
1204 cred_t
*cred
= (cred_t
*) appdata
;
1205 struct pam_response
*reply
;
1207 reply
= calloc(num_msg
, sizeof *reply
);
1211 for (i
= 0; i
< num_msg
; i
++) {
1212 switch (msg
[i
]->msg_style
) {
1213 case PAM_PROMPT_ECHO_ON
: /* assume want user name */
1214 reply
[i
].resp_retcode
= PAM_SUCCESS
;
1215 reply
[i
].resp
= COPY_STRING(cred
->uname
);
1216 /* PAM frees resp. */
1218 case PAM_PROMPT_ECHO_OFF
: /* assume want password */
1219 reply
[i
].resp_retcode
= PAM_SUCCESS
;
1220 reply
[i
].resp
= COPY_STRING(cred
->pass
);
1221 /* PAM frees resp. */
1225 reply
[i
].resp_retcode
= PAM_SUCCESS
;
1226 reply
[i
].resp
= NULL
;
1228 default: /* unknown message style */
1230 return PAM_CONV_ERR
;
1239 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1240 * authenticated, or 1 if not authenticated. If some sort of PAM system
1241 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1242 * function returns -1. This can be used as an indication that we should
1243 * fall back to a different authentication mechanism.
1246 auth_pam(struct passwd
**ppw
, const char *pass
)
1248 const char *tmpl_user
;
1252 cred_t auth_cred
= { (*ppw
)->pw_name
, pass
};
1253 struct pam_conv conv
= { &auth_conv
, &auth_cred
};
1255 e
= pam_start("ftpd", (*ppw
)->pw_name
, &conv
, &pamh
);
1256 if (e
!= PAM_SUCCESS
) {
1258 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1259 * if context creation has failed in the first place.
1261 syslog(LOG_ERR
, "pam_start: %s", pam_strerror(NULL
, e
));
1265 e
= pam_set_item(pamh
, PAM_RHOST
, remotehost
);
1266 if (e
!= PAM_SUCCESS
) {
1267 syslog(LOG_ERR
, "pam_set_item(PAM_RHOST): %s",
1268 pam_strerror(pamh
, e
));
1269 if ((e
= pam_end(pamh
, e
)) != PAM_SUCCESS
) {
1270 syslog(LOG_ERR
, "pam_end: %s", pam_strerror(pamh
, e
));
1276 e
= pam_authenticate(pamh
, 0);
1280 * With PAM we support the concept of a "template"
1281 * user. The user enters a login name which is
1282 * authenticated by PAM, usually via a remote service
1283 * such as RADIUS or TACACS+. If authentication
1284 * succeeds, a different but related "template" name
1285 * is used for setting the credentials, shell, and
1286 * home directory. The name the user enters need only
1287 * exist on the remote authentication server, but the
1288 * template name must be present in the local password
1291 * This is supported by two various mechanisms in the
1292 * individual modules. However, from the application's
1293 * point of view, the template user is always passed
1294 * back as a changed value of the PAM_USER item.
1296 if ((e
= pam_get_item(pamh
, PAM_USER
, &item
)) ==
1298 tmpl_user
= (const char *) item
;
1299 if (strcmp((*ppw
)->pw_name
, tmpl_user
) != 0)
1300 *ppw
= getpwnam(tmpl_user
);
1302 syslog(LOG_ERR
, "Couldn't get PAM_USER: %s",
1303 pam_strerror(pamh
, e
));
1308 case PAM_USER_UNKNOWN
:
1314 syslog(LOG_ERR
, "pam_authenticate: %s", pam_strerror(pamh
, e
));
1320 e
= pam_acct_mgmt(pamh
, 0);
1321 if (e
!= PAM_SUCCESS
) {
1322 syslog(LOG_ERR
, "pam_acct_mgmt: %s",
1323 pam_strerror(pamh
, e
));
1329 if ((e
= pam_end(pamh
, e
)) != PAM_SUCCESS
) {
1330 syslog(LOG_ERR
, "pam_end: %s", pam_strerror(pamh
, e
));
1337 #endif /* USE_PAM */
1345 login_cap_t
*lc
= NULL
;
1350 char *residue
= NULL
;
1353 if (logged_in
|| askpasswd
== 0) {
1354 reply(503, "Login with USER first.");
1358 if (!guest
) { /* "ftp" is only account allowed no password */
1360 rval
= 1; /* failure below */
1364 rval
= auth_pam(&pw
, passwd
);
1370 if (opieverify(&opiedata
, passwd
) == 0)
1371 xpasswd
= pw
->pw_passwd
;
1373 xpasswd
= crypt(passwd
, pw
->pw_passwd
);
1374 if (passwd
[0] == '\0' && pw
->pw_passwd
[0] != '\0')
1380 rval
= strcmp(pw
->pw_passwd
, xpasswd
);
1381 if (pw
->pw_expire
&& time(NULL
) >= pw
->pw_expire
)
1382 rval
= 1; /* failure */
1385 * If rval == 1, the user failed the authentication check
1386 * above. If rval == 0, either PAM or local authentication
1390 reply(530, "Login incorrect.");
1393 "FTP LOGIN FAILED FROM %s",
1395 syslog(LOG_AUTHPRIV
| LOG_NOTICE
,
1396 "FTP LOGIN FAILED FROM %s, %s",
1397 remotehost
, curname
);
1400 if (login_attempts
++ >= 5) {
1402 "repeated login failures from %s",
1409 login_attempts
= 0; /* this time successful */
1410 if (setegid(pw
->pw_gid
) < 0) {
1411 reply(550, "Can't set gid.");
1414 /* May be overridden by login.conf */
1417 if ((lc
= login_getpwclass(pw
)) != NULL
) {
1418 char remote_ip
[NI_MAXHOST
];
1420 if (getnameinfo((struct sockaddr
*)&his_addr
, his_addr
.su_len
,
1421 remote_ip
, sizeof(remote_ip
) - 1, NULL
, 0,
1424 remote_ip
[sizeof(remote_ip
) - 1] = 0;
1425 if (!auth_hostok(lc
, remotehost
, remote_ip
)) {
1426 syslog(LOG_INFO
|LOG_AUTH
,
1427 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1429 reply(530, "Permission denied.");
1433 if (!auth_timeok(lc
, time(NULL
))) {
1434 reply(530, "Login not available right now.");
1439 /* XXX Missing LOGIN_SETMAC */
1440 setusercontext(lc
, pw
, 0,
1441 LOGIN_SETLOGIN
|LOGIN_SETGROUP
|LOGIN_SETPRIORITY
|
1442 LOGIN_SETRESOURCES
|LOGIN_SETUMASK
);
1444 setlogin(pw
->pw_name
);
1445 initgroups(pw
->pw_name
, pw
->pw_gid
);
1450 if ((e
= pam_open_session(pamh
, 0)) != PAM_SUCCESS
) {
1451 syslog(LOG_ERR
, "pam_open_session: %s", pam_strerror(pamh
, e
));
1452 } else if ((e
= pam_setcred(pamh
, PAM_ESTABLISH_CRED
)) != PAM_SUCCESS
) {
1453 syslog(LOG_ERR
, "pam_setcred: %s", pam_strerror(pamh
, e
));
1458 /* open wtmp before chroot */
1460 ftpd_logwtmp(ttyline
, pw
->pw_name
,
1461 (struct sockaddr
*)&his_addr
);
1464 if (guest
&& stats
&& statfd
< 0)
1465 #ifdef VIRTUAL_HOSTING
1466 statfd
= open(thishost
->statfile
, O_WRONLY
|O_APPEND
);
1468 statfd
= open(_PATH_FTPDSTATFILE
, O_WRONLY
|O_APPEND
);
1474 checkuser(_PATH_FTPCHROOT
, pw
->pw_name
, 1, &residue
)
1475 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1476 || login_getcapbool(lc
, "ftp-chroot", 0)
1481 * For a chrooted local user,
1482 * a) see whether ftpchroot(5) specifies a chroot directory,
1483 * b) extract the directory pathname from the line,
1484 * c) expand it to the absolute pathname if necessary.
1486 if (dochroot
&& residue
&&
1487 (chrootdir
= strtok(residue
, " \t")) != NULL
) {
1488 if (chrootdir
[0] != '/')
1489 asprintf(&chrootdir
, "%s/%s", pw
->pw_dir
, chrootdir
);
1491 chrootdir
= strdup(chrootdir
); /* make it permanent */
1492 if (chrootdir
== NULL
)
1493 fatalerror("Ran out of memory.");
1495 if (guest
|| dochroot
) {
1497 * If no chroot directory set yet, use the login directory.
1498 * Copy it so it can be modified while pw->pw_dir stays intact.
1500 if (chrootdir
== NULL
&&
1501 (chrootdir
= strdup(pw
->pw_dir
)) == NULL
)
1502 fatalerror("Ran out of memory.");
1504 * Check for the "/chroot/./home" syntax,
1505 * separate the chroot and home directory pathnames.
1507 if ((homedir
= strstr(chrootdir
, "/./")) != NULL
) {
1508 *(homedir
++) = '\0'; /* wipe '/' */
1509 homedir
++; /* skip '.' */
1512 * We MUST do a chdir() after the chroot. Otherwise
1513 * the old current directory will be accessible as "."
1514 * outside the new root!
1519 * Finally, do chroot()
1521 if (chroot(chrootdir
) < 0) {
1522 reply(550, "Can't change root.");
1525 } else /* real user w/o chroot */
1526 homedir
= pw
->pw_dir
;
1528 * Set euid *before* doing chdir() so
1529 * a) the user won't be carried to a directory that he couldn't reach
1530 * on his own due to no permission to upper path components,
1531 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1532 * (uid 0 has no root power over NFS if not mapped explicitly.)
1534 if (seteuid(pw
->pw_uid
) < 0) {
1535 reply(550, "Can't set uid.");
1538 if (chdir(homedir
) < 0) {
1539 if (guest
|| dochroot
) {
1540 reply(550, "Can't change to base directory.");
1543 if (chdir("/") < 0) {
1544 reply(550, "Root is inaccessible.");
1547 lreply(230, "No directory! Logging in with home=/.");
1552 * Display a login message, if it exists.
1553 * N.B. reply(230,) must follow the message.
1555 #ifdef VIRTUAL_HOSTING
1556 fd
= fopen(thishost
->loginmsg
, "r");
1558 fd
= fopen(_PATH_FTPLOGINMESG
, "r");
1561 char *cp
, line
[LINE_MAX
];
1563 while (fgets(line
, sizeof(line
), fd
) != NULL
) {
1564 if ((cp
= strchr(line
, '\n')) != NULL
)
1566 lreply(230, "%s", line
);
1574 ident
= strdup(passwd
);
1576 fatalerror("Ran out of memory.");
1578 reply(230, "Guest login ok, access restrictions apply.");
1580 #ifdef VIRTUAL_HOSTING
1581 if (thishost
!= firsthost
)
1582 snprintf(proctitle
, sizeof(proctitle
),
1583 "%s: anonymous(%s)/%s", remotehost
, hostname
,
1587 snprintf(proctitle
, sizeof(proctitle
),
1588 "%s: anonymous/%s", remotehost
, passwd
);
1589 setproctitle("%s", proctitle
);
1590 #endif /* SETPROCTITLE */
1592 syslog(LOG_INFO
, "ANONYMOUS FTP LOGIN FROM %s, %s",
1593 remotehost
, passwd
);
1596 reply(230, "User %s logged in, "
1597 "access restrictions apply.", pw
->pw_name
);
1599 reply(230, "User %s logged in.", pw
->pw_name
);
1602 snprintf(proctitle
, sizeof(proctitle
),
1603 "%s: user/%s", remotehost
, pw
->pw_name
);
1604 setproctitle("%s", proctitle
);
1605 #endif /* SETPROCTITLE */
1607 syslog(LOG_INFO
, "FTP LOGIN FROM %s as %s",
1608 remotehost
, pw
->pw_name
);
1610 if (logging
&& (guest
|| dochroot
))
1611 syslog(LOG_INFO
, "session root changed to %s", chrootdir
);
1619 /* Forget all about it... */
1629 retrieve(char *cmd
, char *name
)
1633 int (*closefunc
)(FILE *);
1637 fin
= fopen(name
, "r"), closefunc
= fclose
;
1642 snprintf(line
, sizeof(line
), cmd
, name
), name
= line
;
1643 fin
= ftpd_popen(line
, "r"), closefunc
= ftpd_pclose
;
1645 st
.st_blksize
= BUFSIZ
;
1649 perror_reply(550, name
);
1651 LOGCMD("get", name
);
1658 if (fstat(fileno(fin
), &st
) < 0) {
1659 perror_reply(550, name
);
1662 if (!S_ISREG(st
.st_mode
)) {
1664 * Never sending a raw directory is a workaround
1665 * for buggy clients that will attempt to RETR
1666 * a directory before listing it, e.g., Mozilla.
1667 * Preventing a guest from getting irregular files
1668 * is a simple security measure.
1670 if (S_ISDIR(st
.st_mode
) || guest
) {
1671 reply(550, "%s: not a plain file.", name
);
1675 /* st.st_blksize is set for all descriptor types */
1678 if (restart_point
) {
1679 if (type
== TYPE_A
) {
1686 if ((c
=getc(fin
)) == EOF
) {
1687 perror_reply(550, name
);
1693 } else if (lseek(fileno(fin
), restart_point
, L_SET
) < 0) {
1694 perror_reply(550, name
);
1698 dout
= dataconn(name
, st
.st_size
, "w");
1702 send_data(fin
, dout
, st
.st_blksize
, st
.st_size
,
1703 restart_point
== 0 && cmd
== NULL
&& S_ISREG(st
.st_mode
));
1704 if (cmd
== NULL
&& guest
&& stats
&& byte_count
> 0)
1705 logxfer(name
, byte_count
, start
);
1711 LOGBYTES("get", name
, byte_count
);
1716 store(char *name
, char *mode
, int unique
)
1720 int (*closefunc
)(FILE *);
1722 if (*mode
== 'a') { /* APPE */
1724 /* Programming error */
1725 syslog(LOG_ERR
, "Internal: unique flag to APPE");
1728 if (guest
&& noguestmod
) {
1729 reply(550, "Appending to existing file denied.");
1732 restart_point
= 0; /* not affected by preceding REST */
1734 if (unique
) /* STOU overrides REST */
1736 if (guest
&& noguestmod
) {
1737 if (restart_point
) { /* guest STOR w/REST */
1738 reply(550, "Modifying existing file denied.");
1740 } else /* treat guest STOR as STOU */
1745 mode
= "r+"; /* so ASCII manual seek can work */
1747 if ((fd
= guniquefd(name
, &name
)) < 0)
1749 fout
= fdopen(fd
, mode
);
1751 fout
= fopen(name
, mode
);
1754 perror_reply(553, name
);
1758 if (restart_point
) {
1759 if (type
== TYPE_A
) {
1766 if ((c
=getc(fout
)) == EOF
) {
1767 perror_reply(550, name
);
1774 * We must do this seek to "current" position
1775 * because we are changing from reading to
1778 if (fseeko(fout
, 0, SEEK_CUR
) < 0) {
1779 perror_reply(550, name
);
1782 } else if (lseek(fileno(fout
), restart_point
, L_SET
) < 0) {
1783 perror_reply(550, name
);
1787 din
= dataconn(name
, -1, "r");
1790 if (receive_data(din
, fout
) == 0) {
1792 reply(226, "Transfer complete (unique file name:%s).",
1795 reply(226, "Transfer complete.");
1801 LOGBYTES(*mode
== 'a' ? "append" : "put", name
, byte_count
);
1805 LOGCMD(*mode
== 'a' ? "append" : "put" , name
);
1810 getdatasock(char *mode
)
1812 int on
= 1, s
, t
, tries
;
1815 return (fdopen(data
, mode
));
1817 s
= socket(data_dest
.su_family
, SOCK_STREAM
, 0);
1820 if (setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
)) < 0)
1821 syslog(LOG_WARNING
, "data setsockopt (SO_REUSEADDR): %m");
1822 /* anchor socket to avoid multi-homing problems */
1823 data_source
= ctrl_addr
;
1824 data_source
.su_port
= htons(dataport
);
1826 for (tries
= 1; ; tries
++) {
1828 * We should loop here since it's possible that
1829 * another ftpd instance has passed this point and is
1830 * trying to open a data connection in active mode now.
1831 * Until the other connection is opened, we'll be getting
1832 * EADDRINUSE because no SOCK_STREAM sockets in the system
1833 * can share both local and remote addresses, localIP:20
1834 * and *:* in this case.
1836 if (bind(s
, (struct sockaddr
*)&data_source
,
1837 data_source
.su_len
) >= 0)
1839 if (errno
!= EADDRINUSE
|| tries
> 10)
1843 seteuid(pw
->pw_uid
);
1845 if (data_source
.su_family
== AF_INET
)
1847 on
= IPTOS_THROUGHPUT
;
1848 if (setsockopt(s
, IPPROTO_IP
, IP_TOS
, &on
, sizeof(int)) < 0)
1849 syslog(LOG_WARNING
, "data setsockopt (IP_TOS): %m");
1854 * Turn off push flag to keep sender TCP from sending short packets
1855 * at the boundaries of each write().
1858 if (setsockopt(s
, IPPROTO_TCP
, TCP_NOPUSH
, &on
, sizeof on
) < 0)
1859 syslog(LOG_WARNING
, "data setsockopt (TCP_NOPUSH): %m");
1861 return (fdopen(s
, mode
));
1863 /* Return the real value of errno (close may change it) */
1865 seteuid(pw
->pw_uid
);
1872 dataconn(char *name
, off_t size
, char *mode
)
1876 int retry
= 0, tos
, conerrno
;
1881 snprintf(sizebuf
, sizeof(sizebuf
),
1882 " (%jd bytes)", (intmax_t)size
);
1886 union sockunion from
;
1887 socklen_t fromlen
= ctrl_addr
.su_len
;
1889 struct timeval timeout
;
1893 FD_SET(pdata
, &set
);
1895 timeout
.tv_usec
= 0;
1896 timeout
.tv_sec
= 120;
1899 * Granted a socket is in the blocking I/O mode,
1900 * accept() will block after a successful select()
1901 * if the selected connection dies in between.
1902 * Therefore set the non-blocking I/O flag here.
1904 if ((flags
= fcntl(pdata
, F_GETFL
, 0)) == -1 ||
1905 fcntl(pdata
, F_SETFL
, flags
| O_NONBLOCK
) == -1)
1907 if (select(pdata
+1, &set
, NULL
, NULL
, &timeout
) <= 0 ||
1908 (s
= accept(pdata
, (struct sockaddr
*) &from
, &fromlen
)) < 0)
1913 * Unset the inherited non-blocking I/O flag
1914 * on the child socket so stdio can work on it.
1916 if ((flags
= fcntl(pdata
, F_GETFL
, 0)) == -1 ||
1917 fcntl(pdata
, F_SETFL
, flags
& ~O_NONBLOCK
) == -1)
1920 if (from
.su_family
== AF_INET
)
1922 tos
= IPTOS_THROUGHPUT
;
1923 if (setsockopt(s
, IPPROTO_IP
, IP_TOS
, &tos
, sizeof(int)) < 0)
1924 syslog(LOG_WARNING
, "pdata setsockopt (IP_TOS): %m");
1927 reply(150, "Opening %s mode data connection for '%s'%s.",
1928 type
== TYPE_A
? "ASCII" : "BINARY", name
, sizebuf
);
1929 return (fdopen(pdata
, mode
));
1931 reply(425, "Can't open data connection.");
1937 reply(125, "Using existing data connection for '%s'%s.",
1940 return (fdopen(data
, mode
));
1943 data_dest
= his_addr
;
1946 file
= getdatasock(mode
);
1948 char hostbuf
[NI_MAXHOST
], portbuf
[NI_MAXSERV
];
1950 if (getnameinfo((struct sockaddr
*)&data_source
,
1952 hostbuf
, sizeof(hostbuf
) - 1,
1953 portbuf
, sizeof(portbuf
) - 1,
1954 NI_NUMERICHOST
|NI_NUMERICSERV
))
1955 *hostbuf
= *portbuf
= 0;
1956 hostbuf
[sizeof(hostbuf
) - 1] = 0;
1957 portbuf
[sizeof(portbuf
) - 1] = 0;
1958 reply(425, "Can't create data socket (%s,%s): %s.",
1959 hostbuf
, portbuf
, strerror(errno
));
1962 data
= fileno(file
);
1964 if (connect(data
, (struct sockaddr
*)&data_dest
,
1965 data_dest
.su_len
) == 0)
1970 if (conerrno
== EADDRINUSE
) {
1976 } while (retry
<= swaitmax
);
1977 if (conerrno
!= 0) {
1978 reply(425, "Can't build data connection: %s.",
1979 strerror(conerrno
));
1982 reply(150, "Opening %s mode data connection for '%s'%s.",
1983 type
== TYPE_A
? "ASCII" : "BINARY", name
, sizebuf
);
1988 * A helper macro to avoid code duplication
1989 * in send_data() and receive_data().
1991 * XXX We have to block SIGURG during putc() because BSD stdio
1992 * is unable to restart interrupted write operations and hence
1993 * the entire buffer contents will be lost as soon as a write()
1994 * call indicates EINTR to stdio.
1996 #define FTPD_PUTC(ch, file, label) \
2002 ret = putc((ch), (file)); \
2004 CHECKOOB(return (-1)) \
2005 else if (ferror(file)) \
2008 } while (ret == EOF); \
2012 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2013 * encapsulation of the data subject to Mode, Structure, and Type.
2015 * NB: Form isn't handled.
2018 send_data(FILE *instr
, FILE *outstr
, size_t blksize
, off_t filesize
, int isreg
)
2020 int c
, cp
, filefd
, netfd
;
2031 CHECKOOB(return (-1))
2032 else if (c
== EOF
&& ferror(instr
))
2035 if (ferror(instr
)) { /* resume after OOB */
2039 if (feof(instr
)) /* EOF */
2041 syslog(LOG_ERR
, "Internal: impossible condition"
2042 " on file after getc()");
2045 if (c
== '\n' && cp
!= '\r') {
2046 FTPD_PUTC('\r', outstr
, data_err
);
2049 FTPD_PUTC(c
, outstr
, data_err
);
2053 #ifdef notyet /* BSD stdio isn't ready for that */
2054 while (fflush(outstr
) == EOF
) {
2055 CHECKOOB(return (-1))
2063 if (fflush(outstr
) == EOF
)
2066 reply(226, "Transfer complete.");
2072 * isreg is only set if we are not doing restart and we
2073 * are sending a regular file
2075 netfd
= fileno(outstr
);
2076 filefd
= fileno(instr
);
2079 char *msg
= "Transfer complete.";
2085 while (filesize
> 0) {
2086 err
= sendfile(filefd
, netfd
, offset
, 0,
2089 * Calculate byte_count before OOB processing.
2090 * It can be used in myoob() later.
2095 CHECKOOB(return (-1))
2096 else if (err
== -1) {
2097 if (errno
!= EINTR
&&
2098 cnt
== 0 && offset
== 0)
2102 if (err
== -1) /* resume after OOB */
2105 * We hit the EOF prematurely.
2106 * Perhaps the file was externally truncated.
2109 msg
= "Transfer finished due to "
2110 "premature end of file.";
2115 reply(226, "%s", msg
);
2120 if ((buf
= malloc(blksize
)) == NULL
) {
2122 reply(451, "Ran out of memory.");
2130 cnt
= read(filefd
, buf
, blksize
);
2131 CHECKOOB(free(buf
); return (-1))
2136 if (cnt
< 0) /* resume after OOB */
2138 if (cnt
== 0) /* EOF */
2140 for (len
= cnt
, bp
= buf
; len
> 0;) {
2141 cnt
= write(netfd
, bp
, len
);
2142 CHECKOOB(free(buf
); return (-1))
2156 reply(226, "Transfer complete.");
2160 reply(550, "Unimplemented TYPE %d in send_data.", type
);
2166 perror_reply(426, "Data connection");
2171 perror_reply(551, "Error on input file");
2176 * Transfer data from peer to "outstr" using the appropriate encapulation of
2177 * the data subject to Mode, Structure, and Type.
2179 * N.B.: Form isn't handled.
2182 receive_data(FILE *instr
, FILE *outstr
)
2198 cnt
= read(fileno(instr
), buf
, sizeof(buf
));
2199 CHECKOOB(return (-1))
2202 if (cnt
< 0) /* resume after OOB */
2204 if (cnt
== 0) /* EOF */
2206 for (len
= cnt
, bp
= buf
; len
> 0;) {
2207 cnt
= write(fileno(outstr
), bp
, len
);
2208 CHECKOOB(return (-1))
2223 reply(553, "TYPE E not implemented.");
2230 CHECKOOB(return (-1))
2231 else if (c
== EOF
&& ferror(instr
))
2233 if (c
== EOF
&& ferror(instr
)) { /* resume after OOB */
2240 FTPD_PUTC('\r', outstr
, file_err
);
2250 /* Check for EOF here in order not to lose last \r. */
2252 if (feof(instr
)) /* EOF */
2254 syslog(LOG_ERR
, "Internal: impossible condition"
2255 " on data stream after getc()");
2260 FTPD_PUTC(c
, outstr
, file_err
);
2263 #ifdef notyet /* BSD stdio isn't ready for that */
2264 while (fflush(outstr
) == EOF
) {
2265 CHECKOOB(return (-1))
2273 if (fflush(outstr
) == EOF
)
2278 "WARNING! %d bare linefeeds received in ASCII mode.",
2280 printf(" File may not have transferred correctly.\r\n");
2285 reply(550, "Unimplemented TYPE %d in receive_data.", type
);
2291 perror_reply(426, "Data connection");
2296 perror_reply(452, "Error writing to file");
2301 statfilecmd(char *filename
)
2306 char line
[LINE_MAX
];
2309 code
= lstat(filename
, &st
) == 0 && S_ISDIR(st
.st_mode
) ? 212 : 213;
2310 snprintf(line
, sizeof(line
), _PATH_LS
" -lgA %s", filename
);
2311 fin
= ftpd_popen(line
, "r");
2312 lreply(code
, "Status of %s:", filename
);
2314 while ((c
= getc(fin
)) != EOF
) {
2316 if (ferror(stdout
)){
2317 perror_reply(421, "Control connection");
2323 perror_reply(551, filename
);
2330 * RFC 959 says neutral text should be prepended before
2331 * a leading 3-digit number followed by whitespace, but
2332 * many ftp clients can be confused by any leading digits,
2333 * as a matter of fact.
2335 if (atstart
&& isdigit(c
))
2338 atstart
= (c
== '\n');
2341 reply(code
, "End of status.");
2347 union sockunion
*su
;
2349 char hname
[NI_MAXHOST
];
2353 lreply(211, "%s FTP server status:", hostname
);
2354 printf(" %s\r\n", version
);
2356 lreply(211, "FTP server status:");
2357 printf(" Connected to %s", remotehost
);
2358 if (!getnameinfo((struct sockaddr
*)&his_addr
, his_addr
.su_len
,
2359 hname
, sizeof(hname
) - 1, NULL
, 0, NI_NUMERICHOST
)) {
2360 hname
[sizeof(hname
) - 1] = 0;
2361 if (strcmp(hname
, remotehost
) != 0)
2362 printf(" (%s)", hname
);
2367 printf(" Logged in anonymously\r\n");
2369 printf(" Logged in as %s\r\n", pw
->pw_name
);
2370 } else if (askpasswd
)
2371 printf(" Waiting for password\r\n");
2373 printf(" Waiting for user name\r\n");
2374 printf(" TYPE: %s", typenames
[type
]);
2375 if (type
== TYPE_A
|| type
== TYPE_E
)
2376 printf(", FORM: %s", formnames
[form
]);
2379 printf(" %d", CHAR_BIT
);
2381 printf(" %d", bytesize
); /* need definition! */
2383 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2384 strunames
[stru
], modenames
[mode
]);
2386 printf(" Data connection open\r\n");
2387 else if (pdata
!= -1) {
2391 } else if (usedefault
== 0) {
2395 #define UC(b) (((int) b) & 0xff)
2397 printf(" EPSV only mode (EPSV ALL)\r\n");
2402 if (su
->su_family
== AF_INET
) {
2403 a
= (u_char
*) &su
->su_sin
.sin_addr
;
2404 p
= (u_char
*) &su
->su_sin
.sin_port
;
2405 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2406 ispassive
? "PASV" : "PORT",
2407 UC(a
[0]), UC(a
[1]), UC(a
[2]), UC(a
[3]),
2408 UC(p
[0]), UC(p
[1]));
2415 switch (su
->su_family
) {
2417 a
= (u_char
*) &su
->su_sin
.sin_addr
;
2418 p
= (u_char
*) &su
->su_sin
.sin_port
;
2419 alen
= sizeof(su
->su_sin
.sin_addr
);
2423 a
= (u_char
*) &su
->su_sin6
.sin6_addr
;
2424 p
= (u_char
*) &su
->su_sin6
.sin6_port
;
2425 alen
= sizeof(su
->su_sin6
.sin6_addr
);
2433 printf(" %s (%d,%d,", ispassive
? "LPSV" : "LPRT",
2435 for (i
= 0; i
< alen
; i
++)
2436 printf("%d,", UC(a
[i
]));
2437 printf("%d,%d,%d)\r\n", 2, UC(p
[0]), UC(p
[1]));
2446 switch (su
->su_family
) {
2458 union sockunion tmp
;
2461 if (tmp
.su_family
== AF_INET6
)
2462 tmp
.su_sin6
.sin6_scope_id
= 0;
2463 if (!getnameinfo((struct sockaddr
*)&tmp
, tmp
.su_len
,
2464 hname
, sizeof(hname
) - 1, NULL
, 0,
2466 hname
[sizeof(hname
) - 1] = 0;
2467 printf(" %s |%d|%s|%d|\r\n",
2468 ispassive
? "EPSV" : "EPRT",
2469 af
, hname
, htons(tmp
.su_port
));
2475 printf(" No data connection\r\n");
2476 reply(211, "End of status.");
2483 reply(451, "Error in server: %s", s
);
2484 reply(221, "Closing connection due to server error.");
2490 reply(int n
, const char *fmt
, ...)
2501 syslog(LOG_DEBUG
, "<--- %d ", n
);
2503 vsyslog(LOG_DEBUG
, fmt
, ap
);
2509 lreply(int n
, const char *fmt
, ...)
2520 syslog(LOG_DEBUG
, "<--- %d- ", n
);
2522 vsyslog(LOG_DEBUG
, fmt
, ap
);
2531 reply(250, "%s command successful.", s
);
2538 reply(502, "%s command not implemented.", s
);
2547 if ((cp
= strchr(cbuf
,'\n')))
2549 reply(500, "%s: command not understood.", cbuf
);
2557 LOGCMD("delete", name
);
2558 if (lstat(name
, &st
) < 0) {
2559 perror_reply(550, name
);
2562 if (S_ISDIR(st
.st_mode
)) {
2563 if (rmdir(name
) < 0) {
2564 perror_reply(550, name
);
2569 if (guest
&& noguestmod
) {
2570 reply(550, "Operation not permitted.");
2573 if (unlink(name
) < 0) {
2574 perror_reply(550, name
);
2585 if (chdir(path
) < 0)
2586 perror_reply(550, path
);
2596 LOGCMD("mkdir", name
);
2597 if (guest
&& noguestmkd
)
2598 reply(550, "Operation not permitted.");
2599 else if (mkdir(name
, 0777) < 0)
2600 perror_reply(550, name
);
2602 if ((s
= doublequote(name
)) == NULL
)
2603 fatalerror("Ran out of memory.");
2604 reply(257, "\"%s\" directory created.", s
);
2610 removedir(char *name
)
2613 LOGCMD("rmdir", name
);
2614 if (rmdir(name
) < 0)
2615 perror_reply(550, name
);
2623 char *s
, path
[MAXPATHLEN
+ 1];
2625 if (getcwd(path
, sizeof(path
)) == NULL
)
2626 perror_reply(550, "Get current directory");
2628 if ((s
= doublequote(path
)) == NULL
)
2629 fatalerror("Ran out of memory.");
2630 reply(257, "\"%s\" is current directory.", s
);
2636 renamefrom(char *name
)
2640 if (guest
&& noguestmod
) {
2641 reply(550, "Operation not permitted.");
2644 if (lstat(name
, &st
) < 0) {
2645 perror_reply(550, name
);
2648 reply(350, "File exists, ready for destination name.");
2653 renamecmd(char *from
, char *to
)
2657 LOGCMD2("rename", from
, to
);
2659 if (guest
&& (stat(to
, &st
) == 0)) {
2660 reply(550, "%s: permission denied.", to
);
2664 if (rename(from
, to
) < 0)
2665 perror_reply(550, "rename");
2671 dolog(struct sockaddr
*who
)
2673 char who_name
[NI_MAXHOST
];
2675 realhostname_sa(remotehost
, sizeof(remotehost
) - 1, who
, who
->sa_len
);
2676 remotehost
[sizeof(remotehost
) - 1] = 0;
2677 if (getnameinfo(who
, who
->sa_len
,
2678 who_name
, sizeof(who_name
) - 1, NULL
, 0, NI_NUMERICHOST
))
2680 who_name
[sizeof(who_name
) - 1] = 0;
2683 #ifdef VIRTUAL_HOSTING
2684 if (thishost
!= firsthost
)
2685 snprintf(proctitle
, sizeof(proctitle
), "%s: connected (to %s)",
2686 remotehost
, hostname
);
2689 snprintf(proctitle
, sizeof(proctitle
), "%s: connected",
2691 setproctitle("%s", proctitle
);
2692 #endif /* SETPROCTITLE */
2695 #ifdef VIRTUAL_HOSTING
2696 if (thishost
!= firsthost
)
2697 syslog(LOG_INFO
, "connection from %s (%s) to %s",
2698 remotehost
, who_name
, hostname
);
2701 syslog(LOG_INFO
, "connection from %s (%s)",
2702 remotehost
, who_name
);
2707 * Record logout in wtmp file
2708 * and exit with supplied status.
2711 dologout(int status
)
2714 if (logged_in
&& dowtmp
) {
2716 ftpd_logwtmp(ttyline
, "", NULL
);
2718 /* beware of flushing buffers after a SIGPIPE */
2736 syslog(LOG_ERR
, "Internal: maskurg() while no transfer");
2741 sigaddset(&sset
, SIGURG
);
2742 sigprocmask(flag
? SIG_BLOCK
: SIG_UNBLOCK
, &sset
, NULL
);
2752 syslog(LOG_ERR
, "Internal: flagxfer(1): "
2753 "transfer already under way");
2759 syslog(LOG_ERR
, "Internal: flagxfer(0): "
2760 "no active transfer");
2767 * Returns 0 if OK to resume or -1 if abort requested.
2776 syslog(LOG_ERR
, "Internal: myoob() while no transfer");
2780 ret
= get_line(cp
, 7, stdin
);
2782 reply(221, "You could at least say goodbye.");
2784 } else if (ret
== -2) {
2785 /* Ignore truncated command. */
2789 if (strcmp(cp
, "ABOR\r\n") == 0) {
2791 reply(426, "Transfer aborted. Data connection closed.");
2792 reply(226, "Abort successful.");
2795 if (strcmp(cp
, "STAT\r\n") == 0) {
2797 if (file_size
!= -1)
2798 reply(213, "Status: %jd of %jd bytes transferred.",
2799 (intmax_t)byte_count
, (intmax_t)file_size
);
2801 reply(213, "Status: %jd bytes transferred.",
2802 (intmax_t)byte_count
);
2808 * Note: a response of 425 is not mentioned as a possible response to
2809 * the PASV command in RFC959. However, it has been blessed as
2810 * a legitimate response by Jon Postel in a telephone conversation
2811 * with Rick Adams on 25 Jan 89.
2820 if (pdata
>= 0) /* close old port if one set */
2823 pdata
= socket(ctrl_addr
.su_family
, SOCK_STREAM
, 0);
2825 perror_reply(425, "Can't open passive connection");
2829 if (setsockopt(pdata
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
)) < 0)
2830 syslog(LOG_WARNING
, "pdata setsockopt (SO_REUSEADDR): %m");
2835 if (ctrl_addr
.su_family
== AF_INET
) {
2836 on
= restricted_data_ports
? IP_PORTRANGE_HIGH
2837 : IP_PORTRANGE_DEFAULT
;
2839 if (setsockopt(pdata
, IPPROTO_IP
, IP_PORTRANGE
,
2840 &on
, sizeof(on
)) < 0)
2844 #ifdef IPV6_PORTRANGE
2845 if (ctrl_addr
.su_family
== AF_INET6
) {
2846 on
= restricted_data_ports
? IPV6_PORTRANGE_HIGH
2847 : IPV6_PORTRANGE_DEFAULT
;
2849 if (setsockopt(pdata
, IPPROTO_IPV6
, IPV6_PORTRANGE
,
2850 &on
, sizeof(on
)) < 0)
2855 pasv_addr
= ctrl_addr
;
2856 pasv_addr
.su_port
= 0;
2857 if (bind(pdata
, (struct sockaddr
*)&pasv_addr
, pasv_addr
.su_len
) < 0)
2860 seteuid(pw
->pw_uid
);
2862 len
= sizeof(pasv_addr
);
2863 if (getsockname(pdata
, (struct sockaddr
*) &pasv_addr
, &len
) < 0)
2865 if (listen(pdata
, 1) < 0)
2867 if (pasv_addr
.su_family
== AF_INET
)
2868 a
= (char *) &pasv_addr
.su_sin
.sin_addr
;
2869 else if (pasv_addr
.su_family
== AF_INET6
&&
2870 IN6_IS_ADDR_V4MAPPED(&pasv_addr
.su_sin6
.sin6_addr
))
2871 a
= (char *) &pasv_addr
.su_sin6
.sin6_addr
.s6_addr
[12];
2875 p
= (char *) &pasv_addr
.su_port
;
2877 #define UC(b) (((int) b) & 0xff)
2879 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a
[0]),
2880 UC(a
[1]), UC(a
[2]), UC(a
[3]), UC(p
[0]), UC(p
[1]));
2884 seteuid(pw
->pw_uid
);
2887 perror_reply(425, "Can't open passive connection");
2892 * Long Passive defined in RFC 1639.
2893 * 228 Entering Long Passive Mode
2894 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2898 long_passive(char *cmd
, int pf
)
2904 if (pdata
>= 0) /* close old port if one set */
2907 if (pf
!= PF_UNSPEC
) {
2908 if (ctrl_addr
.su_family
!= pf
) {
2909 switch (ctrl_addr
.su_family
) {
2922 * only EPRT/EPSV ready clients will understand this
2924 if (strcmp(cmd
, "EPSV") == 0 && pf
) {
2925 reply(522, "Network protocol mismatch, "
2928 reply(501, "Network protocol mismatch."); /*XXX*/
2934 pdata
= socket(ctrl_addr
.su_family
, SOCK_STREAM
, 0);
2936 perror_reply(425, "Can't open passive connection");
2940 if (setsockopt(pdata
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
)) < 0)
2941 syslog(LOG_WARNING
, "pdata setsockopt (SO_REUSEADDR): %m");
2945 pasv_addr
= ctrl_addr
;
2946 pasv_addr
.su_port
= 0;
2947 len
= pasv_addr
.su_len
;
2950 if (ctrl_addr
.su_family
== AF_INET
) {
2951 on
= restricted_data_ports
? IP_PORTRANGE_HIGH
2952 : IP_PORTRANGE_DEFAULT
;
2954 if (setsockopt(pdata
, IPPROTO_IP
, IP_PORTRANGE
,
2955 &on
, sizeof(on
)) < 0)
2959 #ifdef IPV6_PORTRANGE
2960 if (ctrl_addr
.su_family
== AF_INET6
) {
2961 on
= restricted_data_ports
? IPV6_PORTRANGE_HIGH
2962 : IPV6_PORTRANGE_DEFAULT
;
2964 if (setsockopt(pdata
, IPPROTO_IPV6
, IPV6_PORTRANGE
,
2965 &on
, sizeof(on
)) < 0)
2970 if (bind(pdata
, (struct sockaddr
*)&pasv_addr
, len
) < 0)
2973 seteuid(pw
->pw_uid
);
2975 if (getsockname(pdata
, (struct sockaddr
*) &pasv_addr
, &len
) < 0)
2977 if (listen(pdata
, 1) < 0)
2980 #define UC(b) (((int) b) & 0xff)
2982 if (strcmp(cmd
, "LPSV") == 0) {
2983 p
= (char *)&pasv_addr
.su_port
;
2984 switch (pasv_addr
.su_family
) {
2986 a
= (char *) &pasv_addr
.su_sin
.sin_addr
;
2989 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2990 4, 4, UC(a
[0]), UC(a
[1]), UC(a
[2]), UC(a
[3]),
2991 2, UC(p
[0]), UC(p
[1]));
2994 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr
.su_sin6
.sin6_addr
)) {
2995 a
= (char *) &pasv_addr
.su_sin6
.sin6_addr
.s6_addr
[12];
2998 a
= (char *) &pasv_addr
.su_sin6
.sin6_addr
;
3000 "Entering Long Passive Mode "
3001 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3002 6, 16, UC(a
[0]), UC(a
[1]), UC(a
[2]), UC(a
[3]),
3003 UC(a
[4]), UC(a
[5]), UC(a
[6]), UC(a
[7]),
3004 UC(a
[8]), UC(a
[9]), UC(a
[10]), UC(a
[11]),
3005 UC(a
[12]), UC(a
[13]), UC(a
[14]), UC(a
[15]),
3006 2, UC(p
[0]), UC(p
[1]));
3009 } else if (strcmp(cmd
, "EPSV") == 0) {
3010 switch (pasv_addr
.su_family
) {
3013 reply(229, "Entering Extended Passive Mode (|||%d|)",
3014 ntohs(pasv_addr
.su_port
));
3018 /* more proper error code? */
3022 seteuid(pw
->pw_uid
);
3025 perror_reply(425, "Can't open passive connection");
3030 * Generate unique name for file with basename "local"
3031 * and open the file in order to avoid possible races.
3032 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3033 * Return descriptor to the file, set "name" to its name.
3035 * Generates failure reply on error.
3038 guniquefd(char *local
, char **name
)
3040 static char new[MAXPATHLEN
];
3046 cp
= strrchr(local
, '/');
3049 if (stat(cp
? local
: ".", &st
) < 0) {
3050 perror_reply(553, cp
? local
: ".");
3055 * Let not overwrite dirname with counter suffix.
3057 * In this extreme case dot won't be put in front of suffix.
3059 if (strlen(local
) > sizeof(new) - 4) {
3060 reply(553, "Pathname too long.");
3065 /* -4 is for the .nn<null> we put on the end below */
3066 snprintf(new, sizeof(new) - 4, "%s", local
);
3067 cp
= new + strlen(new);
3069 * Don't generate dotfile unless requested explicitly.
3070 * This covers the case when basename gets truncated off
3073 if (cp
> new && cp
[-1] != '/')
3075 for (count
= 0; count
< 100; count
++) {
3076 /* At count 0 try unmodified name */
3078 sprintf(cp
, "%d", count
);
3079 if ((fd
= open(count
? new : local
,
3080 O_RDWR
| O_CREAT
| O_EXCL
, 0666)) >= 0) {
3081 *name
= count
? new : local
;
3084 if (errno
!= EEXIST
) {
3085 perror_reply(553, count
? new : local
);
3089 reply(452, "Unique file name cannot be created.");
3094 * Format and send reply containing system error number.
3097 perror_reply(int code
, char *string
)
3100 reply(code
, "%s: %s.", string
, strerror(errno
));
3103 static char *onefile
[] = {
3109 send_file_list(char *whichf
)
3115 char **dirlist
, *dirname
;
3120 if (strpbrk(whichf
, "~{[*?") != NULL
) {
3121 int flags
= GLOB_BRACE
|GLOB_NOCHECK
|GLOB_TILDE
;
3123 memset(&gl
, 0, sizeof(gl
));
3124 gl
.gl_matchc
= MAXGLOBARGS
;
3125 /*flags |= GLOB_LIMIT;*/
3127 if (glob(whichf
, flags
, 0, &gl
)) {
3128 reply(550, "No matching files found.");
3130 } else if (gl
.gl_pathc
== 0) {
3132 perror_reply(550, whichf
);
3135 dirlist
= gl
.gl_pathv
;
3137 onefile
[0] = whichf
;
3142 while ((dirname
= *dirlist
++)) {
3143 if (stat(dirname
, &st
) < 0) {
3145 * If user typed "ls -l", etc, and the client
3146 * used NLST, do what the user meant.
3148 if (dirname
[0] == '-' && *dirlist
== NULL
&&
3150 retrieve(_PATH_LS
" %s", dirname
);
3152 perror_reply(550, whichf
);
3156 if (S_ISREG(st
.st_mode
)) {
3158 dout
= dataconn("file list", -1, "w");
3164 fprintf(dout
, "%s%s\n", dirname
,
3165 type
== TYPE_A
? "\r" : "");
3169 byte_count
+= strlen(dirname
) +
3170 (type
== TYPE_A
? 2 : 1);
3171 CHECKOOB(goto abrt
);
3173 } else if (!S_ISDIR(st
.st_mode
))
3176 if ((dirp
= opendir(dirname
)) == NULL
)
3179 while ((dir
= readdir(dirp
)) != NULL
) {
3180 char nbuf
[MAXPATHLEN
];
3182 CHECKOOB(goto abrt
);
3184 if (strcmp(dir
->d_name
, ".") == 0)
3186 if (strcmp(dir
->d_name
, "..") == 0)
3189 snprintf(nbuf
, sizeof(nbuf
),
3190 "%s/%s", dirname
, dir
->d_name
);
3193 * We have to do a stat to insure it's
3194 * not a directory or special file.
3196 if (simple
|| (stat(nbuf
, &st
) == 0 &&
3197 S_ISREG(st
.st_mode
))) {
3199 dout
= dataconn("file list", -1, "w");
3205 if (nbuf
[0] == '.' && nbuf
[1] == '/')
3206 fprintf(dout
, "%s%s\n", &nbuf
[2],
3207 type
== TYPE_A
? "\r" : "");
3209 fprintf(dout
, "%s%s\n", nbuf
,
3210 type
== TYPE_A
? "\r" : "");
3214 byte_count
+= strlen(nbuf
) +
3215 (type
== TYPE_A
? 2 : 1);
3216 CHECKOOB(goto abrt
);
3224 reply(550, "No files found.");
3225 else if (ferror(dout
))
3226 data_err
: perror_reply(550, "Data connection");
3228 reply(226, "Transfer complete.");
3246 reapchild(int signo
)
3248 while (waitpid(-1, NULL
, WNOHANG
) > 0);
3252 appendf(char **strp
, char *fmt
, ...)
3258 vasprintf(&p
, fmt
, ap
);
3261 fatalerror("Ran out of memory.");
3266 asprintf(strp
, "%s%s", ostr
, p
);
3268 fatalerror("Ran out of memory.");
3274 logcmd(char *cmd
, char *file1
, char *file2
, off_t cnt
)
3277 char wd
[MAXPATHLEN
+ 1];
3282 if (getcwd(wd
, sizeof(wd
) - 1) == NULL
)
3283 strcpy(wd
, strerror(errno
));
3285 appendf(&msg
, "%s", cmd
);
3287 appendf(&msg
, " %s", file1
);
3289 appendf(&msg
, " %s", file2
);
3291 appendf(&msg
, " = %jd bytes", (intmax_t)cnt
);
3292 appendf(&msg
, " (wd: %s", wd
);
3293 if (guest
|| dochroot
)
3294 appendf(&msg
, "; chrooted");
3296 syslog(LOG_INFO
, "%s", msg
);
3301 logxfer(char *name
, off_t size
, time_t start
)
3303 char buf
[MAXPATHLEN
+ 1024];
3304 char path
[MAXPATHLEN
+ 1];
3309 if (realpath(name
, path
) == NULL
) {
3310 syslog(LOG_NOTICE
, "realpath failed on %s: %m", path
);
3313 snprintf(buf
, sizeof(buf
), "%.20s!%s!%s!%s!%jd!%ld\n",
3314 ctime(&now
)+4, ident
, remotehost
,
3315 path
, (intmax_t)size
,
3316 (long)(now
- start
+ (now
== start
)));
3317 write(statfd
, buf
, strlen(buf
));
3322 doublequote(char *s
)
3327 for (p
= s
, n
= 0; *p
; p
++)
3331 if ((s2
= malloc(p
- s
+ n
+ 1)) == NULL
)
3334 for (p
= s2
; *s
; s
++, p
++) {
3335 if ((*p
= *s
) == '"')
3343 /* setup server socket for specified address family */
3344 /* if af is PF_UNSPEC more than one socket may be returned */
3345 /* the returned list is dynamically allocated, so caller needs to free it */
3347 socksetup(int af
, char *bindname
, const char *bindport
)
3349 struct addrinfo hints
, *res
, *r
;
3350 int error
, maxs
, *s
, *socks
;
3353 memset(&hints
, 0, sizeof(hints
));
3354 hints
.ai_flags
= AI_PASSIVE
;
3355 hints
.ai_family
= af
;
3356 hints
.ai_socktype
= SOCK_STREAM
;
3357 error
= getaddrinfo(bindname
, bindport
, &hints
, &res
);
3359 syslog(LOG_ERR
, "%s", gai_strerror(error
));
3360 if (error
== EAI_SYSTEM
)
3361 syslog(LOG_ERR
, "%s", strerror(errno
));
3365 /* Count max number of sockets we may open */
3366 for (maxs
= 0, r
= res
; r
; r
= r
->ai_next
, maxs
++)
3368 socks
= malloc((maxs
+ 1) * sizeof(int));
3371 syslog(LOG_ERR
, "couldn't allocate memory for sockets");
3375 *socks
= 0; /* num of sockets counter at start of array */
3377 for (r
= res
; r
; r
= r
->ai_next
) {
3378 *s
= socket(r
->ai_family
, r
->ai_socktype
, r
->ai_protocol
);
3380 syslog(LOG_DEBUG
, "control socket: %m");
3383 if (setsockopt(*s
, SOL_SOCKET
, SO_REUSEADDR
,
3384 &on
, sizeof(on
)) < 0)
3386 "control setsockopt (SO_REUSEADDR): %m");
3387 if (r
->ai_family
== AF_INET6
) {
3388 if (setsockopt(*s
, IPPROTO_IPV6
, IPV6_V6ONLY
,
3389 &on
, sizeof(on
)) < 0)
3391 "control setsockopt (IPV6_V6ONLY): %m");
3393 if (bind(*s
, r
->ai_addr
, r
->ai_addrlen
) < 0) {
3394 syslog(LOG_DEBUG
, "control bind: %m");
3406 syslog(LOG_ERR
, "control socket: Couldn't bind to any socket");